| 1 |
<?php |
| 2 |
namespace Aws; |
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
class LruArrayCache implements CacheInterface, \Countable |
| 15 |
{ |
| 16 |
|
| 17 |
private $maxItems; |
| 18 |
|
| 19 |
|
| 20 |
private $items = array(); |
| 21 |
|
| 22 |
|
| 23 |
|
| 24 |
|
| 25 |
public function __construct($maxItems = 1000) |
| 26 |
{ |
| 27 |
$this->maxItems = $maxItems; |
| 28 |
} |
| 29 |
|
| 30 |
public function get($key) |
| 31 |
{ |
| 32 |
$key = $key ?? ''; |
| 33 |
if (!isset($this->items[$key])) { |
| 34 |
return null; |
| 35 |
} |
| 36 |
|
| 37 |
$entry = $this->items[$key]; |
| 38 |
|
| 39 |
|
| 40 |
if (!$entry[1] || time() < $entry[1]) { |
| 41 |
|
| 42 |
unset($this->items[$key]); |
| 43 |
$this->items[$key] = $entry; |
| 44 |
return $entry[0]; |
| 45 |
} |
| 46 |
|
| 47 |
unset($this->items[$key]); |
| 48 |
return null; |
| 49 |
} |
| 50 |
|
| 51 |
public function set($key, $value, $ttl = 0) |
| 52 |
{ |
| 53 |
$key = $key ?? ''; |
| 54 |
|
| 55 |
$ttl = $ttl ? time() + $ttl : 0; |
| 56 |
$this->items[$key] = [$value, $ttl]; |
| 57 |
|
| 58 |
|
| 59 |
$diff = count($this->items) - $this->maxItems; |
| 60 |
|
| 61 |
|
| 62 |
if ($diff > 0) { |
| 63 |
|
| 64 |
reset($this->items); |
| 65 |
for ($i = 0; $i < $diff; $i++) { |
| 66 |
unset($this->items[key($this->items)]); |
| 67 |
next($this->items); |
| 68 |
} |
| 69 |
} |
| 70 |
} |
| 71 |
|
| 72 |
public function remove($key) |
| 73 |
{ |
| 74 |
$key = $key ?? ''; |
| 75 |
unset($this->items[$key]); |
| 76 |
} |
| 77 |
|
| 78 |
|
| 79 |
|
| 80 |
|
| 81 |
#[\ReturnTypeWillChange] |
| 82 |
public function count() |
| 83 |
{ |
| 84 |
return count($this->items); |
| 85 |
} |
| 86 |
} |