*/ final class LRUCache implements LRUCacheInterface { /** * @var array */ private array $items = []; private int $size; public function __construct(int $size) { if ($size <= 0) { throw new InvalidArgumentException('Cache size must be greater than 0'); } $this->size = $size; } /** {@inheritDoc} */ public function add(string $key, $item): void { // already on the list if (isset($this->items[$key])) { $this->items[$key] = $item; $this->moveToFront($key); return; } $this->items[$key] = $item; // there's still room for new items if (\count($this->items) <= $this->size) { return; } // no room for new items // remove the least used element \reset($this->items); unset($this->items[\key($this->items)]); } /** {@inheritDoc} */ public function get(string $key) { if (false === isset($this->items[$key])) { return null; } $this->moveToFront($key); return $this->items[$key]; } private function moveToFront(string $key): void { $cachedItem = $this->items[$key]; unset($this->items[$key]); $this->items[$key] = $cachedItem; } }