<?php

/*
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

class MemcacheDriver {

    public $memcache;
    private bool $enabled;
    private string $server;
    private string $prefix;
    private int $port;
    private $dummycache;

    /**
     *
     * @param bool $enabled true to enable memcached, false to use non-persistent dummy cache
     * @param string $server
     * @param int $port
     * @param string $prefix Prefix to add to keys to avoid conflicts with other apps on same server
     */
    function __construct(bool $enabled = false, string $server = "127.0.0.1", int $port = 11211, string $prefix = "") {
        $this->enabled = $enabled;
        $this->server = $server;
        $this->port = $port;
        $this->prefix = $prefix;
        if ($enabled) {
            $this->memcache = new Memcached();
            $this->memcache->addServer($this->server, $this->port);
        }
        $this->dummycache = [];
    }

    /**
     * Check if the memcache is actually setup or if it's a dummy shim.
     * @return bool true if memcache is enabled, false if only dummy cache enabled
     */
    function enabled(): bool {
        return $this->enabled;
    }

    /**
     * Get the value for key.
     * @param string $key
     * @return value or false if not found
     */
    function get(string $key) {
        if ($this->enabled) {
            $key = $this->prefix . $key;
            return $this->memcache->get($key);
        } else {
            if (!empty($this->dummycache[$key])) {
                return $this->dummycache[$key];
            }
            return false;
        }
    }

    /**
     * Set the value of $key to $val
     * @param string $key
     * @param type $val
     * @param int $expires number of seconds (max 60*60*24*30) or UNIX timestamp for cache expiry
     * Default expiration of 0 means no expiration
     */
    function set(string $key, $val, int $expires = 0) {
        if ($expires < 0) {
            $expires = 0;
        }
        if ($this->enabled) {
            $key = $this->prefix . $key;
            $this->memcache->set($key, $val, $expires);
        } else {
            $this->dummycache[$key] = $val;
        }
    }

    /**
     * Get the cache key prefix string
     * @return string
     */
    function getPrefix(): string {
        return $this->prefix;
    }

    function getMemcached() {
        return $this->memcache;
    }

}
