DatabaseCache.php
128 lines
| 1 | <?php |
| 2 | |
| 3 | namespace Analyst\Cache; |
| 4 | |
| 5 | use Analyst\Contracts\CacheContract; |
| 6 | |
| 7 | /** |
| 8 | * Class DatabaseCache |
| 9 | * |
| 10 | * @since 1.1.5 |
| 11 | */ |
| 12 | class DatabaseCache implements CacheContract |
| 13 | { |
| 14 | const OPTION_KEY = 'analyst_cache'; |
| 15 | |
| 16 | protected static $instance; |
| 17 | |
| 18 | /** |
| 19 | * Get instance of db cache |
| 20 | * |
| 21 | * @return DatabaseCache |
| 22 | */ |
| 23 | public static function getInstance() |
| 24 | { |
| 25 | if (!self::$instance) { |
| 26 | self::$instance = new DatabaseCache(); |
| 27 | } |
| 28 | |
| 29 | return self::$instance; |
| 30 | } |
| 31 | |
| 32 | /** |
| 33 | * Key value pair |
| 34 | * |
| 35 | * @var array[] |
| 36 | */ |
| 37 | protected $values = []; |
| 38 | |
| 39 | /** |
| 40 | * DatabaseCache constructor. |
| 41 | */ |
| 42 | public function __construct() |
| 43 | { |
| 44 | $raw = get_option(self::OPTION_KEY, serialize([])); |
| 45 | |
| 46 | // Raw data may be an array already |
| 47 | $this->values = is_array($raw) ? $raw : @unserialize($raw); |
| 48 | |
| 49 | // In case serialization is failed |
| 50 | // make sure values is an array |
| 51 | if (!is_array($this->values)) { |
| 52 | $this->values = []; |
| 53 | } |
| 54 | } |
| 55 | |
| 56 | /** |
| 57 | * Save value with given key |
| 58 | * |
| 59 | * @param string $key |
| 60 | * @param string $value |
| 61 | * |
| 62 | * @return static |
| 63 | */ |
| 64 | public function put($key, $value) |
| 65 | { |
| 66 | $this->values[$key] = $value; |
| 67 | |
| 68 | $this->sync(); |
| 69 | |
| 70 | return $this; |
| 71 | } |
| 72 | |
| 73 | /** |
| 74 | * Get value by given key |
| 75 | * |
| 76 | * @param $key |
| 77 | * |
| 78 | * @param null $default |
| 79 | * @return string |
| 80 | */ |
| 81 | public function get($key, $default = null) |
| 82 | { |
| 83 | $value = isset($this->values[$key]) ? $this->values[$key] : $default; |
| 84 | |
| 85 | return $value; |
| 86 | } |
| 87 | |
| 88 | /** |
| 89 | * @param $key |
| 90 | * |
| 91 | * @return static |
| 92 | */ |
| 93 | public function delete($key) |
| 94 | { |
| 95 | if (isset($this->values[$key])) { |
| 96 | unset($this->values[$key]); |
| 97 | |
| 98 | $this->sync(); |
| 99 | } |
| 100 | |
| 101 | return $this; |
| 102 | } |
| 103 | |
| 104 | /** |
| 105 | * Update cache in DB |
| 106 | */ |
| 107 | protected function sync() |
| 108 | { |
| 109 | update_option(self::OPTION_KEY, serialize($this->values)); |
| 110 | } |
| 111 | |
| 112 | /** |
| 113 | * Should get value and remove it from cache |
| 114 | * |
| 115 | * @param $key |
| 116 | * @param null $default |
| 117 | * @return mixed |
| 118 | */ |
| 119 | public function pop($key, $default = null) |
| 120 | { |
| 121 | $value = $this->get($key); |
| 122 | |
| 123 | $this->delete($key); |
| 124 | |
| 125 | return $value; |
| 126 | } |
| 127 | } |
| 128 |