| 1 |
<?php |
| 2 |
/** |
| 3 |
* Array cache helper. |
| 4 |
* |
| 5 |
* @package Calotes\Helper |
| 6 |
*/ |
| 7 |
|
| 8 |
namespace Calotes\Helper; |
| 9 |
|
| 10 |
use Calotes\Base\Component; |
| 11 |
|
| 12 |
/** |
| 13 |
* This is runtime cache, so the cache content will be flush after each refresh. |
| 14 |
*/ |
| 15 |
class Array_Cache extends Component { |
| 16 |
|
| 17 |
/** |
| 18 |
* The cached array. |
| 19 |
* |
| 20 |
* @var array |
| 21 |
*/ |
| 22 |
protected static $cached = array(); |
| 23 |
|
| 24 |
/** |
| 25 |
* Sets a value in the cache. |
| 26 |
* |
| 27 |
* @param mixed $name The name of the value to set. |
| 28 |
* @param mixed $value The value to set. |
| 29 |
* @param mixed $group The group of the value (optional). |
| 30 |
* |
| 31 |
* @return void |
| 32 |
*/ |
| 33 |
public static function set( $name, $value, $group = null ) { |
| 34 |
$key = $name . $group; |
| 35 |
self::$cached[ $key ] = $value; |
| 36 |
} |
| 37 |
|
| 38 |
/** |
| 39 |
* Retrieves a value from the cache. |
| 40 |
* |
| 41 |
* @param mixed $name The name of the value to retrieve. |
| 42 |
* @param mixed $group The group of the value (optional). |
| 43 |
* @param mixed $default_name The default value to return if the value is not found (optional). |
| 44 |
* |
| 45 |
* @return mixed The retrieved value or the default value if not found. |
| 46 |
*/ |
| 47 |
public static function get( $name, $group = null, $default_name = null ) { |
| 48 |
$key = $name . $group; |
| 49 |
|
| 50 |
return self::$cached[ $key ] ?? $default_name; |
| 51 |
} |
| 52 |
|
| 53 |
/** |
| 54 |
* Appends a new element to a cached array. |
| 55 |
* |
| 56 |
* @param mixed $name The name of the value to append. |
| 57 |
* @param mixed $value The value to append. |
| 58 |
* @param mixed $group The group of the value (optional). |
| 59 |
* |
| 60 |
* @return void |
| 61 |
*/ |
| 62 |
public static function append( $name, $value, $group = null ) { |
| 63 |
$data = self::get( $name, $group, array() ); |
| 64 |
if ( is_array( $data ) ) { |
| 65 |
$data[] = $value; |
| 66 |
} |
| 67 |
self::set( $name, $data, $group ); |
| 68 |
} |
| 69 |
|
| 70 |
/** |
| 71 |
* Removes a value from the cache. |
| 72 |
* |
| 73 |
* @param mixed $name The name of the value to remove. |
| 74 |
* @param mixed $group The group of the value (optional). |
| 75 |
* |
| 76 |
* @return bool True if the value was successfully removed, false otherwise. |
| 77 |
*/ |
| 78 |
public static function remove( $name, $group = null ) { |
| 79 |
$key = $name . $group; |
| 80 |
if ( isset( self::$cached[ $key ] ) ) { |
| 81 |
unset( self::$cached[ $key ] ); |
| 82 |
|
| 83 |
return true; |
| 84 |
} |
| 85 |
|
| 86 |
return false; |
| 87 |
} |
| 88 |
} |
| 89 |
|