Proyectos de Subversion Moodle

Rev

| Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
1 efrain 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
        if (!isset($this->items[$key])) {
33
            return null;
34
        }
35
 
36
        $entry = $this->items[$key];
37
 
38
        // Ensure the item is not expired.
39
        if (!$entry[1] || time() < $entry[1]) {
40
            // LRU: remove the item and push it to the end of the array.
41
            unset($this->items[$key]);
42
            $this->items[$key] = $entry;
43
            return $entry[0];
44
        }
45
 
46
        unset($this->items[$key]);
47
        return null;
48
    }
49
 
50
    public function set($key, $value, $ttl = 0)
51
    {
52
        // Only call time() if the TTL is not 0/false/null
53
        $ttl = $ttl ? time() + $ttl : 0;
54
        $this->items[$key] = [$value, $ttl];
55
 
56
        // Determine if there are more items in the cache than allowed.
57
        $diff = count($this->items) - $this->maxItems;
58
 
59
        // Clear out least recently used items.
60
        if ($diff > 0) {
61
            // Reset to the beginning of the array and begin unsetting.
62
            reset($this->items);
63
            for ($i = 0; $i < $diff; $i++) {
64
                unset($this->items[key($this->items)]);
65
                next($this->items);
66
            }
67
        }
68
    }
69
 
70
    public function remove($key)
71
    {
72
        unset($this->items[$key]);
73
    }
74
 
75
    /**
76
     * @return int
77
     */
78
    #[\ReturnTypeWillChange]
79
    public function count()
80
    {
81
        return count($this->items);
82
    }
83
}