Proyectos de Subversion Moodle

Rev

Rev 1 | | Comparar con el anterior | Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
1 efrain 1
<?php
2
// This file is part of Moodle - http://moodle.org/
3
//
4
// Moodle is free software: you can redistribute it and/or modify
5
// it under the terms of the GNU General Public License as published by
6
// the Free Software Foundation, either version 3 of the License, or
7
// (at your option) any later version.
8
//
9
// Moodle is distributed in the hope that it will be useful,
10
// but WITHOUT ANY WARRANTY; without even the implied warranty of
11
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
// GNU General Public License for more details.
13
//
14
// You should have received a copy of the GNU General Public License
15
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
16
 
1441 ariadna 17
use core_cache\configurable_cache_interface;
18
use core_cache\definition;
19
use core_cache\key_aware_cache_interface;
20
use core_cache\store;
1 efrain 21
 
22
/**
23
 * The APCu cache store class.
24
 *
1441 ariadna 25
 * @package    cachestore_apcu
1 efrain 26
 * @copyright  2012 Sam Hemelryk
27
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
28
 */
1441 ariadna 29
class cachestore_apcu extends store implements configurable_cache_interface, key_aware_cache_interface {
1 efrain 30
    /**
31
     * The required version of APCu for this extension.
32
     */
33
    const REQUIRED_VERSION = '4.0.0';
34
 
35
    /**
36
     * The name of this store instance.
37
     * @var string
38
     */
39
    protected $name;
40
 
41
    /**
42
     * The definition used when this instance was initialised.
1441 ariadna 43
     * @var definition
1 efrain 44
     */
45
    protected $definition = null;
46
 
47
    /**
48
     * The storeprefix to use on all instances of this store.  Configured as part store setup.
49
     * @var string
50
     */
51
    protected $storeprefix = null;
52
 
53
    /**
54
     * The prefix added specifically for this cache.
55
     * @var string
56
     */
57
    protected $cacheprefix = null;
58
 
59
    /**
60
     * Static method to check that the APCu stores requirements have been met.
61
     *
62
     * It checks that the APCu extension has been loaded and that it has been enabled.
63
     *
64
     * @return bool True if the stores software/hardware requirements have been met and it can be used. False otherwise.
65
     */
66
    public static function are_requirements_met() {
67
        $enabled = ini_get('apc.enabled') && (php_sapi_name() != "cli" || ini_get('apc.enable_cli'));
68
        if (!extension_loaded('apcu') || !$enabled) {
69
            return false;
70
        }
71
 
72
        $version = phpversion('apcu');
73
        return $version && version_compare($version, self::REQUIRED_VERSION, '>=');
74
    }
75
 
76
    /**
77
     * Static method to check if a store is usable with the given mode.
78
     *
1441 ariadna 79
     * @param int $mode One of store::MODE_*
1 efrain 80
     * @return bool True if the mode is supported.
81
     */
82
    public static function is_supported_mode($mode) {
83
        return ($mode === self::MODE_APPLICATION || $mode === self::MODE_SESSION);
84
    }
85
 
86
    /**
87
     * Returns the supported features as a binary flag.
88
     *
89
     * @param array $configuration The configuration of a store to consider specifically.
90
     * @return int The supported features.
91
     */
92
    public static function get_supported_features(array $configuration = array()) {
93
        return self::SUPPORTS_NATIVE_TTL;
94
    }
95
 
96
    /**
97
     * Returns the supported modes as a binary flag.
98
     *
99
     * @param array $configuration The configuration of a store to consider specifically.
100
     * @return int The supported modes.
101
     */
102
    public static function get_supported_modes(array $configuration = array()) {
103
        return self::MODE_APPLICATION + self::MODE_SESSION;
104
    }
105
 
106
    /**
107
     * Constructs an instance of the cache store.
108
     *
109
     * This method should not create connections or perform and processing, it should be used
110
     *
111
     * @param string $name The name of the cache store
112
     * @param array $configuration The configuration for this store instance.
113
     */
114
    public function __construct($name, array $configuration = array()) {
115
        global $CFG;
116
        $this->name = $name;
117
        $this->storeprefix = $CFG->prefix;
118
        if (isset($configuration['prefix'])) {
119
            $this->storeprefix = $configuration['prefix'];
120
        }
121
    }
122
 
123
    /**
124
     * Returns the name of this store instance.
125
     * @return string
126
     */
127
    public function my_name() {
128
        return $this->name;
129
    }
130
 
131
    /**
132
     * Initialises a new instance of the cache store given the definition the instance is to be used for.
133
     *
134
     * This function should prepare any given connections etc.
135
     *
1441 ariadna 136
     * @param definition $definition
1 efrain 137
     * @return bool
138
     */
1441 ariadna 139
    public function initialise(definition $definition) {
1 efrain 140
        $this->definition = $definition;
141
        $this->cacheprefix = $this->storeprefix.$definition->generate_definition_hash().'__';
142
        return true;
143
    }
144
 
145
    /**
146
     * Returns true if this cache store instance has been initialised.
147
     * @return bool
148
     */
149
    public function is_initialised() {
150
        return ($this->definition !== null);
151
    }
152
 
153
    /**
154
     * Prepares the given key for use.
155
     *
156
     * Should be called before all interaction.
157
     *
158
     * @param string $key The key to prepare for storing in APCu.
159
     *
160
     * @return string
161
     */
162
    protected function prepare_key($key) {
163
        return $this->cacheprefix . $key;
164
    }
165
 
166
    /**
167
     * Retrieves an item from the cache store given its key.
168
     *
169
     * @param string $key The key to retrieve
170
     * @return mixed The data that was associated with the key, or false if the key did not exist.
171
     */
172
    public function get($key) {
173
        $key = $this->prepare_key($key);
174
        $success = false;
175
        $outcome = apcu_fetch($key, $success);
176
        if ($success) {
177
            return $outcome;
178
        }
179
        return $success;
180
    }
181
 
182
    /**
183
     * Retrieves several items from the cache store in a single transaction.
184
     *
185
     * If not all of the items are available in the cache then the data value for those that are missing will be set to false.
186
     *
187
     * @param array $keys The array of keys to retrieve
188
     * @return array An array of items from the cache. There will be an item for each key, those that were not in the store will
189
     *      be set to false.
190
     */
191
    public function get_many($keys) {
192
        $map = array();
193
        foreach ($keys as $key) {
194
            $map[$key] = $this->prepare_key($key);
195
        }
196
        $outcomes = array();
197
        $success = false;
198
        $results = apcu_fetch($map, $success);
199
        if ($success) {
200
            foreach ($map as $key => $used) {
201
                if (array_key_exists($used, $results)) {
202
                    $outcomes[$key] = $results[$used];
203
                } else {
204
                    $outcomes[$key] = false;
205
                }
206
            }
207
        } else {
208
            $outcomes = array_fill_keys($keys, false);
209
        }
210
        return $outcomes;
211
    }
212
 
213
    /**
214
     * Sets an item in the cache given its key and data value.
215
     *
216
     * @param string $key The key to use.
217
     * @param mixed $data The data to set.
218
     * @return bool True if the operation was a success false otherwise.
219
     */
220
    public function set($key, $data) {
221
        $key = $this->prepare_key($key);
222
        return apcu_store($key, $data, $this->definition->get_ttl());
223
    }
224
 
225
    /**
226
     * Sets many items in the cache in a single transaction.
227
     *
228
     * @param array $keyvaluearray An array of key value pairs. Each item in the array will be an associative array with two
229
     *      keys, 'key' and 'value'.
230
     * @return int The number of items successfully set. It is up to the developer to check this matches the number of items
231
     *      sent ... if they care that is.
232
     */
233
    public function set_many(array $keyvaluearray) {
234
        $map = array();
235
        foreach ($keyvaluearray as $pair) {
236
            $key = $this->prepare_key($pair['key']);
237
            $map[$key] = $pair['value'];
238
        }
239
        $result = apcu_store($map, null, $this->definition->get_ttl());
240
        return count($map) - count($result);
241
    }
242
 
243
    /**
244
     * Deletes an item from the cache store.
245
     *
246
     * @param string $key The key to delete.
247
     * @return bool Returns true if the operation was a success, false otherwise.
248
     */
249
    public function delete($key) {
250
        $key = $this->prepare_key($key);
251
        return apcu_delete($key);
252
    }
253
 
254
    /**
255
     * Deletes several keys from the cache in a single action.
256
     *
257
     * @param array $keys The keys to delete
258
     * @return int The number of items successfully deleted.
259
     */
260
    public function delete_many(array $keys) {
261
        $count = 0;
262
        foreach ($keys as $key) {
263
            if ($this->delete($key)) {
264
                $count++;
265
            }
266
        }
267
        return $count;
268
    }
269
 
270
    /**
271
     * Purges the cache deleting all items within it.
272
     *
273
     * @return boolean True on success. False otherwise.
274
     */
275
    public function purge() {
276
        if (class_exists('APCUIterator', false)) {
277
            $iterator = new APCUIterator('#^' . preg_quote($this->cacheprefix, '#') . '#');
278
        } else {
279
            $iterator = new APCIterator('user', '#^' . preg_quote($this->cacheprefix, '#') . '#');
280
        }
281
        return apcu_delete($iterator);
282
    }
283
 
284
    /**
285
     * Performs any necessary clean up when the store instance is being deleted.
286
     */
287
    public function instance_deleted() {
288
        if (class_exists('APCUIterator', false)) {
289
            $iterator = new APCUIterator('#^' . preg_quote($this->storeprefix, '#') . '#');
290
        } else {
291
            $iterator = new APCIterator('user', '#^' . preg_quote($this->storeprefix, '#') . '#');
292
        }
293
        return apcu_delete($iterator);
294
    }
295
 
296
    /**
297
     * Generates an instance of the cache store that can be used for testing.
298
     *
299
     * Returns an instance of the cache store, or false if one cannot be created.
300
     *
1441 ariadna 301
     * @param definition $definition
302
     * @return store
1 efrain 303
     */
1441 ariadna 304
    public static function initialise_test_instance(definition $definition) {
1 efrain 305
        $testperformance = get_config('cachestore_apcu', 'testperformance');
306
        if (empty($testperformance)) {
307
            return false;
308
        }
309
        if (!self::are_requirements_met()) {
310
            return false;
311
        }
312
        $name = 'APCu test';
313
        $cache = new cachestore_apcu($name);
314
        // No need to check if is_ready() as this has already being done by requirement check.
315
        $cache->initialise($definition);
316
        return $cache;
317
    }
318
 
319
    /**
320
     * Test is a cache has a key.
321
     *
322
     * @param string|int $key
323
     * @return bool True if the cache has the requested key, false otherwise.
324
     */
325
    public function has($key) {
326
        $key = $this->prepare_key($key);
327
        return apcu_exists($key);
328
    }
329
 
330
    /**
331
     * Test if a cache has at least one of the given keys.
332
     *
333
     * @param array $keys
334
     * @return bool True if the cache has at least one of the given keys
335
     */
336
    public function has_any(array $keys) {
337
        foreach ($keys as $arraykey => $key) {
338
            $keys[$arraykey] = $this->prepare_key($key);
339
        }
340
        $result = apcu_exists($keys);
341
        return count($result) > 0;
342
    }
343
 
344
    /**
345
     * Test is a cache has all of the given keys.
346
     *
347
     * @param array $keys
348
     * @return bool True if the cache has all of the given keys, false otherwise.
349
     */
350
    public function has_all(array $keys) {
351
        foreach ($keys as $arraykey => $key) {
352
            $keys[$arraykey] = $this->prepare_key($key);
353
        }
354
        $result = apcu_exists($keys);
355
        return count($result) === count($keys);
356
    }
357
 
358
    /**
359
     * Generates the appropriate configuration required for unit testing.
360
     *
361
     * @return array Array of unit test configuration data to be used by initialise().
362
     */
363
    public static function unit_test_configuration() {
364
        return array('prefix' => 'phpunit');
365
    }
366
 
367
    /**
368
     * Given the data from the add instance form this function creates a configuration array.
369
     *
370
     * @param stdClass $data
371
     * @return array
372
     */
373
    public static function config_get_configuration_array($data) {
374
        $config = array();
375
 
376
        if (isset($data->prefix)) {
377
            $config['prefix'] = $data->prefix;
378
        }
379
        return $config;
380
    }
381
    /**
382
     * Allows the cache store to set its data against the edit form before it is shown to the user.
383
     *
384
     * @param moodleform $editform
385
     * @param array $config
386
     */
387
    public static function config_set_edit_form_data(moodleform $editform, array $config) {
388
        if (isset($config['prefix'])) {
389
            $data['prefix'] = $config['prefix'];
390
        } else {
391
            $data['prefix'] = '';
392
        }
393
        $editform->set_data($data);
394
    }
395
 
396
    /**
397
     * Returns true if this cache store instance is both suitable for testing, and ready for testing.
398
     *
399
     * Cache stores that support being used as the default store for unit and acceptance testing should
400
     * override this function and return true if there requirements have been met.
401
     *
402
     * @return bool
403
     */
404
    public static function ready_to_be_used_for_testing() {
405
        return true;
406
    }
407
}