| 1 |
<?php |
| 2 |
|
| 3 |
namespace Dudlewebs\WPMCS\s3\Aws; |
| 4 |
|
| 5 |
/** |
| 6 |
* Simple in-memory LRU cache that limits the number of cached entries. |
| 7 |
* |
| 8 |
* The LRU cache is implemented using PHP's ordered associative array. When |
| 9 |
* accessing an element, the element is removed from the hash and re-added to |
| 10 |
* ensure that recently used items are always at the end of the list while |
| 11 |
* least recently used are at the beginning. When a value is added to the |
| 12 |
* cache, if the number of cached items exceeds the allowed number, the first |
| 13 |
* N number of items are removed from the array. |
| 14 |
*/ |
| 15 |
class LruArrayCache implements CacheInterface, \Countable |
| 16 |
{ |
| 17 |
/** @var int */ |
| 18 |
private $maxItems; |
| 19 |
/** @var array */ |
| 20 |
private $items = array(); |
| 21 |
/** |
| 22 |
* @param int $maxItems Maximum number of allowed cache items. |
| 23 |
*/ |
| 24 |
public function __construct($maxItems = 1000) |
| 25 |
{ |
| 26 |
$this->maxItems = $maxItems; |
| 27 |
} |
| 28 |
public function get($key) |
| 29 |
{ |
| 30 |
if (!isset($this->items[$key])) { |
| 31 |
return null; |
| 32 |
} |
| 33 |
$entry = $this->items[$key]; |
| 34 |
// Ensure the item is not expired. |
| 35 |
if (!$entry[1] || \time() < $entry[1]) { |
| 36 |
// LRU: remove the item and push it to the end of the array. |
| 37 |
unset($this->items[$key]); |
| 38 |
$this->items[$key] = $entry; |
| 39 |
return $entry[0]; |
| 40 |
} |
| 41 |
unset($this->items[$key]); |
| 42 |
return null; |
| 43 |
} |
| 44 |
public function set($key, $value, $ttl = 0) |
| 45 |
{ |
| 46 |
// Only call time() if the TTL is not 0/false/null |
| 47 |
$ttl = $ttl ? \time() + $ttl : 0; |
| 48 |
$this->items[$key] = [$value, $ttl]; |
| 49 |
// Determine if there are more items in the cache than allowed. |
| 50 |
$diff = \count($this->items) - $this->maxItems; |
| 51 |
// Clear out least recently used items. |
| 52 |
if ($diff > 0) { |
| 53 |
// Reset to the beginning of the array and begin unsetting. |
| 54 |
\reset($this->items); |
| 55 |
for ($i = 0; $i < $diff; $i++) { |
| 56 |
unset($this->items[\key($this->items)]); |
| 57 |
\next($this->items); |
| 58 |
} |
| 59 |
} |
| 60 |
} |
| 61 |
public function remove($key) |
| 62 |
{ |
| 63 |
unset($this->items[$key]); |
| 64 |
} |
| 65 |
/** |
| 66 |
* @return int |
| 67 |
*/ |
| 68 |
#[\ReturnTypeWillChange] |
| 69 |
public function count() |
| 70 |
{ |
| 71 |
return \count($this->items); |
| 72 |
} |
| 73 |
} |
| 74 |
|