<?php
/*
* 项目: iOrange(橘子)
* 作者: 离家出走(yzxh24)
* Email: yzxh24@gmail.com
* 主页: www.iorange.cc
*/
/* vim: set ts=4 sw=4: */
require_once 'Abstract.php';
class CacheFile extends CacheAbstract
{
    protected $_defaultConfig = array(
        'encoding' => true,
        'depth' => 0,
        'umask' => 0777
    );

    public function __construct($cacheConfig)
    {
        if (empty($cacheConfig) || !is_array($cacheConfig))
        {
            throw new CacheException('文件缓存设置选项错误');
        }

        if (empty($cacheConfig['folder']))
        {
            throw new CacheException('缓存文件保存目录为空');
        }
        $this->_defaultConfig = array_merge($this->_defaultConfig, $cacheConfig);
    }

    public function get($key)
    {
        $cacheFile = $this->_getSaveFile($key);
        if (!is_file($cacheFile))
        {
            return false;
        }

        if(($time = @filemtime($cacheFile)) > time())
        {
            return unserialize(file_get_contents($cacheFile));
        }
        else if($time > 0)
        {
            $this->remove($key);
        }
        return false;
    }

    public function set($key, $data, $expire = 3600)
    {
        if (!is_writable($this->_defaultConfig['folder']))
        {
            throw new CacheException('请将' . $this->_defaultConfig['folder'] . '目录设置为可写');
        }
        $cacheFile = $this->_getSaveFile($key);
        if($expire<=0)
        {
            $expire=31536000; // 1 year
        }
        $expire += time();

        $data = serialize($data);
        if(@file_put_contents($cacheFile, $data, LOCK_EX) == strlen($data))
        {
            @chmod($cacheFile, 0777);
            return @touch($cacheFile, $expire);
        }
        else
        {
            return false;
        }
    }

    public function remove($key)
    {
        $cacheFile = $this->_getSaveFile($key);

        if (is_file($cacheFile))
        {
            @unlink($cacheFile);
        }
    }

    private function _getSaveFile($key)
    {
        if ($this->_defaultConfig['encoding'])
        {
            $fileName = 'cache_' . md5($key) . '.php';
        }
        else
        {
            $fileName = 'cache_' . $key . '.php';
        }

        $rootFolder = rtrim($this->_defaultConfig['folder'], '\\/');
        $rootFolder .= DIRECTORY_SEPARATOR;

        if ($this->_defaultConfig['depth'] > 0)
        {
            $hash = md5($fileName);
            $rootFolder .= 'cache_';
            for ($i =1; $i <= $this->_defaultConfig['depth']; $i++)
            {
                $rootFolder .= substr($hash, 0, $i) . DIRECTORY_SEPARATOR;
                if (!is_dir($rootFolder))
                {
                    mkdir($rootFolder);
                }
            }
        }

        return $rootFolder . $fileName;
    }
}