Skip to content

Instantly share code, notes, and snippets.

@gotterdemarung
Created April 8, 2016 14:47
Show Gist options
  • Select an option

  • Save gotterdemarung/a439c2536578b9797e60bfeac378d657 to your computer and use it in GitHub Desktop.

Select an option

Save gotterdemarung/a439c2536578b9797e60bfeac378d657 to your computer and use it in GitHub Desktop.
<?php
namespace Maxwell\Cache;
class PhpNativeLruCache implements CacheInterface, \Countable
{
private $capacity;
private $ttl;
private $map = [];
/**
* PhpLruCache constructor.
*
* @param int $capacity Expected maximum capacity
* @param int $ttl Time to live in seconds, zero or negative value for infinity
*/
public function __construct($capacity, $ttl)
{
if (!is_int($capacity) || $capacity < 1) {
throw new \InvalidArgumentException('$capacity should be int and greater, than 0');
}
if (!is_int($ttl)) {
throw new \InvalidArgumentException('$ttl must be integer');
}
$this->capacity = $capacity;
$this->ttl = $ttl;
}
/**
* Returns cache with requested parameters
*
* @param string $prefix
* @param int $ttl Time in seconds
* @return CacheInterface
*/
public function getCache($prefix, $ttl)
{
return new self($this->capacity, $ttl);
}
/**
* Returns fully-qualified key (with prefix)
*
* @param mixed $key
* @return string
*/
public function key($key)
{
return 's' . $key;
}
/**
* @inheritdoc
*/
public function offsetExists($offset)
{
if (!isset($this->map[$this->key($offset)])) {
return false;
}
if ($this->ttl > 0 && $this->map[$this->key($offset)][1] < time()) {
$this->offsetUnset($offset);
return false;
}
return true;
}
/**
* @inheritdoc
*/
public function offsetGet($offset)
{
if (!$this->offsetExists($offset)) {
return null;
}
$node = $this->map[$this->key($offset)];
unset($this->map[$this->key($offset)]);
$this->map[$this->key($offset)] = $node;
return $node[0];
}
/**
* @inheritdoc
*/
public function offsetSet($offset, $value)
{
$this->map[$this->key($offset)] = [$value, time() + $this->ttl];
if ($this->count() > $this->capacity) {
array_shift($this->map);
}
}
/**
* @inheritdoc
*/
public function offsetUnset($offset)
{
unset($this->map[$this->key($offset)]);
}
/**
* @inheritdoc
*/
public function count()
{
return count($this->map);
}
/**
* Removes all entries from cache
*/
public function flush()
{
$this->map = [];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment