Merge "Parser test for "Free external link with trailing punctuation""
[lhc/web/wiklou.git] / includes / libs / ProcessCacheLRU.php
index f2d9f42..ce97142 100644 (file)
@@ -38,10 +38,7 @@ class ProcessCacheLRU {
         * @throws UnexpectedValueException When $maxCacheKeys is not an int or =< 0.
         */
        public function __construct( $maxKeys ) {
-               if ( !is_int( $maxKeys ) || $maxKeys < 1 ) {
-                       throw new UnexpectedValueException( __METHOD__ . " must be given an integer >= 1" );
-               }
-               $this->maxCacheKeys = $maxKeys;
+               $this->resize( $maxKeys );
        }
 
        /**
@@ -64,7 +61,7 @@ class ProcessCacheLRU {
                        unset( $this->cacheTimes[$evictKey] );
                }
                $this->cache[$key][$prop] = $value;
-               $this->cacheTimes[$key][$prop] = time();
+               $this->cacheTimes[$key][$prop] = microtime( true );
        }
 
        /**
@@ -72,12 +69,13 @@ class ProcessCacheLRU {
         *
         * @param $key string
         * @param $prop string
-        * @param $maxAge integer Ignore items older than this many seconds (since 1.21)
+        * @param $maxAge float Ignore items older than this many seconds (since 1.21)
         * @return bool
         */
-       public function has( $key, $prop, $maxAge = 0 ) {
+       public function has( $key, $prop, $maxAge = 0.0 ) {
                if ( isset( $this->cache[$key][$prop] ) ) {
-                       return ( $maxAge <= 0 || ( time() - $this->cacheTimes[$key][$prop] ) <= $maxAge );
+                       return ( $maxAge <= 0 ||
+                               ( microtime( true ) - $this->cacheTimes[$key][$prop] ) <= $maxAge );
                }
 
                return false;
@@ -119,6 +117,26 @@ class ProcessCacheLRU {
                }
        }
 
+       /**
+        * Resize the maximum number of cache entries, removing older entries as needed
+        *
+        * @param $maxKeys integer
+        * @return void
+        * @throws UnexpectedValueException
+        */
+       public function resize( $maxKeys ) {
+               if ( !is_int( $maxKeys ) || $maxKeys < 1 ) {
+                       throw new UnexpectedValueException( __METHOD__ . " must be given an integer >= 1" );
+               }
+               $this->maxCacheKeys = $maxKeys;
+               while ( count( $this->cache ) > $this->maxCacheKeys ) {
+                       reset( $this->cache );
+                       $evictKey = key( $this->cache );
+                       unset( $this->cache[$evictKey] );
+                       unset( $this->cacheTimes[$evictKey] );
+               }
+       }
+
        /**
         * Push an entry to the top of the cache
         *