PageRenderTime 48ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 0ms

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

https://gitlab.com/buitenzorg812/garapic.cms
PHP | 322 lines | 141 code | 35 blank | 146 comment | 11 complexity | 60db5ecfa22ae440f3bc0bd623f7a5b2 MD5 | raw file
  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 - 2016, 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 - 2016, British Columbia Institute of Technology (http://bcit.ca/)
  33. * @license http://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. );
  62. /**
  63. * Redis connection
  64. *
  65. * @var Redis
  66. */
  67. protected $_redis;
  68. // ------------------------------------------------------------------------
  69. /**
  70. * Class constructor
  71. *
  72. * Setup Redis
  73. *
  74. * Loads Redis config file if present. Will halt execution
  75. * if a Redis connection can't be established.
  76. *
  77. * @return void
  78. * @see Redis::connect()
  79. */
  80. public function __construct()
  81. {
  82. if ( ! $this->is_supported())
  83. {
  84. log_message('error', 'Cache: Failed to create Redis object; extension not loaded?');
  85. return;
  86. }
  87. $CI =& get_instance();
  88. if ($CI->config->load('redis', TRUE, TRUE))
  89. {
  90. $config = array_merge(self::$_default_config, $CI->config->item('redis'));
  91. }
  92. else
  93. {
  94. $config = self::$_default_config;
  95. }
  96. $this->_redis = new Redis();
  97. try
  98. {
  99. if ( ! $this->_redis->connect($config['host'], ($config['host'][0] === '/' ? 0 : $config['port']), $config['timeout']))
  100. {
  101. log_message('error', 'Cache: Redis connection failed. Check your configuration.');
  102. }
  103. if (isset($config['password']) && ! $this->_redis->auth($config['password']))
  104. {
  105. log_message('error', 'Cache: Redis authentication failed.');
  106. }
  107. }
  108. catch (RedisException $e)
  109. {
  110. log_message('error', 'Cache: Redis connection refused ('.$e->getMessage().')');
  111. }
  112. }
  113. // ------------------------------------------------------------------------
  114. /**
  115. * Get cache
  116. *
  117. * @param string $key Cache ID
  118. * @return mixed
  119. */
  120. public function get($key)
  121. {
  122. $data = $this->_redis->hMGet($key, array('__ci_type', '__ci_value'));
  123. if ( ! isset($data['__ci_type'], $data['__ci_value']) OR $data['__ci_value'] === FALSE)
  124. {
  125. return FALSE;
  126. }
  127. switch ($data['__ci_type'])
  128. {
  129. case 'array':
  130. case 'object':
  131. return unserialize($data['__ci_value']);
  132. case 'boolean':
  133. case 'integer':
  134. case 'double': // Yes, 'double' is returned and NOT 'float'
  135. case 'string':
  136. case 'NULL':
  137. return settype($data['__ci_value'], $data['__ci_type'])
  138. ? $data['__ci_value']
  139. : FALSE;
  140. case 'resource':
  141. default:
  142. return FALSE;
  143. }
  144. }
  145. // ------------------------------------------------------------------------
  146. /**
  147. * Save cache
  148. *
  149. * @param string $id Cache ID
  150. * @param mixed $data Data to save
  151. * @param int $ttl Time to live in seconds
  152. * @param bool $raw Whether to store the raw value (unused)
  153. * @return bool TRUE on success, FALSE on failure
  154. */
  155. public function save($id, $data, $ttl = 60, $raw = FALSE)
  156. {
  157. switch ($data_type = gettype($data))
  158. {
  159. case 'array':
  160. case 'object':
  161. $data = serialize($data);
  162. break;
  163. case 'boolean':
  164. case 'integer':
  165. case 'double': // Yes, 'double' is returned and NOT 'float'
  166. case 'string':
  167. case 'NULL':
  168. break;
  169. case 'resource':
  170. default:
  171. return FALSE;
  172. }
  173. if ( ! $this->_redis->hMSet($id, array('__ci_type' => $data_type, '__ci_value' => $data)))
  174. {
  175. return FALSE;
  176. }
  177. elseif ($ttl)
  178. {
  179. $this->_redis->expireAt($id, time() + $ttl);
  180. }
  181. return TRUE;
  182. }
  183. // ------------------------------------------------------------------------
  184. /**
  185. * Delete from cache
  186. *
  187. * @param string $key Cache key
  188. * @return bool
  189. */
  190. public function delete($key)
  191. {
  192. return ($this->_redis->delete($key) === 1);
  193. }
  194. // ------------------------------------------------------------------------
  195. /**
  196. * Increment a raw value
  197. *
  198. * @param string $id Cache ID
  199. * @param int $offset Step/value to add
  200. * @return mixed New value on success or FALSE on failure
  201. */
  202. public function increment($id, $offset = 1)
  203. {
  204. return $this->_redis->hIncrBy($id, 'data', $offset);
  205. }
  206. // ------------------------------------------------------------------------
  207. /**
  208. * Decrement a raw value
  209. *
  210. * @param string $id Cache ID
  211. * @param int $offset Step/value to reduce by
  212. * @return mixed New value on success or FALSE on failure
  213. */
  214. public function decrement($id, $offset = 1)
  215. {
  216. return $this->_redis->hIncrBy($id, 'data', -$offset);
  217. }
  218. // ------------------------------------------------------------------------
  219. /**
  220. * Clean cache
  221. *
  222. * @return bool
  223. * @see Redis::flushDB()
  224. */
  225. public function clean()
  226. {
  227. return $this->_redis->flushDB();
  228. }
  229. // ------------------------------------------------------------------------
  230. /**
  231. * Get cache driver info
  232. *
  233. * @param string $type Not supported in Redis.
  234. * Only included in order to offer a
  235. * consistent cache API.
  236. * @return array
  237. * @see Redis::info()
  238. */
  239. public function cache_info($type = NULL)
  240. {
  241. return $this->_redis->info();
  242. }
  243. // ------------------------------------------------------------------------
  244. /**
  245. * Get cache metadata
  246. *
  247. * @param string $key Cache key
  248. * @return array
  249. */
  250. public function get_metadata($key)
  251. {
  252. $value = $this->get($key);
  253. if ($value !== FALSE)
  254. {
  255. return array(
  256. 'expire' => time() + $this->_redis->ttl($key),
  257. 'data' => $value
  258. );
  259. }
  260. return FALSE;
  261. }
  262. // ------------------------------------------------------------------------
  263. /**
  264. * Check if Redis driver is supported
  265. *
  266. * @return bool
  267. */
  268. public function is_supported()
  269. {
  270. return extension_loaded('redis');
  271. }
  272. // ------------------------------------------------------------------------
  273. /**
  274. * Class destructor
  275. *
  276. * Closes the connection to Redis if present.
  277. *
  278. * @return void
  279. */
  280. public function __destruct()
  281. {
  282. if ($this->_redis)
  283. {
  284. $this->_redis->close();
  285. }
  286. }
  287. }