审查视图

simplewind/vendor/alipay_wap/lotusphp_runtime/StoreFile.php 2.3 KB
刘朕 authored
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125
<?php
class LtStoreFile implements LtStore
{
	public $storeDir;
	public $prefix = 'LtStore';
	public $useSerialize = false;
	static public $defaultStoreDir = "/tmp/LtStoreFile/";
	public function init()
	{
		/**
		 * 目录不存在和是否可写在调用add是测试
		 * @todo detect dir is exists and writable
		 */
		if (null == $this->storeDir)
		{
			$this->storeDir = self::$defaultStoreDir;
		}
		$this->storeDir = str_replace('\\', '/', $this->storeDir);
		$this->storeDir = rtrim($this->storeDir, '\\/') . '/';
	}

	/**
	 * 当key存在时:
	 * 如果没有过期, 不更新值, 返回 false
	 * 如果已经过期,   更新值, 返回 true
	 *
	 * @return bool
	 */
	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;
	}

	/**
	 * 删除不存在的key返回false
	 *
	 * @return bool
	 */
	public function del($key)
	{
		$file = $this->getFilePath($key);
		if (!is_file($file))
		{
			return false;
		}
		else
		{
			return @unlink($file);
		}
	}

	/**
	 * 取不存在的key返回false
	 * 已经过期返回false
	 *
	 * @return 成功返回数据,失败返回false
	 */
	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;
	}

	/**
	 * key不存在 返回false
	 * 不管有没有过期,都更新数据
	 *
	 * @return bool
	 */
	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';
	}
}