<?php
class LtStoreFile implements LtStore
{
	public $storeDir;
	public $prefix = 'LtStore';
	public $useSerialize = false;
	static public $defaultStoreDir = "/tmp/LtStoreFile/";
	public function init()
	{
		
		if (null == $this->storeDir)
		{
			$this->storeDir = self::$defaultStoreDir;
		}
		$this->storeDir = str_replace('\\', '/', $this->storeDir);
		$this->storeDir = rtrim($this->storeDir, '\\/') . '/';
	}
	
	public function add($key, $value)
	{
		$file = $this->getFilePath($key);
		$cachePath = pathinfo($file, PATHINFO_DIRNAME);
		if (!is_dir($cachePath))
		{
			if (!@mkdir($cachePath, 0777, true))
			{
				trigger_error("Can not create $cachePath");
			}
		}
		if (is_file($file))
		{
			return false;
		}
		if ($this->useSerialize)
		{
			$value = serialize($value);
		}
		$length = file_put_contents($file, '<?php exit;?>' . $value);
		return $length > 0 ? true : false;
	}
	
	public function del($key)
	{
		$file = $this->getFilePath($key);
		if (!is_file($file))
		{
			return false;
		}
		else
		{
			return @unlink($file);
		}
	}
	
	public function get($key)
	{
		$file = $this->getFilePath($key);
		if (!is_file($file))
		{
			return false;
		}
		$str = file_get_contents($file);
		$value = substr($str, 13);
		if ($this->useSerialize)
		{
			$value = unserialize($value);
		}
		return $value;
	}
	
	public function update($key, $value)
	{
		$file = $this->getFilePath($key);
		if (!is_file($file))
		{
			return false;
		}
		else
		{
			if ($this->useSerialize)
			{
				$value = serialize($value);
			}
			$length = file_put_contents($file, '<?php exit;?>' . $value);
			return $length > 0 ? true : false;
		}
	}
	public function getFilePath($key)
	{
		$token = md5($key);
		return $this->storeDir .
		$this->prefix . '/' .
		substr($token, 0, 2) .'/' .
		substr($token, 2, 2) . '/' .
		$token . '.php';
	}
}