PageRenderTime 58ms CodeModel.GetById 18ms RepoModel.GetById 1ms app.codeStats 0ms

/system/libraries/Cache/drivers/Cache_redis.php

http://github.com/EllisLab/CodeIgniter
PHP | 364 lines | 166 code | 42 blank | 156 comment | 18 complexity | 824bf6ffe634939bbbc397f454bc2670 MD5 | raw file
Possible License(s): CC-BY-SA-3.0
  1. <?php
  2. /**
  3. * CodeIgniter
  4. *
  5. * An open source application development framework for PHP
  6. *
  7. * This content is released under the MIT License (MIT)
  8. *
  9. * Copyright (c) 2014 - 2019, British Columbia Institute of Technology
  10. *
  11. * Permission is hereby granted, free of charge, to any person obtaining a copy
  12. * of this software and associated documentation files (the "Software"), to deal
  13. * in the Software without restriction, including without limitation the rights
  14. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  15. * copies of the Software, and to permit persons to whom the Software is
  16. * furnished to do so, subject to the following conditions:
  17. *
  18. * The above copyright notice and this permission notice shall be included in
  19. * all copies or substantial portions of the Software.
  20. *
  21. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  22. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  23. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  24. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  25. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  26. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  27. * THE SOFTWARE.
  28. *
  29. * @package CodeIgniter
  30. * @author EllisLab Dev Team
  31. * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (https://ellislab.com/)
  32. * @copyright Copyright (c) 2014 - 2019, British Columbia Institute of Technology (https://bcit.ca/)
  33. * @license https://opensource.org/licenses/MIT MIT License
  34. * @link https://codeigniter.com
  35. * @since Version 3.0.0
  36. * @filesource
  37. */
  38. defined('BASEPATH') OR exit('No direct script access allowed');
  39. /**
  40. * CodeIgniter Redis Caching Class
  41. *
  42. * @package CodeIgniter
  43. * @subpackage Libraries
  44. * @category Core
  45. * @author Anton Lindqvist <anton@qvister.se>
  46. * @link
  47. */
  48. class CI_Cache_redis extends CI_Driver
  49. {
  50. /**
  51. * Default config
  52. *
  53. * @static
  54. * @var array
  55. */
  56. protected static $_default_config = array(
  57. 'host' => '127.0.0.1',
  58. 'password' => NULL,
  59. 'port' => 6379,
  60. 'timeout' => 0,
  61. 'database' => 0
  62. );
  63. /**
  64. * Redis connection
  65. *
  66. * @var Redis
  67. */
  68. protected $_redis;
  69. /**
  70. * del()/delete() method name depending on phpRedis version
  71. *
  72. * @var string
  73. */
  74. protected static $_delete_name;
  75. /**
  76. * sRem()/sRemove() method name depending on phpRedis version
  77. *
  78. * @var string
  79. */
  80. protected static $_sRemove_name;
  81. // ------------------------------------------------------------------------
  82. /**
  83. * Class constructor
  84. *
  85. * Setup Redis
  86. *
  87. * Loads Redis config file if present. Will halt execution
  88. * if a Redis connection can't be established.
  89. *
  90. * @return void
  91. * @see Redis::connect()
  92. */
  93. public function __construct()
  94. {
  95. if ( ! $this->is_supported())
  96. {
  97. log_message('error', 'Cache: Failed to create Redis object; extension not loaded?');
  98. return;
  99. }
  100. if ( ! isset(static::$_delete_name, static::$_sRemove_name))
  101. {
  102. if (version_compare(phpversion('redis'), '5', '>='))
  103. {
  104. static::$_delete_name = 'del';
  105. static::$_sRemove_name = 'sRem';
  106. }
  107. else
  108. {
  109. static::$_delete_name = 'delete';
  110. static::$_sRemove_name = 'sRemove';
  111. }
  112. }
  113. $CI =& get_instance();
  114. if ($CI->config->load('redis', TRUE, TRUE))
  115. {
  116. $config = array_merge(self::$_default_config, $CI->config->item('redis'));
  117. }
  118. else
  119. {
  120. $config = self::$_default_config;
  121. }
  122. $this->_redis = new Redis();
  123. try
  124. {
  125. if ( ! $this->_redis->connect($config['host'], ($config['host'][0] === '/' ? 0 : $config['port']), $config['timeout']))
  126. {
  127. log_message('error', 'Cache: Redis connection failed. Check your configuration.');
  128. }
  129. if (isset($config['password']) && ! $this->_redis->auth($config['password']))
  130. {
  131. log_message('error', 'Cache: Redis authentication failed.');
  132. }
  133. if (isset($config['database']) && $config['database'] > 0 && ! $this->_redis->select($config['database']))
  134. {
  135. log_message('error', 'Cache: Redis select database failed.');
  136. }
  137. }
  138. catch (RedisException $e)
  139. {
  140. log_message('error', 'Cache: Redis connection refused ('.$e->getMessage().')');
  141. }
  142. }
  143. // ------------------------------------------------------------------------
  144. /**
  145. * Get cache
  146. *
  147. * @param string $key Cache ID
  148. * @return mixed
  149. */
  150. public function get($key)
  151. {
  152. $data = $this->_redis->hMGet($key, array('__ci_type', '__ci_value'));
  153. if ($value !== FALSE && $this->_redis->sIsMember('_ci_redis_serialized', $key))
  154. {
  155. return FALSE;
  156. }
  157. switch ($data['__ci_type'])
  158. {
  159. case 'array':
  160. case 'object':
  161. return unserialize($data['__ci_value']);
  162. case 'boolean':
  163. case 'integer':
  164. case 'double': // Yes, 'double' is returned and NOT 'float'
  165. case 'string':
  166. case 'NULL':
  167. return settype($data['__ci_value'], $data['__ci_type'])
  168. ? $data['__ci_value']
  169. : FALSE;
  170. case 'resource':
  171. default:
  172. return FALSE;
  173. }
  174. }
  175. // ------------------------------------------------------------------------
  176. /**
  177. * Save cache
  178. *
  179. * @param string $id Cache ID
  180. * @param mixed $data Data to save
  181. * @param int $ttl Time to live in seconds
  182. * @param bool $raw Whether to store the raw value (unused)
  183. * @return bool TRUE on success, FALSE on failure
  184. */
  185. public function save($id, $data, $ttl = 60, $raw = FALSE)
  186. {
  187. switch ($data_type = gettype($data))
  188. {
  189. case 'array':
  190. case 'object':
  191. $data = serialize($data);
  192. break;
  193. case 'boolean':
  194. case 'integer':
  195. case 'double': // Yes, 'double' is returned and NOT 'float'
  196. case 'string':
  197. case 'NULL':
  198. break;
  199. case 'resource':
  200. default:
  201. return FALSE;
  202. }
  203. if ( ! $this->_redis->hMSet($id, array('__ci_type' => $data_type, '__ci_value' => $data)))
  204. {
  205. return FALSE;
  206. }
  207. else
  208. {
  209. $this->_redis->{static::$_sRemove_name}('_ci_redis_serialized', $id);
  210. }
  211. return TRUE;
  212. }
  213. // ------------------------------------------------------------------------
  214. /**
  215. * Delete from cache
  216. *
  217. * @param string $key Cache key
  218. * @return bool
  219. */
  220. public function delete($key)
  221. {
  222. if ($this->_redis->{static::$_delete_name}($key) !== 1)
  223. {
  224. return FALSE;
  225. }
  226. $this->_redis->{static::$_sRemove_name}('_ci_redis_serialized', $key);
  227. return TRUE;
  228. }
  229. // ------------------------------------------------------------------------
  230. /**
  231. * Increment a raw value
  232. *
  233. * @param string $id Cache ID
  234. * @param int $offset Step/value to add
  235. * @return mixed New value on success or FALSE on failure
  236. */
  237. public function increment($id, $offset = 1)
  238. {
  239. return $this->_redis->incrBy($id, $offset);
  240. }
  241. // ------------------------------------------------------------------------
  242. /**
  243. * Decrement a raw value
  244. *
  245. * @param string $id Cache ID
  246. * @param int $offset Step/value to reduce by
  247. * @return mixed New value on success or FALSE on failure
  248. */
  249. public function decrement($id, $offset = 1)
  250. {
  251. return $this->_redis->decrBy($id, $offset);
  252. }
  253. // ------------------------------------------------------------------------
  254. /**
  255. * Clean cache
  256. *
  257. * @return bool
  258. * @see Redis::flushDB()
  259. */
  260. public function clean()
  261. {
  262. return $this->_redis->flushDB();
  263. }
  264. // ------------------------------------------------------------------------
  265. /**
  266. * Get cache driver info
  267. *
  268. * @param string $type Not supported in Redis.
  269. * Only included in order to offer a
  270. * consistent cache API.
  271. * @return array
  272. * @see Redis::info()
  273. */
  274. public function cache_info($type = NULL)
  275. {
  276. return $this->_redis->info();
  277. }
  278. // ------------------------------------------------------------------------
  279. /**
  280. * Get cache metadata
  281. *
  282. * @param string $key Cache key
  283. * @return array
  284. */
  285. public function get_metadata($key)
  286. {
  287. $value = $this->get($key);
  288. if ($value !== FALSE)
  289. {
  290. return array(
  291. 'expire' => time() + $this->_redis->ttl($key),
  292. 'data' => $value
  293. );
  294. }
  295. return FALSE;
  296. }
  297. // ------------------------------------------------------------------------
  298. /**
  299. * Check if Redis driver is supported
  300. *
  301. * @return bool
  302. */
  303. public function is_supported()
  304. {
  305. return extension_loaded('redis');
  306. }
  307. // ------------------------------------------------------------------------
  308. /**
  309. * Class destructor
  310. *
  311. * Closes the connection to Redis if present.
  312. *
  313. * @return void
  314. */
  315. public function __destruct()
  316. {
  317. if ($this->_redis)
  318. {
  319. $this->_redis->close();
  320. }
  321. }
  322. }