123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184 |
- <?php
- namespace Elgg\Cache;
- class LRUCache implements \ArrayAccess {
-
- protected $maximumSize;
-
- protected $data = array();
-
- public function __construct($size) {
- if (!is_int($size) || $size <= 0) {
- throw new \InvalidArgumentException();
- }
- $this->maximumSize = $size;
- }
-
- public function get($key, $default = null) {
- if (isset($this->data[$key])) {
- $this->recordAccess($key);
- return $this->data[$key];
- } else {
- return $default;
- }
- }
-
- public function set($key, $value) {
- if (isset($this->data[$key])) {
- $this->data[$key] = $value;
- $this->recordAccess($key);
- } else {
- $this->data[$key] = $value;
- if ($this->size() > $this->maximumSize) {
-
- reset($this->data);
- unset($this->data[key($this->data)]);
- }
- }
- }
-
- public function size() {
- return count($this->data);
- }
-
- public function containsKey($key) {
- return isset($this->data[$key]);
- }
-
- public function remove($key) {
- if (isset($this->data[$key])) {
- $value = $this->data[$key];
- unset($this->data[$key]);
- return $value;
- } else {
- return null;
- }
- }
-
- public function clear() {
- $this->data = array();
- }
-
- protected function recordAccess($key) {
- $value = $this->data[$key];
- unset($this->data[$key]);
- $this->data[$key] = $value;
- }
-
- public function offsetSet($key, $value) {
- $this->set($key, $value);
- }
-
- public function offsetGet($key) {
- return $this->get($key);
- }
-
- public function offsetUnset($key) {
- $this->remove($key);
- }
-
- public function offsetExists($key) {
- return $this->containsKey($key);
- }
- }
|