Last active
August 21, 2022 11:06
-
-
Save mikemix/c24a52dda95f6c4b47aa9efa767cceb4 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
declare(strict_types=1); | |
namespace App\Cache; | |
/** | |
* @template TCacheItem | |
* @template-implements LRUCacheInterface<TCacheItem> | |
*/ | |
final class LRUCache implements LRUCacheInterface | |
{ | |
/** | |
* @var array<string, TCacheItem> | |
*/ | |
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; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment