<?php
namespace Zeedhi\Framework\Cache\Type;

use Zeedhi\Framework\Cache\Cache;
use Zeedhi\Framework\Cache\Exception;

/**
 * Memcached implementation WITHOUT doctrine/cache
 * but preserving old method signatures for compatibility.
 */
class MemcachedImpl implements Cache
{
    /** @var \Memcached */
    protected $memcached;

    public function __construct(\Memcached $memcached)
    {
        $this->memcached = $memcached;
    }

    // -----------------------------------------------------
    //  Métodos Novos (implementação nativa)
    // -----------------------------------------------------

    public function save($key, $value, $lifeTime = 0)
    {
        return $this->doSave($key, $value, $lifeTime);
    }

    public function fetch($key)
    {
        $value = $this->doFetch($key);

        if ($value === false && $this->memcached->getResultCode() === \Memcached::RES_NOTFOUND) {
            throw Exception::valueNotFound($key);
        }

        return $value;
    }

    public function delete($key)
    {
        return $this->doDelete($key);
    }

    public function contains($key)
    {
        return $this->doContains($key);
    }

    // -----------------------------------------------------
    //  Métodos Antigos: simulando Doctrine MemcachedCache
    // -----------------------------------------------------

    /** Compatível com Doctrine\Common\Cache\MemcachedCache */
    public function getMemcached()
    {
        return $this->memcached;
    }

    /** Compatível com Doctrine\Common\Cache\MemcachedCache */
    public function setMemcached(\Memcached $memcached)
    {
        $this->memcached = $memcached;
    }

    /** Compatível com métodos protegidos antigos de Doctrine Cache */
    protected function doFetch($key)
    {
        return $this->memcached->get($key);
    }

    protected function doSave($key, $value, $lifeTime = 0)
    {
        return $this->memcached->set($key, $value, $lifeTime);
    }

    protected function doDelete($key)
    {
        return $this->memcached->delete($key);
    }

    protected function doContains($key)
    {
        $this->memcached->get($key);
        return $this->memcached->getResultCode() !== \Memcached::RES_NOTFOUND;
    }
}
