Elgg  Version 3.0
LRUCache.php
Go to the documentation of this file.
1 <?php
2 
3 namespace Elgg\Cache;
4 
18 class LRUCache implements \ArrayAccess {
20  protected $maximumSize;
21 
27  protected $data = [];
28 
35  public function __construct($size) {
36  if (!is_int($size) || $size <= 0) {
37  throw new \InvalidArgumentException();
38  }
39  $this->maximumSize = $size;
40  }
41 
49  public function get($key, $default = null) {
50  if ($this->containsKey($key)) {
51  $this->recordAccess($key);
52 
53  return $this->data[$key];
54  }
55 
56  return $default;
57  }
58 
66  public function set($key, $value) {
67  if ($this->containsKey($key)) {
68  $this->data[$key] = $value;
69  $this->recordAccess($key);
70  } else {
71  $this->data[$key] = $value;
72  if ($this->size() > $this->maximumSize) {
73  // remove least recently used element (front of array)
74  reset($this->data);
75  unset($this->data[key($this->data)]);
76  }
77  }
78  }
79 
85  public function size() {
86  return count($this->data);
87  }
88 
95  public function containsKey($key) {
96  return array_key_exists($key, $this->data);
97  }
98 
105  public function remove($key) {
106  if ($this->containsKey($key)) {
107  $value = $this->data[$key];
108  unset($this->data[$key]);
109  return $value;
110  }
111 
112  return null;
113  }
114 
120  public function clear() {
121  $this->data = [];
122  }
123 
130  protected function recordAccess($key) {
131  $value = $this->data[$key];
132  unset($this->data[$key]);
133  $this->data[$key] = $value;
134  }
135 
145  public function offsetSet($key, $value) {
146  $this->set($key, $value);
147  }
148 
157  public function offsetGet($key) {
158  return $this->get($key);
159  }
160 
169  public function offsetUnset($key) {
170  $this->remove($key);
171  }
172 
181  public function offsetExists($key) {
182  return $this->containsKey($key);
183  }
184 }
size()
Get the number of elements in the cache.
Definition: LRUCache.php:85
Least Recently Used Cache.
Definition: LRUCache.php:18
$size
Definition: remove.php:24
recordAccess($key)
Moves the element from current position to end of array.
Definition: LRUCache.php:130
clear()
Clear the cache.
Definition: LRUCache.php:120
offsetGet($key)
Get the value for specified key.
Definition: LRUCache.php:157
offsetExists($key)
Does key exist?
Definition: LRUCache.php:181
__construct($size)
Create a LRU Cache.
Definition: LRUCache.php:35
$default
Definition: checkbox.php:35
if($container instanceof ElggGroup &&$container->guid!=elgg_get_page_owner_guid()) $key
Definition: summary.php:55
containsKey($key)
Does the cache contain an element with this key.
Definition: LRUCache.php:95
$value
Definition: debugging.php:7
offsetSet($key, $value)
Assigns a value for the specified key.
Definition: LRUCache.php:145
offsetUnset($key)
Unsets a key.
Definition: LRUCache.php:169