Debian Codegraph @

lib/3rdParty/composer/aws/aws-sdk-php/src/LruArrayCache.php

raw symbols SCIP
1 <?php
2 namespace Aws;
3
4 /**
5 * Simple in-memory LRU cache that limits the number of cached entries.
6 *
7 * The LRU cache is implemented using PHP's ordered associative array. When
8 * accessing an element, the element is removed from the hash and re-added to
9 * ensure that recently used items are always at the end of the list while
10 * least recently used are at the beginning. When a value is added to the
11 * cache, if the number of cached items exceeds the allowed number, the first
12 * N number of items are removed from the array.
13 */
14 class LruArrayCache implements CacheInterface, \Countable
15 {
16 /** @var int */
17 private $maxItems;
18
19 /** @var array */
20 private $items = array();
21
22 /**
23 * @param int $maxItems Maximum number of allowed cache items.
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 // Ensure the item is not expired.
40 if (!$entry[1] || time() < $entry[1]) {
41 // LRU: remove the item and push it to the end of the array.
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 // Only call time() if the TTL is not 0/false/null
55 $ttl = $ttl ? time() + $ttl : 0;
56 $this->items[$key] = [$value, $ttl];
57
58 // Determine if there are more items in the cache than allowed.
59 $diff = count($this->items) - $this->maxItems;
60
61 // Clear out least recently used items.
62 if ($diff > 0) {
63 // Reset to the beginning of the array and begin unsetting.
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 * @return int
80 */
81 #[\ReturnTypeWillChange]
82 public function count()
83 {
84 return count($this->items);
85 }
86 }