PluginProbe
Media Cloud Sync / 1.2.12
Media Cloud Sync v1.2.12
1.4.0 1.3.12 1.3.11 1.3.10 trunk 1.0.0 1.0.1 1.0.2 1.0.3 1.1.0 1.1.1 1.2.0 1.2.10 1.2.11 1.2.12 1.2.13 1.2.2 1.2.3 1.2.4 1.2.5 1.2.6 1.2.7 1.2.8 1.2.9 1.3.0 All 34 releases
media-cloud-sync / includes / sdk / s3 / Aws / LruArrayCache.php

LruArrayCache.php in Media Cloud Sync 1.2.12, at includes/sdk/s3/Aws/LruArrayCache.php

74 lines 2.2 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
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