Merge "registration: Only allow one extension to set a specific config setting"
[lhc/web/wiklou.git] / includes / libs / MapCacheLRU.php
1 <?php
2 /**
3 * Per-process memory cache for storing items.
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 * @ingroup Cache
22 */
23 use Wikimedia\Assert\Assert;
24
25 /**
26 * Handles a simple LRU key/value map with a maximum number of entries
27 *
28 * Use ProcessCacheLRU if hierarchical purging is needed or objects can become stale
29 *
30 * @see ProcessCacheLRU
31 * @ingroup Cache
32 * @since 1.23
33 */
34 class MapCacheLRU {
35 /** @var array */
36 protected $cache = []; // (key => value)
37
38 protected $maxCacheKeys; // integer; max entries
39
40 /**
41 * @param int $maxKeys Maximum number of entries allowed (min 1).
42 * @throws Exception When $maxCacheKeys is not an int or not above zero.
43 */
44 public function __construct( $maxKeys ) {
45 Assert::parameterType( 'integer', $maxKeys, '$maxKeys' );
46 Assert::parameter( $maxKeys > 0, '$maxKeys', 'must be above zero' );
47
48 $this->maxCacheKeys = $maxKeys;
49 }
50
51 /**
52 * @param array $values Key/value map in order of increasingly recent access
53 * @param int $maxKeys
54 * @return MapCacheLRU
55 * @since 1.30
56 */
57 public static function newFromArray( array $values, $maxKeys ) {
58 $mapCache = new self( $maxKeys );
59 $mapCache->cache = ( count( $values ) > $maxKeys )
60 ? array_slice( $values, -$maxKeys, null, true )
61 : $values;
62
63 return $mapCache;
64 }
65
66 /**
67 * @return array Key/value map in order of increasingly recent access
68 * @since 1.30
69 */
70 public function toArray() {
71 return $this->cache;
72 }
73
74 /**
75 * Set a key/value pair.
76 * This will prune the cache if it gets too large based on LRU.
77 * If the item is already set, it will be pushed to the top of the cache.
78 *
79 * To reduce evictions due to one-off use of many new keys, $rank can be
80 * set to have keys start at the top of a bottom fraction of the list. A value
81 * of 3/8 means values start at the top of the bottom 3/8s of the list and are
82 * moved to the top of the list when accessed a second time.
83 *
84 * @param string $key
85 * @param mixed $value
86 * @param float $rank Bottom fraction of the list where keys start off [Default: 1.0]
87 * @return void
88 */
89 public function set( $key, $value, $rank = 1.0 ) {
90 if ( $this->has( $key ) ) {
91 $this->ping( $key );
92 } elseif ( count( $this->cache ) >= $this->maxCacheKeys ) {
93 reset( $this->cache );
94 $evictKey = key( $this->cache );
95 unset( $this->cache[$evictKey] );
96 }
97
98 if ( $rank < 1.0 && $rank > 0 ) {
99 $offset = intval( $rank * count( $this->cache ) );
100 $this->cache = array_slice( $this->cache, 0, $offset, true )
101 + [ $key => $value ]
102 + array_slice( $this->cache, $offset, null, true );
103 } else {
104 $this->cache[$key] = $value;
105 }
106 }
107
108 /**
109 * Check if a key exists
110 *
111 * @param string $key
112 * @return bool
113 */
114 public function has( $key ) {
115 if ( !is_int( $key ) && !is_string( $key ) ) {
116 throw new UnexpectedValueException(
117 __METHOD__ . ' called with invalid key. Must be string or integer.' );
118 }
119 return array_key_exists( $key, $this->cache );
120 }
121
122 /**
123 * Get the value for a key.
124 * This returns null if the key is not set.
125 * If the item is already set, it will be pushed to the top of the cache.
126 *
127 * @param string $key
128 * @return mixed Returns null if the key was not found
129 */
130 public function get( $key ) {
131 if ( !$this->has( $key ) ) {
132 return null;
133 }
134
135 $this->ping( $key );
136
137 return $this->cache[$key];
138 }
139
140 /**
141 * @return array
142 * @since 1.25
143 */
144 public function getAllKeys() {
145 return array_keys( $this->cache );
146 }
147
148 /**
149 * Get an item with the given key, producing and setting it if not found.
150 *
151 * If the callback returns false, then nothing is stored.
152 *
153 * @since 1.28
154 * @param string $key
155 * @param callable $callback Callback that will produce the value
156 * @param float $rank Bottom fraction of the list where keys start off [Default: 1.0]
157 * @return mixed The cached value if found or the result of $callback otherwise
158 */
159 public function getWithSetCallback( $key, callable $callback, $rank = 1.0 ) {
160 if ( $this->has( $key ) ) {
161 $value = $this->get( $key );
162 } else {
163 $value = call_user_func( $callback );
164 if ( $value !== false ) {
165 $this->set( $key, $value, $rank );
166 }
167 }
168
169 return $value;
170 }
171
172 /**
173 * Clear one or several cache entries, or all cache entries
174 *
175 * @param string|array $keys
176 * @return void
177 */
178 public function clear( $keys = null ) {
179 if ( $keys === null ) {
180 $this->cache = [];
181 } else {
182 foreach ( (array)$keys as $key ) {
183 unset( $this->cache[$key] );
184 }
185 }
186 }
187
188 /**
189 * Push an entry to the top of the cache
190 *
191 * @param string $key
192 */
193 protected function ping( $key ) {
194 $item = $this->cache[$key];
195 unset( $this->cache[$key] );
196 $this->cache[$key] = $item;
197 }
198 }