* @file
* @ingroup Cache
*/
+use Wikimedia\Assert\Assert;
/**
* Handles a simple LRU key/value map with a maximum number of entries
*/
class MapCacheLRU {
/** @var array */
- protected $cache = array(); // (key => value)
+ protected $cache = []; // (key => value)
protected $maxCacheKeys; // integer; max entries
/**
* @param int $maxKeys Maximum number of entries allowed (min 1).
- * @throws Exception When $maxCacheKeys is not an int or =< 0.
+ * @throws Exception When $maxCacheKeys is not an int or not above zero.
*/
public function __construct( $maxKeys ) {
- if ( !is_int( $maxKeys ) || $maxKeys < 1 ) {
- throw new Exception( __METHOD__ . " must be given an integer and >= 1" );
- }
+ Assert::parameterType( 'integer', $maxKeys, '$maxKeys' );
+ Assert::parameter( $maxKeys > 0, '$maxKeys', 'must be above zero' );
+
$this->maxCacheKeys = $maxKeys;
}
*/
public function set( $key, $value ) {
if ( array_key_exists( $key, $this->cache ) ) {
- $this->ping( $key ); // push to top
+ $this->ping( $key );
} elseif ( count( $this->cache ) >= $this->maxCacheKeys ) {
reset( $this->cache );
$evictKey = key( $this->cache );
* @return bool
*/
public function has( $key ) {
- if ( is_string( $key ) || is_integer( $key ) ) {
- return array_key_exists( $key, $this->cache );
- }
- wfWarn( __METHOD__ . ": Key passed isn't a string or an integer.", 2 );
- return false;
+ return array_key_exists( $key, $this->cache );
}
/**
* @return mixed
*/
public function get( $key ) {
- if ( array_key_exists( $key, $this->cache ) ) {
- $this->ping( $key ); // push to top
- return $this->cache[$key];
- } else {
+ if ( !array_key_exists( $key, $this->cache ) ) {
return null;
}
+ $this->ping( $key );
+ return $this->cache[$key];
}
/**
*/
public function clear( $keys = null ) {
if ( $keys === null ) {
- $this->cache = array();
+ $this->cache = [];
} else {
foreach ( (array)$keys as $key ) {
unset( $this->cache[$key] );