bootstrap /fuel/core/classes/cache/storage/redis.php

Language PHP Lines 491
MD5 Hash a90656f0b1255c38620c860fcdf979d0 Estimated Cost $7,525 (why?)
Repository https://bitbucket.org/codeyash/bootstrap.git View Raw File View Project SPDX
  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
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
<?php
/**
 * Part of the Fuel framework.
 *
 * @package    Fuel
 * @version    1.5
 * @author     Fuel Development Team
 * @license    MIT License
 * @copyright  2010 - 2013 Fuel Development Team
 * @link       http://fuelphp.com
 */

namespace Fuel\Core;



class Cache_Storage_Redis extends \Cache_Storage_Driver
{

	/**
	 * @const  string  Tag used for opening & closing cache properties
	 */
	const PROPS_TAG = 'Fuel_Cache_Properties';

	/**
	 * @var  array  driver specific configuration
	 */
	protected $config = array();

	/*
	 * @var  Redis  storage for the redis object
	 */
	protected $redis = false;

	public function __construct($identifier, $config)
	{
		parent::__construct($identifier, $config);

		$this->config = isset($config['redis']) ? $config['redis'] : array();

		// make sure we have a redis id
		$this->config['cache_id'] = $this->_validate_config('cache_id', isset($this->config['cache_id'])
			? $this->config['cache_id'] : 'fuel');

		// check for an expiration override
		$this->expiration = $this->_validate_config('expiration', isset($this->config['expiration'])
			? $this->config['expiration'] : $this->expiration);

		// make sure we have a redis database configured
		$this->config['database'] = $this->_validate_config('database', isset($this->config['database'])
			? $this->config['database'] : 'default');

		if ($this->redis === false)
		{
			// get the redis database instance
			try
			{
				$this->redis = \Redis::instance($this->config['database']);
			}
			catch (\Exception $e)
			{
				throw new \FuelException('Can not connect to the Redis engine. The error message says "'.$e->getMessage().'".');
			}

			// get the redis version
			preg_match('/redis_version:(.*?)\n/', $this->redis->info(), $info);
			if (version_compare(trim($info[1]), '1.2') < 0)
			{
				throw new \FuelException('Version 1.2 or higher of the Redis NoSQL engine is required to use the redis cache driver.');
			}
		}
	}

	/**
	 * Translates a given identifier to a valid redis key
	 *
	 * @param   string
	 * @return  string
	 */
	protected function identifier_to_key( $identifier )
	{
		return $this->config['cache_id'].':'.$identifier;
	}

	/**
	 * Prepend the cache properties
	 *
	 * @return string
	 */
	protected function prep_contents()
	{
		$properties = array(
			'created'          => $this->created,
			'expiration'       => $this->expiration,
			'dependencies'     => $this->dependencies,
			'content_handler'  => $this->content_handler
		);
		$properties = '{{'.static::PROPS_TAG.'}}'.json_encode($properties).'{{/'.static::PROPS_TAG.'}}';

		return $properties.$this->contents;
	}

	/**
	 * Remove the prepended cache properties and save them in class properties
	 *
	 * @param   string
	 * @throws  UnexpectedValueException
	 */
	protected function unprep_contents($payload)
	{
		$properties_end = strpos($payload, '{{/'.static::PROPS_TAG.'}}');
		if ($properties_end === FALSE)
		{
			throw new \UnexpectedValueException('Cache has bad formatting');
		}

		$this->contents = substr($payload, $properties_end + strlen('{{/'.static::PROPS_TAG.'}}'));
		$props = substr(substr($payload, 0, $properties_end), strlen('{{'.static::PROPS_TAG.'}}'));
		$props = json_decode($props, true);
		if ($props === NULL)
		{
			throw new \UnexpectedValueException('Cache properties retrieval failed');
		}

		$this->created          = $props['created'];
		$this->expiration       = is_null($props['expiration']) ? null : (int) ($props['expiration'] - time());
		$this->dependencies     = $props['dependencies'];
		$this->content_handler  = $props['content_handler'];
	}

	/**
	 * Check if other caches or files have been changed since cache creation
	 *
	 * @param   array
	 * @return  bool
	 */
	public function check_dependencies(array $dependencies)
	{
		foreach($dependencies as $dep)
		{
			// get the section name and identifier
			$sections = explode('.', $dep);
			if (count($sections) > 1)
			{
				$identifier = array_pop($sections);
				$sections = '.'.implode('.', $sections);

			}
			else
			{
				$identifier = $dep;
				$sections = '';
			}

			// get the cache index
			$index = $this->redis->get($this->config['cache_id'].':index:'.$sections);
			is_null($index) or $index = $this->_unserialize($index);

			// get the key from the index
			$key = isset($index[$identifier][0]) ? $index[$identifier] : false;

			// key found and newer?
			if ($key === false or $key[1] > $this->created)
			{
				return false;
			}
		}
		return true;
	}

	/**
	 * Delete Cache
	 */
	public function delete()
	{
		// get the key for the cache identifier
		$key = $this->_get_key(true);

		// delete the key from the redis server
		if ($key and $this->redis->del($key) === false)
		{
			// do something here?
		}

		$this->reset();
	}

	/**
	 * Purge all caches
	 *
	 * @param   limit purge to subsection
	 * @return  bool
	 */
	public function delete_all($section)
	{
		// determine the section index name
		$section = empty($section) ? '' : '.'.$section;

		// get the directory index
		$index = $this->redis->get($this->config['cache_id'].':dir:');
		is_null($index) or $index = $this->_unserialize($index);

		if (is_array($index))
		{
			if (!empty($section))
			{
				// limit the delete if we have a valid section
				$dirs = array();
				foreach ($index as $entry)
				{
					if ($entry == $section or strpos($entry, $section.'.') === 0)
					{
						$dirs[] = $entry;
					}
				}
			}
			else
			{
				// else delete the entire contents of the cache
				$dirs = $index;
			}

			// loop through the selected indexes
			foreach ($dirs as $dir)
			{
				// get the stored cache entries for this index
				$list = $this->redis->get($this->config['cache_id'].':index:'.$dir);
				if (is_null($list))
				{
					$list = array();
				}
				else
				{
					$list = $this->_unserialize($list);
				}

				// delete all stored keys
				foreach($list as $item)
				{
					$this->redis->del($item[0]);
				}

				// and delete the index itself
				$this->redis->del($this->config['cache_id'].':index:'.$dir);
			}

			// update the directory index
			$this->redis->set($this->config['cache_id'].':dir:', $this->_serialize(array_diff($index, $dirs)));
		}
	}

	/**
	 * Save a cache, this does the generic pre-processing
	 *
	 * @return  bool  success
	 */
	protected function _set()
	{
		// get the key for the cache identifier
		$key = $this->_get_key();

		// write the cache
		$this->redis->set($key, $this->prep_contents());
		if ( ! empty($this->expiration))
		{
			$this->redis->expireat($key, $this->expiration);
		}

		return true;
	}

	/**
	 * Load a cache, this does the generic post-processing
	 *
	 * @return  bool  success
	 */
	protected function _get()
	{
		// get the key for the cache identifier
		$key = $this->_get_key();

		// fetch the session data from the redis server
		$payload = $this->redis->get($key);
		try
		{
			$this->unprep_contents($payload);
		}
		catch (\UnexpectedValueException $e)
		{
			return false;
		}

		return true;
	}

	/**
	 * get's the memcached key belonging to the cache identifier
	 *
	 * @param   bool  if true, remove the key retrieved from the index
	 * @return  string
	 */
	private function _get_key($remove = false)
	{
		// get the section name and identifier
		$sections = explode('.', $this->identifier);
		if (count($sections) > 1)
		{
			$identifier = array_pop($sections);
			$sections = '.'.implode('.', $sections);
		}
		else
		{
			$identifier = $this->identifier;
			$sections = '';
		}

		// get the cache index
		$index = $this->redis->get($this->config['cache_id'].':index:'.$sections);
		is_null($index) or $index = $this->_unserialize($index);

		// get the key from the index
		$key = isset($index[$identifier][0]) ? $index[$identifier][0] : false;

		if ($remove === true)
		{
			if ( $key !== false )
			{
				unset($index[$identifier]);
				$this->redis->set($this->config['cache_id'].':index:'.$sections, $this->_serialize($index));
			}
		}
		else
		{
			if ( $key === false )
			{
				// create a new key
				$key = $this->_new_key();

				if ( ! is_array($index))
				{
					// create a new index and store the key
					$this->redis->set($this->config['cache_id'].':index:'.$sections, $this->_serialize(array($identifier => array($key,$this->created))));
				}
				else
				{
					// add the key to the index
					$index[$identifier] = array($key,$this->created);
					$this->redis->set($this->config['cache_id'].':index:'.$sections, $this->_serialize($index));
				}

				// get the directory index
				$index = $this->redis->get($this->config['cache_id'].':dir:');
				is_null($index) or $index = $this->_unserialize($index);

				if (is_array($index))
				{
					if ( ! in_array($sections, $index))
					{
						$index[] = $sections;
					}
				}
				else
				{
					$index = array($sections);
				}

				// update the directory index
				$this->redis->set($this->config['cache_id'].':dir:', $this->_serialize($index));
			}
		}

		return $key;
	}

	/**
	 * generate a new unique key for the current identifier
	 *
	 * @return  string
	 */
	private function _new_key()
	{
		$key = '';
		while (strlen($key) < 32)
		{
			$key .= mt_rand(0, mt_getrandmax());
		}
		return $this->config['cache_id'].'_'.uniqid($key);
	}

	/**
	 * validate a driver config value
	 *
	 * @param   string  name of the config variable to validate
	 * @param   mixed   value
	 * @return  mixed
	 */
	private function _validate_config($name, $value)
	{
		switch ($name)
		{
			case 'database':
				// do we have a database config
				if (empty($value) or ! is_array($value))
				{
					$value = 'default';
				}
			break;

			case 'cache_id':
				if (empty($value) or ! is_string($value))
				{
					$value = 'fuel';
				}
			break;

			case 'expiration':
				if (empty($value) or ! is_numeric($value))
				{
					$value = null;
				}
			break;

			default:
			break;
		}

		return $value;
	}

	/**
	 * Serialize an array
	 *
	 * This function first converts any slashes found in the array to a temporary
	 * marker, so when it gets unserialized the slashes will be preserved
	 *
	 * @param   array
	 * @return  string
	 */
	protected function _serialize($data)
	{
		if (is_array($data))
		{
			foreach ($data as $key => $val)
			{
				if (is_string($val))
				{
					$data[$key] = str_replace('\\', '{{slash}}', $val);
				}
			}
		}
		else
		{
			if (is_string($data))
			{
				$data = str_replace('\\', '{{slash}}', $data);
			}
		}

		return serialize($data);
	}

	/**
	 * Unserialize
	 *
	 * This function unserializes a data string, then converts any
	 * temporary slash markers back to actual slashes
	 *
	 * @param   array
	 * @return  string
	 */
	protected function _unserialize($data)
	{
		$data = @unserialize(stripslashes($data));

		if (is_array($data))
		{
			foreach ($data as $key => $val)
			{
				if (is_string($val))
				{
					$data[$key] = str_replace('{{slash}}', '\\', $val);
				}
			}

			return $data;
		}

		return (is_string($data)) ? str_replace('{{slash}}', '\\', $data) : $data;
	}
}
Back to Top