diff --git a/.upgradenotes/MDL-82158-2024062501361899.yml b/.upgradenotes/MDL-82158-2024062501361899.yml
new file mode 100644
index 00000000000..13a1a603771
--- /dev/null
+++ b/.upgradenotes/MDL-82158-2024062501361899.yml
@@ -0,0 +1,75 @@
+issueNumber: MDL-82158
+notes:
+ core_cache:
+ - message: >
+ The following classes have been renamed and now support autoloading.
+
+ Existing classes are currently unaffected.
+
+
+ | Old class name | New class name |
+
+ | --- | --- |
+
+ | `\cache_definition` | `\core_cache\definition` |
+
+ | `\cache_request` | `\core_cache\request_cache` |
+
+ | `\cache_session` | `\core_cache\session_cache` |
+
+ | `\cache_cached_object` | `\core_cache\cached_object` |
+
+ | `\cache_config` | `\core_cache\config` |
+
+ | `\cache_config_writer` | `\core_cache\config_writer` |
+
+ | `\cache_config_disabled` | `\core_cache\disabled_config` |
+
+ | `\cache_disabled` | `\core_cache\disabled_cache` |
+
+ | `\config_writer` | `\core_cache\config_writer` |
+
+ | `\cache_data_source` | `\core_cache\data_source_interface` |
+
+ | `\cache_data_source_versionable` | `\core_cache\versionable_data_source_interface` |
+
+ | `\cache_exception` | `\core_cache\exception/cache_exception` |
+
+ | `\cache_factory` | `\core_cache\factory` |
+
+ | `\cache_factory_disabled` | `\core_cache\disabled_factory` |
+
+ | `\cache_helper` | `\core_cache\helper` |
+
+ | `\cache_is_key_aware` | `\core_cache\key_aware_cache_interface` |
+
+ | `\cache_is_lockable` | `\core_cache\lockable_cache_interface` |
+
+ | `\cache_is_searchable` | `\core_cache\searchable_cache_interface` |
+
+ | `\cache_is_configurable` | `\core_cache\configurable_cache_interface` |
+
+ | `\cache_loader` | `\core_cache\loader_interface` |
+
+ | `\cache_loader_with_locking` | `\core_cache\loader_with_locking_interface` |
+
+ | `\cache_lock_interface` | `\core_cache\cache_lock_interface` |
+
+ | `\cache_store` | `\core_cache\store` |
+
+ | `\cache_store_interface` | `\core_cache\store_interface` |
+
+ | `\cache_ttl_wrapper` | `\core_cache\ttl_wrapper` |
+
+ | `\cacheable_object` | `\core_cache\cacheable_object_interface` |
+
+ | `\cacheable_object_array` | `\core_cache\cacheable_object_array` |
+
+ | `\cache_definition_mappings_form` | `\core_cache\form/cache_definition_mappings_form` |
+
+ | `\cache_definition_sharing_form` | `\core_cache\form/cache_definition_sharing_form` |
+
+ | `\cache_lock_form` | `\core_cache\form/cache_lock_form` |
+
+ | `\cache_mode_mappings_form` | `\core_cache\form/cache_mode_mappings_form` |
+ type: improved
diff --git a/admin/cli/install.php b/admin/cli/install.php
index 440a3d7ef87..bcdaad9a1d9 100644
--- a/admin/cli/install.php
+++ b/admin/cli/install.php
@@ -195,7 +195,6 @@ require_once($CFG->libdir.'/moodlelib.php');
require_once($CFG->libdir.'/deprecatedlib.php');
require_once($CFG->libdir.'/adminlib.php');
require_once($CFG->libdir.'/componentlib.class.php');
-require_once($CFG->dirroot.'/cache/lib.php');
require($CFG->dirroot.'/version.php');
$CFG->target_release = $release;
diff --git a/admin/tool/uploadcourse/classes/helper.php b/admin/tool/uploadcourse/classes/helper.php
index 95291f6bdc8..80585b8cd90 100644
--- a/admin/tool/uploadcourse/classes/helper.php
+++ b/admin/tool/uploadcourse/classes/helper.php
@@ -23,7 +23,6 @@
*/
defined('MOODLE_INTERNAL') || die();
-require_once($CFG->dirroot . '/cache/lib.php');
require_once($CFG->dirroot . '/backup/util/includes/backup_includes.php');
require_once($CFG->dirroot . '/backup/util/includes/restore_includes.php');
@@ -605,4 +604,4 @@ class tool_uploadcourse_helper {
}
return $id;
}
-}
\ No newline at end of file
+}
diff --git a/cache/README.md b/cache/README.md
index d225aa62572..c7e9a6da525 100644
--- a/cache/README.md
+++ b/cache/README.md
@@ -8,7 +8,7 @@ A definition:
$definitions = array(
'string' => array( // Required, unique to the component
- 'mode' => cache_store::MODE_APPLICATION, // Required
+ 'mode' => \core_cache\store::MODE_APPLICATION, // Required
'simplekeys' => false, // Optional
'simpledata' => false, // Optional
'requireidentifiers' => array( // Optional
@@ -38,7 +38,7 @@ A definition:
Getting something from a cache using the definition:
- $cache = cache::make('core', 'string');
+ $cache = \core_cache\cache::make('core', 'string');
if (!$component = $cache->get('component')) {
// get returns false if its not there and can't be loaded.
$component = generate_data();
@@ -47,7 +47,7 @@ Getting something from a cache using the definition:
The same thing but using params:
- $cache = cache::make_from_params(cache_store::MODE_APPLICATION, 'core', 'string');
+ $cache = \core_cache\cache::make_from_params(\core_cache\store::MODE_APPLICATION, 'core', 'string');
if (!$component = $cache->get('component')) {
// get returns false if its not there and can't be loaded.
$component = generate_data();
@@ -56,7 +56,7 @@ The same thing but using params:
If a data source had been specified in the definition, the following would be all that was needed.
- $cache = cache::make('core', 'string');
+ $cache = \core_cache\cache::make('core', 'string');
$component = $cache->get('component');
Disabling the cache stores.
@@ -67,9 +67,9 @@ While the cache API must still be functional in order for calls to it to work it
define('CACHE_DISABLE_STORES', true);
// Disable the cache within your script when you want with:
- cache_factory::disable_stores();
+ \core_cache\factory::disable_stores();
// If you disabled it using the above means you can re-enable it with:
- cache_factory::reset();
+ \core_cache\factory::reset();
Disabling the cache entirely.
Like above there are times when you want the cache to avoid initialising anything it doesn't absolutely need. Things such as installation and upgrade require this functionality.
@@ -90,7 +90,7 @@ The loader is central to the whole thing.
It is used by the end developer to get an object that handles caching.
90% of end developers will not need to know or use anything else in the cache API.
In order to get a loader you must use one of two static methods, make or make_from_params.
-The loader has been kept as simple as possible, interaction is summarised by the cache_loader interface.
+The loader has been kept as simple as possible, interaction is summarised by the core_cache\loader_interface interface.
Internally there is lots of magic going on. The important parts to know about are:
* There are two ways to get a loader, the first with a definition (discussed below) the second with params. When params are used they are turned into an adhoc definition with default params.
* A loader is passed three things when being constructed, a definition, a store, and another loader or datasource if there is either.
@@ -106,9 +106,9 @@ The store is the bridge between the cache API and a cache solution.
Cache store plugins exist within moodle/cache/store.
The administrator of a site can configure multiple instances of each plugin, the configuration gets initialised as a store for the loader when required in code (during construction of the loader).
The following points highlight things you should know about stores.
-* A cache_store interface is used to define the requirements of a store plugin.
-* The store plugin can inherit the cache_is_lockable interface to handle its own locking.
-* The store plugin can inherit the cache_is_key_aware interface to handle is own has checks.
+* A \core_cache\store interface is used to define the requirements of a store plugin.
+* The store plugin can inherit the \core_cache\lockable_cache_interface interface to handle its own locking.
+* The store plugin can inherit the \core_cache\key_aware_cache_interface interface to handle is own has checks.
* Store plugins inform the cache API about the things they support. Features can be required by a definition.
* Data guarantee - Data is guaranteed to exist in the cache once it is set there. It is never cleaned up to free space or because it has not been recently used.
* Multiple identifiers - Rather than a single string key, the parts that make up the key are passed as an array.
@@ -141,7 +141,7 @@ The following optional settings can also be defined:
* maxsize - This gives a cache an indication about the maximum items it should store. Cache stores don't have to use this, it is up to them to decide if its required.
* overrideclass - If provided this class will be used for the loader. It must extend one of the core loader classes (based upon mode).
* overrideclassfile - Included if required when using the overrideclass param.
-* datasource - If provided this class will be used as a data source for the definition. It must implement the cache_data_source interface.
+* datasource - If provided this class will be used as a data source for the definition. It must implement the \core_cache\data_source_interface interface.
* datasourcefile - Included if required when using the datasource param.
* staticacceleration - Any data passing through the cache will be held onto to make subsequent requests for it faster.
* staticaccelerationsize - If set to an int this will be the maximum number of items stored in the static acceleration array.
@@ -171,7 +171,7 @@ By default all sharing options are available to select. This particular option a
### Data source
Data sources allow cache _misses_ (requests for a key that doesn't exist) to be handled and loaded internally.
The loader gets used as the last resort if provided and means that code using the cache doesn't need to handle the situation that information isn't cached.
-They can be specified in a cache definition and must implement the cache_data_source interface.
+They can be specified in a cache definition and must implement the \core_cache\data_source_interface interface.
### How it all chains together.
Consider the following:
@@ -212,12 +212,12 @@ Other internal magic you should be aware of
The following should fill you in on a bit more of the behind-the-scenes stuff for the cache API.
### Helper class
-There is a helper class called cache_helper which is abstract with static methods.
+There is a helper class called \core_cache\helper which is abstract with static methods.
This class handles much of the internal generation and initialisation requirements.
In normal use this class will not be needed outside of the API (mostly internal use only)
### Configuration
-There are two configuration classes cache_config and cache_config_writer.
+There are two configuration classes \core_cache\config and \core_cache\config_writer.
The reader class is used for every request, the writer is only used when modifying the configuration.
Because the cache API is designed to cache database configuration and meta data it must be able to operate prior to database configuration being loaded.
To get around this we store the configuration information in a file in the dataroot.
diff --git a/cache/admin.php b/cache/admin.php
index 6da94ffc69e..8e5cf809b48 100644
--- a/cache/admin.php
+++ b/cache/admin.php
@@ -25,10 +25,11 @@
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
+use core_cache\factory as cache_factory;
+use core_cache\helper as cache_helper;
+
require_once('../config.php');
require_once($CFG->dirroot.'/lib/adminlib.php');
-require_once($CFG->dirroot.'/cache/locallib.php');
-require_once($CFG->dirroot.'/cache/forms.php');
// The first time the user visits this page we are going to reparse the definitions.
// Just ensures that everything is up to date.
diff --git a/cache/classes/administration_helper.php b/cache/classes/administration_helper.php
index 7ce90f55975..9e553364010 100644
--- a/cache/classes/administration_helper.php
+++ b/cache/classes/administration_helper.php
@@ -14,47 +14,33 @@
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see .
-/**
- * Cache administration helper.
- *
- * This file is part of Moodle's cache API, affectionately called MUC.
- * It contains the components that are requried in order to use caching.
- *
- * @package core
- * @category cache
- * @author Peter Burnett
- * @copyright 2020 Catalyst IT
- * @copyright 2012 Sam Hemelryk
- * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
- */
-
namespace core_cache;
-defined('MOODLE_INTERNAL') || die();
-use cache_helper, cache_store, cache_config, cache_factory, cache_definition;
+use core_component;
+use core\output\pix_icon;
+use lang_string;
/**
* Administration helper base class.
*
* Defines abstract methods for a subclass to define the admin page.
*
- * @package core
+ * @package core_cache
* @category cache
* @author Peter Burnett
* @copyright 2020 Catalyst IT
* @copyright 2012 Sam Hemelryk
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
-abstract class administration_helper extends cache_helper {
-
+abstract class administration_helper extends helper {
/**
* Returns an array containing all of the information about stores a renderer needs.
* @return array
*/
public static function get_store_instance_summaries(): array {
- $return = array();
- $default = array();
- $instance = \cache_config::instance();
+ $return = [];
+ $default = [];
+ $instance = config::instance();
$stores = $instance->get_all_stores();
$locks = $instance->get_locks();
foreach ($stores as $name => $details) {
@@ -64,7 +50,7 @@ abstract class administration_helper extends cache_helper {
$store = new $class($details['name'], $details['configuration']);
}
$lock = (isset($details['lock'])) ? $locks[$details['lock']] : $instance->get_default_lock();
- $record = array(
+ $record = [
'name' => $name,
'plugin' => $details['plugin'],
'default' => $details['default'],
@@ -72,24 +58,24 @@ abstract class administration_helper extends cache_helper {
'requirementsmet' => $class::are_requirements_met(),
'mappings' => 0,
'lock' => $lock,
- 'modes' => array(
- cache_store::MODE_APPLICATION =>
- ($class::get_supported_modes($return) & cache_store::MODE_APPLICATION) == cache_store::MODE_APPLICATION,
- cache_store::MODE_SESSION =>
- ($class::get_supported_modes($return) & cache_store::MODE_SESSION) == cache_store::MODE_SESSION,
- cache_store::MODE_REQUEST =>
- ($class::get_supported_modes($return) & cache_store::MODE_REQUEST) == cache_store::MODE_REQUEST,
- ),
- 'supports' => array(
+ 'modes' => [
+ store::MODE_APPLICATION =>
+ ($class::get_supported_modes($return) & store::MODE_APPLICATION) == store::MODE_APPLICATION,
+ store::MODE_SESSION =>
+ ($class::get_supported_modes($return) & store::MODE_SESSION) == store::MODE_SESSION,
+ store::MODE_REQUEST =>
+ ($class::get_supported_modes($return) & store::MODE_REQUEST) == store::MODE_REQUEST,
+ ],
+ 'supports' => [
'multipleidentifiers' => $store ? $store->supports_multiple_identifiers() : false,
'dataguarantee' => $store ? $store->supports_data_guarantee() : false,
'nativettl' => $store ? $store->supports_native_ttl() : false,
- 'nativelocking' => ($store instanceof \cache_is_lockable),
- 'keyawareness' => ($store instanceof \cache_is_key_aware),
- 'searchable' => ($store instanceof \cache_is_searchable)
- ),
- 'warnings' => $store ? $store->get_warnings() : array()
- );
+ 'nativelocking' => ($store instanceof lockable_cache_interface),
+ 'keyawareness' => ($store instanceof key_aware_cache_interface),
+ 'searchable' => ($store instanceof searchable_cache_interface),
+ ],
+ 'warnings' => $store ? $store->get_warnings() : [],
+ ];
if (empty($details['default'])) {
$return[$name] = $record;
} else {
@@ -136,31 +122,31 @@ abstract class administration_helper extends cache_helper {
* See the code below for details
*/
public static function get_store_plugin_summaries(): array {
- $return = array();
+ $return = [];
$plugins = \core_component::get_plugin_list_with_file('cachestore', 'lib.php', true);
foreach ($plugins as $plugin => $path) {
- $class = 'cachestore_'.$plugin;
- $return[$plugin] = array(
- 'name' => get_string('pluginname', 'cachestore_'.$plugin),
+ $class = 'cachestore_' . $plugin;
+ $return[$plugin] = [
+ 'name' => get_string('pluginname', 'cachestore_' . $plugin),
'requirementsmet' => $class::are_requirements_met(),
'instances' => 0,
- 'modes' => array(
- cache_store::MODE_APPLICATION => ($class::get_supported_modes() & cache_store::MODE_APPLICATION),
- cache_store::MODE_SESSION => ($class::get_supported_modes() & cache_store::MODE_SESSION),
- cache_store::MODE_REQUEST => ($class::get_supported_modes() & cache_store::MODE_REQUEST),
- ),
- 'supports' => array(
- 'multipleidentifiers' => ($class::get_supported_features() & cache_store::SUPPORTS_MULTIPLE_IDENTIFIERS),
- 'dataguarantee' => ($class::get_supported_features() & cache_store::SUPPORTS_DATA_GUARANTEE),
- 'nativettl' => ($class::get_supported_features() & cache_store::SUPPORTS_NATIVE_TTL),
- 'nativelocking' => (in_array('cache_is_lockable', class_implements($class))),
- 'keyawareness' => (array_key_exists('cache_is_key_aware', class_implements($class))),
- ),
- 'canaddinstance' => ($class::can_add_instance() && $class::are_requirements_met())
- );
+ 'modes' => [
+ store::MODE_APPLICATION => ($class::get_supported_modes() & store::MODE_APPLICATION),
+ store::MODE_SESSION => ($class::get_supported_modes() & store::MODE_SESSION),
+ store::MODE_REQUEST => ($class::get_supported_modes() & store::MODE_REQUEST),
+ ],
+ 'supports' => [
+ 'multipleidentifiers' => ($class::get_supported_features() & store::SUPPORTS_MULTIPLE_IDENTIFIERS),
+ 'dataguarantee' => ($class::get_supported_features() & store::SUPPORTS_DATA_GUARANTEE),
+ 'nativettl' => ($class::get_supported_features() & store::SUPPORTS_NATIVE_TTL),
+ 'nativelocking' => (in_array(lockable_cache_interface::class, class_implements($class))),
+ 'keyawareness' => (array_key_exists(key_aware_cache_interface::class, class_implements($class))),
+ ],
+ 'canaddinstance' => ($class::can_add_instance() && $class::are_requirements_met()),
+ ];
}
- $instance = cache_config::instance();
+ $instance = config::instance();
$stores = $instance->get_all_stores();
foreach ($stores as $store) {
$plugin = $store['plugin'];
@@ -179,28 +165,28 @@ abstract class administration_helper extends cache_helper {
* See the code below for details
*/
public static function get_definition_summaries(): array {
- $factory = cache_factory::instance();
+ $factory = factory::instance();
$config = $factory->create_config_instance();
- $storenames = array();
+ $storenames = [];
foreach ($config->get_all_stores() as $key => $store) {
if (!empty($store['default'])) {
- $storenames[$key] = new \lang_string('store_'.$key, 'cache');
+ $storenames[$key] = new lang_string('store_' . $key, 'cache');
} else {
$storenames[$store['name']] = $store['name'];
}
}
- /* @var cache_definition[] $definitions */
+ /* @var definition[] $definitions */
$definitions = [];
$return = [];
foreach ($config->get_definitions() as $key => $definition) {
- $definitions[$key] = cache_definition::load($definition['component'].'/'.$definition['area'], $definition);
+ $definitions[$key] = definition::load($definition['component'] . '/' . $definition['area'], $definition);
}
foreach ($definitions as $id => $definition) {
- $mappings = array();
- foreach (cache_helper::get_stores_suitable_for_definition($definition) as $store) {
+ $mappings = [];
+ foreach (helper::get_stores_suitable_for_definition($definition) as $store) {
$mappings[] = $storenames[$store->my_name()];
}
- $return[$id] = array(
+ $return[$id] = [
'id' => $id,
'name' => $definition->get_name(),
'mode' => $definition->get_mode(),
@@ -210,8 +196,8 @@ abstract class administration_helper extends cache_helper {
'canuselocalstore' => $definition->can_use_localstore(),
'sharingoptions' => self::get_definition_sharing_options($definition->get_sharing_options(), false),
'selectedsharingoption' => self::get_definition_sharing_options($definition->get_selected_sharing_option(), true),
- 'userinputsharingkey' => $definition->get_user_input_sharing_key()
- );
+ 'userinputsharingkey' => $definition->get_user_input_sharing_key(),
+ ];
}
return $return;
}
@@ -223,20 +209,20 @@ abstract class administration_helper extends cache_helper {
*/
public static function get_default_mode_stores(): array {
global $OUTPUT;
- $instance = cache_config::instance();
- $adequatestores = cache_helper::get_stores_suitable_for_mode_default();
- $icon = new \pix_icon('i/warning', new \lang_string('inadequatestoreformapping', 'cache'));
- $storenames = array();
+ $instance = config::instance();
+ $adequatestores = helper::get_stores_suitable_for_mode_default();
+ $icon = new pix_icon('i/warning', new lang_string('inadequatestoreformapping', 'cache'));
+ $storenames = [];
foreach ($instance->get_all_stores() as $key => $store) {
if (!empty($store['default'])) {
- $storenames[$key] = new \lang_string('store_'.$key, 'cache');
+ $storenames[$key] = new lang_string('store_' . $key, 'cache');
}
}
- $modemappings = array(
- cache_store::MODE_APPLICATION => array(),
- cache_store::MODE_SESSION => array(),
- cache_store::MODE_REQUEST => array(),
- );
+ $modemappings = [
+ store::MODE_APPLICATION => [],
+ store::MODE_SESSION => [],
+ store::MODE_REQUEST => [],
+ ];
foreach ($instance->get_mode_mappings() as $mapping) {
$mode = $mapping['mode'];
if (!array_key_exists($mode, $modemappings)) {
@@ -249,7 +235,7 @@ abstract class administration_helper extends cache_helper {
$modemappings[$mode][$mapping['store']] = $mapping['store'];
}
if (!array_key_exists($mapping['store'], $adequatestores)) {
- $modemappings[$mode][$mapping['store']] = $modemappings[$mode][$mapping['store']].' '.$OUTPUT->render($icon);
+ $modemappings[$mode][$mapping['store']] = $modemappings[$mode][$mapping['store']] . ' ' . $OUTPUT->render($icon);
}
}
return $modemappings;
@@ -261,13 +247,13 @@ abstract class administration_helper extends cache_helper {
* @return array array of lock summaries.
*/
public static function get_lock_summaries(): array {
- $locks = array();
- $instance = cache_config::instance();
+ $locks = [];
+ $instance = config::instance();
$stores = $instance->get_all_stores();
foreach ($instance->get_locks() as $lock) {
$default = !empty($lock['default']);
if ($default) {
- $name = new \lang_string($lock['name'], 'cache');
+ $name = new lang_string($lock['name'], 'cache');
} else {
$name = $lock['name'];
}
@@ -277,12 +263,12 @@ abstract class administration_helper extends cache_helper {
$uses++;
}
}
- $lockdata = array(
+ $lockdata = [
'name' => $name,
'default' => $default,
'uses' => $uses,
- 'type' => get_string('pluginname', $lock['type'])
- );
+ 'type' => get_string('pluginname', $lock['type']),
+ ];
$locks[$lock['name']] = $lockdata;
}
return $locks;
@@ -296,19 +282,19 @@ abstract class administration_helper extends cache_helper {
* @return array An array of lang_string's.
*/
public static function get_definition_sharing_options(int $sharingoption, bool $isselectedoptions = true): array {
- $options = array();
+ $options = [];
$prefix = ($isselectedoptions) ? 'sharingselected' : 'sharing';
- if ($sharingoption & cache_definition::SHARING_ALL) {
- $options[cache_definition::SHARING_ALL] = new \lang_string($prefix.'_all', 'cache');
+ if ($sharingoption & definition::SHARING_ALL) {
+ $options[definition::SHARING_ALL] = new lang_string($prefix . '_all', 'cache');
}
- if ($sharingoption & cache_definition::SHARING_SITEID) {
- $options[cache_definition::SHARING_SITEID] = new \lang_string($prefix.'_siteid', 'cache');
+ if ($sharingoption & definition::SHARING_SITEID) {
+ $options[definition::SHARING_SITEID] = new lang_string($prefix . '_siteid', 'cache');
}
- if ($sharingoption & cache_definition::SHARING_VERSION) {
- $options[cache_definition::SHARING_VERSION] = new \lang_string($prefix.'_version', 'cache');
+ if ($sharingoption & definition::SHARING_VERSION) {
+ $options[definition::SHARING_VERSION] = new lang_string($prefix . '_version', 'cache');
}
- if ($sharingoption & cache_definition::SHARING_INPUT) {
- $options[cache_definition::SHARING_INPUT] = new \lang_string($prefix.'_input', 'cache');
+ if ($sharingoption & definition::SHARING_INPUT) {
+ $options[definition::SHARING_INPUT] = new lang_string($prefix . '_input', 'cache');
}
return $options;
}
@@ -324,13 +310,13 @@ abstract class administration_helper extends cache_helper {
* 3. An array of default stores
*/
public static function get_definition_store_options(string $component, string $area): array {
- $factory = cache_factory::instance();
+ $factory = factory::instance();
$definition = $factory->create_definition($component, $area);
- $config = cache_config::instance();
+ $config = config::instance();
$currentstores = $config->get_stores_for_definition($definition);
$possiblestores = $config->get_stores($definition->get_mode(), $definition->get_requirements_bin());
- $defaults = array();
+ $defaults = [];
foreach ($currentstores as $key => $store) {
if (!empty($store['default'])) {
$defaults[] = $key;
@@ -343,7 +329,7 @@ abstract class administration_helper extends cache_helper {
$possiblestores[$key] = $store;
}
}
- return array($currentstores, $possiblestores, $defaults);
+ return [$currentstores, $possiblestores, $defaults];
}
/**
@@ -354,7 +340,7 @@ abstract class administration_helper extends cache_helper {
* @return array array of actions.
*/
public function get_store_plugin_actions(string $name, array $plugindetails): array {
- return array();
+ return [];
}
/**
@@ -365,7 +351,7 @@ abstract class administration_helper extends cache_helper {
* @return array array of actions.
*/
public function get_store_instance_actions(string $name, array $storedetails): array {
- return array();
+ return [];
}
/**
@@ -376,7 +362,7 @@ abstract class administration_helper extends cache_helper {
* @return array array of actions.
*/
public function get_definition_actions(\context $context, array $definitionsummary): array {
- return array();
+ return [];
}
/**
@@ -385,7 +371,7 @@ abstract class administration_helper extends cache_helper {
* @return array array of locks that are addable.
*/
public function get_addable_lock_options(): array {
- return array();
+ return [];
}
/**
diff --git a/cache/classes/allow_temporary_caches.php b/cache/classes/allow_temporary_caches.php
index 83379c19df8..697cac69e71 100644
--- a/cache/classes/allow_temporary_caches.php
+++ b/cache/classes/allow_temporary_caches.php
@@ -19,7 +19,7 @@ namespace core_cache;
/**
* Create and keep an instance of this class to allow temporary caches when caches are disabled.
*
- * This class works together with code in {@see cache_factory_disabled}.
+ * This class works together with code in {@see disabled_factory}.
*
* The intention is that temporary cache should be short-lived (not for the entire install process),
* which avoids two problems: first, that we might run out of memory for the caches, and second,
@@ -60,12 +60,9 @@ class allow_temporary_caches {
* If there are no other instances of this object, then all temporary caches will be discarded.
*/
public function __destruct() {
- global $CFG;
- require_once($CFG->dirroot . '/cache/disabledlib.php');
-
self::$references--;
if (self::$references === 0) {
- \cache_factory_disabled::clear_temporary_caches();
+ disabled_factory::clear_temporary_caches();
}
}
diff --git a/cache/classes/application_cache.php b/cache/classes/application_cache.php
new file mode 100644
index 00000000000..c7898399d4a
--- /dev/null
+++ b/cache/classes/application_cache.php
@@ -0,0 +1,350 @@
+.
+
+namespace core_cache;
+
+use core\exception\coding_exception;
+use core\exception\moodle_exception;
+
+/**
+ * An application cache.
+ *
+ * This class is used for application caches returned by the cache::make methods.
+ * On top of the standard functionality it also allows locking to be required and or manually operated.
+ *
+ * This cache class should never be interacted with directly. Instead you should always use the cache::make methods.
+ * It is technically possible to call those methods through this class however there is no guarantee that you will get an
+ * instance of this class back again.
+ *
+ * @internal don't use me directly.
+ *
+ * @package core_cache
+ * @category cache
+ * @copyright 2012 Sam Hemelryk
+ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+class application_cache extends cache implements loader_with_locking_interface {
+ /**
+ * Lock identifier.
+ * This is used to ensure the lock belongs to the cache instance + definition + user.
+ * @var string
+ */
+ protected $lockidentifier;
+
+ /**
+ * Gets set to true if the cache's primary store natively supports locking.
+ * If it does then we use that, otherwise we need to instantiate a second store to use for locking.
+ * @var store
+ */
+ protected $nativelocking = null;
+
+ /**
+ * Gets set to true if the cache is going to be using locking.
+ * This isn't a requirement, it doesn't need to use locking (most won't) and this bool is used to quickly check things.
+ * If required then locking will be forced for the get|set|delete operation.
+ * @var bool
+ */
+ protected $requirelocking = false;
+
+ /**
+ * Gets set to true if the cache writes (set|delete) must have a manual lock created first
+ * @var bool
+ */
+ protected $requirelockingbeforewrite = false;
+
+ /**
+ * Gets set to a store to use for locking if the caches primary store doesn't support locking natively.
+ * @var lockable_cache_interface
+ */
+ protected $cachelockinstance;
+
+ /**
+ * Store a list of locks acquired by this process.
+ * @var array
+ */
+ protected $locks;
+
+ /**
+ * Overrides the cache construct method.
+ *
+ * You should not call this method from your code, instead you should use the cache::make methods.
+ *
+ * @param definition $definition
+ * @param store $store
+ * @param loader_interface|data_source_interface $loader
+ */
+ public function __construct(definition $definition, store $store, $loader = null) {
+ parent::__construct($definition, $store, $loader);
+ $this->nativelocking = $this->store_supports_native_locking();
+ if ($definition->require_locking()) {
+ $this->requirelocking = true;
+ $this->requirelockingbeforewrite = $definition->require_locking_before_write();
+ }
+
+ $this->handle_invalidation_events();
+ }
+
+ /**
+ * Returns the identifier to use
+ *
+ * @staticvar int $instances Counts the number of instances. Used as part of the lock identifier.
+ * @return string
+ */
+ public function get_identifier() {
+ static $instances = 0;
+ if ($this->lockidentifier === null) {
+ $this->lockidentifier = md5(
+ $this->get_definition()->generate_definition_hash() .
+ sesskey() .
+ $instances++ .
+ application_cache::class,
+ );
+ }
+ return $this->lockidentifier;
+ }
+
+ /**
+ * Fixes the instance up after a clone.
+ */
+ public function __clone() {
+ // Force a new idenfitier.
+ $this->lockidentifier = null;
+ }
+
+ /**
+ * Acquires a lock on the given key.
+ *
+ * This is done automatically if the definition requires it.
+ * It is recommended to use a definition if you want to have locking although it is possible to do locking without having
+ * it required by the definition.
+ * The problem with such an approach is that you cannot ensure that code will consistently use locking. You will need to
+ * rely on the integrators review skills.
+ *
+ * @param string|int $key The key as given to get|set|delete
+ * @return bool Always returns true
+ * @throws moodle_exception If the lock cannot be obtained
+ */
+ public function acquire_lock($key) {
+ $releaseparent = false;
+ try {
+ if ($this->get_loader() !== false) {
+ $this->get_loader()->acquire_lock($key);
+ // We need to release this lock later if the lock is not successful.
+ $releaseparent = true;
+ }
+ $hashedkey = helper::hash_key($key, $this->get_definition());
+ $before = microtime(true);
+ if ($this->nativelocking) {
+ $lock = $this->get_store()->acquire_lock($hashedkey, $this->get_identifier());
+ } else {
+ $this->ensure_cachelock_available();
+ $lock = $this->cachelockinstance->lock($hashedkey, $this->get_identifier());
+ }
+ $after = microtime(true);
+ if ($lock) {
+ $this->locks[$hashedkey] = $lock;
+ if (MDL_PERF || $this->perfdebug) {
+ \core\lock\timing_wrapper_lock_factory::record_lock_data(
+ $after,
+ $before,
+ $this->get_definition()->get_id(),
+ $hashedkey,
+ $lock,
+ $this->get_identifier() . $hashedkey
+ );
+ }
+ $releaseparent = false;
+ return true;
+ } else {
+ throw new moodle_exception(
+ 'ex_unabletolock',
+ 'cache',
+ '',
+ null,
+ 'store: ' . get_class($this->get_store()) . ', lock: ' . $hashedkey
+ );
+ }
+ } finally {
+ // Release the parent lock if we acquired it, then threw an exception.
+ if ($releaseparent) {
+ $this->get_loader()->release_lock($key);
+ }
+ }
+ }
+
+ /**
+ * Checks if this cache has a lock on the given key.
+ *
+ * @param string|int $key The key as given to get|set|delete
+ * @return bool|null Returns true if there is a lock and this cache has it, null if no one has a lock on that key, false if
+ * someone else has the lock.
+ */
+ public function check_lock_state($key) {
+ $key = helper::hash_key($key, $this->get_definition());
+ if (!empty($this->locks[$key])) {
+ return true; // Shortcut to save having to make a call to the cache store if the lock is held by this process.
+ }
+ if ($this->nativelocking) {
+ return $this->get_store()->check_lock_state($key, $this->get_identifier());
+ } else {
+ $this->ensure_cachelock_available();
+ return $this->cachelockinstance->check_state($key, $this->get_identifier());
+ }
+ }
+
+ /**
+ * Releases the lock this cache has on the given key
+ *
+ * @param string|int $key
+ * @return bool True if the operation succeeded, false otherwise.
+ */
+ public function release_lock($key) {
+ $loaderkey = $key;
+ $key = helper::hash_key($key, $this->get_definition());
+ if ($this->nativelocking) {
+ $released = $this->get_store()->release_lock($key, $this->get_identifier());
+ } else {
+ $this->ensure_cachelock_available();
+ $released = $this->cachelockinstance->unlock($key, $this->get_identifier());
+ }
+ if ($released && array_key_exists($key, $this->locks)) {
+ unset($this->locks[$key]);
+ if (MDL_PERF || $this->perfdebug) {
+ \core\lock\timing_wrapper_lock_factory::record_lock_released_data($this->get_identifier() . $key);
+ }
+ }
+ if ($this->get_loader() !== false) {
+ $this->get_loader()->release_lock($loaderkey);
+ }
+ return $released;
+ }
+
+ /**
+ * Ensure that the dedicated lock store is ready to go.
+ *
+ * This should only happen if the cache store doesn't natively support it.
+ */
+ protected function ensure_cachelock_available() {
+ if ($this->cachelockinstance === null) {
+ $this->cachelockinstance = helper::get_cachelock_for_store($this->get_store());
+ }
+ }
+
+ /**
+ * Sends a key => value pair to the cache.
+ *
+ *
+ * // This code will add four entries to the cache, one for each url.
+ * $cache->set('main', 'http://moodle.org');
+ * $cache->set('docs', 'http://docs.moodle.org');
+ * $cache->set('tracker', 'http://tracker.moodle.org');
+ * $cache->set('qa', 'http://qa.moodle.net');
+ *
+ *
+ * @param string|int $key The key for the data being requested.
+ * @param int $version Version number
+ * @param mixed $data The data to set against the key.
+ * @param bool $setparents If true, sets all parent loaders, otherwise only this one
+ * @return bool True on success, false otherwise.
+ * @throws coding_exception If a required lock has not beeen acquired
+ */
+ protected function set_implementation($key, int $version, $data, bool $setparents = true): bool {
+ if ($this->requirelockingbeforewrite && !$this->check_lock_state($key)) {
+ throw new coding_exception('Attempted to set cache key "' . $key . '" without a lock. '
+ . 'Locking before writes is required for ' . $this->get_definition()->get_id());
+ }
+ return parent::set_implementation($key, $version, $data, $setparents);
+ }
+
+ /**
+ * Sends several key => value pairs to the cache.
+ *
+ * Using this function comes with potential performance implications.
+ * Not all cache stores will support get_many/set_many operations and in order to replicate this functionality will call
+ * the equivalent singular method for each item provided.
+ * This should not deter you from using this function as there is a performance benefit in situations where the cache store
+ * does support it, but you should be aware of this fact.
+ *
+ *
+ * // This code will add four entries to the cache, one for each url.
+ * $cache->set_many(array(
+ * 'main' => 'http://moodle.org',
+ * 'docs' => 'http://docs.moodle.org',
+ * 'tracker' => 'http://tracker.moodle.org',
+ * 'qa' => ''http://qa.moodle.net'
+ * ));
+ *
+ *
+ * @param array $keyvaluearray An array of key => value pairs to send to the cache.
+ * @return int The number of items successfully set. It is up to the developer to check this matches the number of items.
+ * ... if they care that is.
+ * @throws coding_exception If a required lock has not beeen acquired
+ */
+ public function set_many(array $keyvaluearray) {
+ if ($this->requirelockingbeforewrite) {
+ foreach ($keyvaluearray as $key => $value) {
+ if (!$this->check_lock_state($key)) {
+ throw new coding_exception('Attempted to set cache key "' . $key . '" without a lock. '
+ . 'Locking before writes is required for ' . $this->get_definition()->get_id());
+ }
+ }
+ }
+ return parent::set_many($keyvaluearray);
+ }
+
+ /**
+ * Delete the given key from the cache.
+ *
+ * @param string|int $key The key to delete.
+ * @param bool $recurse When set to true the key will also be deleted from all stacked cache loaders and their stores.
+ * This happens by default and ensure that all the caches are consistent. It is NOT recommended to change this.
+ * @return bool True of success, false otherwise.
+ * @throws coding_exception If a required lock has not beeen acquired
+ */
+ public function delete($key, $recurse = true) {
+ if ($this->requirelockingbeforewrite && !$this->check_lock_state($key)) {
+ throw new coding_exception('Attempted to delete cache key "' . $key . '" without a lock. '
+ . 'Locking before writes is required for ' . $this->get_definition()->get_id());
+ }
+ return parent::delete($key, $recurse);
+ }
+
+ /**
+ * Delete all of the given keys from the cache.
+ *
+ * @param array $keys The key to delete.
+ * @param bool $recurse When set to true the key will also be deleted from all stacked cache loaders and their stores.
+ * This happens by default and ensure that all the caches are consistent. It is NOT recommended to change this.
+ * @return int The number of items successfully deleted.
+ * @throws coding_exception If a required lock has not beeen acquired
+ */
+ public function delete_many(array $keys, $recurse = true) {
+ if ($this->requirelockingbeforewrite) {
+ foreach ($keys as $key) {
+ if (!$this->check_lock_state($key)) {
+ throw new coding_exception('Attempted to delete cache key "' . $key . '" without a lock. '
+ . 'Locking before writes is required for ' . $this->get_definition()->get_id());
+ }
+ }
+ }
+ return parent::delete_many($keys, $recurse);
+ }
+}
+
+// Alias this class to the old name.
+// This file will be autoloaded by the legacyclasses autoload system.
+// In future all uses of this class will be corrected and the legacy references will be removed.
+class_alias(application_cache::class, \cache_application::class);
diff --git a/cache/classes/loaders.php b/cache/classes/cache.php
similarity index 58%
rename from cache/classes/loaders.php
rename to cache/classes/cache.php
index 36fdb4da40e..ad4b85c67ac 100644
--- a/cache/classes/loaders.php
+++ b/cache/classes/cache.php
@@ -14,19 +14,10 @@
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see .
-/**
- * Cache loaders
- *
- * This file is part of Moodle's cache API, affectionately called MUC.
- * It contains the components that are required in order to use caching.
- *
- * @package core
- * @category cache
- * @copyright 2012 Sam Hemelryk
- * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
- */
+namespace core_cache;
-defined('MOODLE_INTERNAL') || die();
+use core\exception\coding_exception;
+use stdClass;
/**
* The main cache class.
@@ -35,13 +26,12 @@ defined('MOODLE_INTERNAL') || die();
* In order to create an instance of a cache that they can work with they must call one of the static make methods belonging
* to this class.
*
- * @package core
+ * @package core_cache
* @category cache
* @copyright 2012 Sam Hemelryk
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
-class cache implements cache_loader {
-
+class cache implements loader_interface {
/**
* @var int Constant for cache entries that do not have a version number
*/
@@ -65,13 +55,13 @@ class cache implements cache_loader {
/**
* The definition used when loading this cache if there was one.
- * @var cache_definition
+ * @var definition
*/
private $definition = false;
/**
* The cache store that this loader will make use of.
- * @var cache_store
+ * @var store
*/
private $store;
@@ -80,14 +70,14 @@ class cache implements cache_loader {
* If a cache request misses for the store belonging to this loader then the loader
* stored here will be checked next.
* If there is a loader here then $datasource must be false.
- * @var cache_loader|false
+ * @var loader_interface|false
*/
private $loader = false;
/**
* The data source to use if we need to load data (because if doesn't exist in the cache store).
* If there is a data source here then $loader above must be false.
- * @var cache_data_source|false
+ * @var data_source_interface|false
*/
private $datasource = false;
@@ -119,7 +109,7 @@ class cache implements cache_loader {
* Items will be stored in this cache as they were provided. This ensure there is no unnecessary processing taking place.
* @var array
*/
- private $staticaccelerationarray = array();
+ private $staticaccelerationarray = [];
/**
* The number of items in the static acceleration array. Avoids count calls like you wouldn't believe.
@@ -134,7 +124,7 @@ class cache implements cache_loader {
* key that is first on this array.
* @var array
*/
- private $staticaccelerationkeys = array();
+ private $staticaccelerationkeys = [];
/**
* The maximum size of the static acceleration array.
@@ -182,7 +172,7 @@ class cache implements cache_loader {
/**
* Gets set to true if the cache's primary store natively supports locking.
* If it does then we use that, otherwise we need to instantiate a second store to use for locking.
- * @var cache_store|null
+ * @var store|null
*/
protected $nativelocking = null;
@@ -193,17 +183,17 @@ class cache implements cache_loader {
* @param string $area The area for the definition
* @param array $identifiers Any additional identifiers that should be provided to the definition.
* @param string $unused Used to be datasourceaggregate but that was removed and this is now unused.
- * @return cache_application|cache_session|cache_store
+ * @return application_cache|session_cache|store
*/
- public static function make($component, $area, array $identifiers = array(), $unused = null) {
- $factory = cache_factory::instance();
+ public static function make($component, $area, array $identifiers = [], $unused = null) {
+ $factory = factory::instance();
return $factory->create_cache_from_definition($component, $area, $identifiers);
}
/**
* Creates a new cache instance based upon the given params.
*
- * @param int $mode One of cache_store::MODE_*
+ * @param int $mode One of store::MODE_*
* @param string $component The component this cache relates to.
* @param string $area The area this cache relates to.
* @param array $identifiers Any additional identifiers that should be provided to the definition.
@@ -212,10 +202,10 @@ class cache implements cache_loader {
* - simpledata : Set to true if the type of the data you are going to store is scalar, or an array of scalar vars
* - staticacceleration : If set to true the cache will hold onto data passing through it.
* - staticaccelerationsize : The max size for the static acceleration array.
- * @return cache_application|cache_session|cache_request
+ * @return application_cache|session_cache|request_cache
*/
- public static function make_from_params($mode, $component, $area, array $identifiers = array(), array $options = array()) {
- $factory = cache_factory::instance();
+ public static function make_from_params($mode, $component, $area, array $identifiers = [], array $options = []) {
+ $factory = factory::instance();
return $factory->create_cache_from_params($mode, $component, $area, $identifiers, $options);
}
@@ -224,25 +214,25 @@ class cache implements cache_loader {
*
* You should not call this method from your code, instead you should use the cache::make methods.
*
- * This method is public so that the cache_factory is able to instantiate cache instances.
+ * This method is public so that the factory is able to instantiate cache instances.
* Ideally we would make this method protected and expose its construction to the factory method internally somehow.
* The factory class is responsible for this in order to centralise the storage of instances once created. This way if needed
* we can force a reset of the cache API (used during unit testing).
*
- * @param cache_definition $definition The definition for the cache instance.
- * @param cache_store $store The store that cache should use.
- * @param cache_loader|cache_data_source $loader The next loader in the chain or the data source if there is one and there
- * are no other cache_loaders in the chain.
+ * @param definition $definition The definition for the cache instance.
+ * @param store $store The store that cache should use.
+ * @param loader_interface|data_source_interface $loader The next loader in the chain or the data source if there is one
+ * and there are no other loader_interfaces in the chain.
*/
- public function __construct(cache_definition $definition, cache_store $store, $loader = null) {
+ public function __construct(definition $definition, store $store, $loader = null) {
global $CFG;
$this->definition = $definition;
$this->store = $store;
$this->storetype = get_class($store);
$this->perfdebug = (!empty($CFG->perfdebug) and $CFG->perfdebug > 7);
- if ($loader instanceof cache_loader) {
+ if ($loader instanceof loader_interface) {
$this->set_loader($loader);
- } else if ($loader instanceof cache_data_source) {
+ } else if ($loader instanceof data_source_interface) {
$this->set_data_source($loader);
}
$this->definition->generate_definition_hash();
@@ -256,9 +246,9 @@ class cache implements cache_loader {
/**
* Set the loader for this cache.
*
- * @param cache_loader $loader
+ * @param loader_interface $loader
*/
- protected function set_loader(cache_loader $loader): void {
+ protected function set_loader(loader_interface $loader): void {
$this->loader = $loader;
// Mark the loader as a sub (chained) loader.
@@ -268,9 +258,9 @@ class cache implements cache_loader {
/**
* Set the data source for this cache.
*
- * @param cache_data_source $datasource
+ * @param data_source_interface $datasource
*/
- protected function set_data_source(cache_data_source $datasource): void {
+ protected function set_data_source(data_source_interface $datasource): void {
$this->datasource = $datasource;
}
@@ -312,9 +302,9 @@ class cache implements cache_loader {
if ($this->definition->set_identifiers($identifiers)) {
// As static acceleration uses input keys and not parsed keys
// it much be cleared when the identifier set is changed.
- $this->staticaccelerationarray = array();
+ $this->staticaccelerationarray = [];
if ($this->staticaccelerationsize !== false) {
- $this->staticaccelerationkeys = array();
+ $this->staticaccelerationkeys = [];
$this->staticaccelerationcount = 0;
}
}
@@ -368,7 +358,7 @@ class cache implements cache_loader {
*/
$cache = self::make('core', 'eventinvalidation');
$events = $cache->get_many($this->definition->get_invalidation_events());
- $todelete = array();
+ $todelete = [];
$purgeall = false;
// Iterate the returned data for the events.
@@ -470,7 +460,7 @@ class cache implements cache_loader {
}
} else {
// If there's no result, obviously it doesn't meet the required version.
- if (!cache_helper::result_found($result)) {
+ if (!helper::result_found($result)) {
return false;
}
if (!($result instanceof \core_cache\version_wrapper)) {
@@ -503,7 +493,7 @@ class cache implements cache_loader {
if ($usesstaticacceleration) {
$result = $this->static_acceleration_get($key);
- if (cache_helper::result_found($result) && self::check_version($result, $requiredversion)) {
+ if (helper::result_found($result) && self::check_version($result, $requiredversion)) {
if ($requiredversion === self::VERSION_NONE) {
return $result;
} else {
@@ -518,7 +508,7 @@ class cache implements cache_loader {
// 3. Get it from the store. Obviously wasn't in the static acceleration array.
$result = $this->store->get($parsedkey);
- if (cache_helper::result_found($result)) {
+ if (helper::result_found($result)) {
// Check the result has at least the required version.
try {
$validversion = self::check_version($result, $requiredversion);
@@ -548,14 +538,14 @@ class cache implements cache_loader {
$this->store->delete($parsedkey);
}
}
- if (cache_helper::result_found($result)) {
+ if (helper::result_found($result)) {
// Look to see if there's a TTL wrapper. It might be inside a version wrapper.
if ($requiredversion !== self::VERSION_NONE) {
$ttlconsider = $result->data;
} else {
$ttlconsider = $result;
}
- if ($ttlconsider instanceof cache_ttl_wrapper) {
+ if ($ttlconsider instanceof ttl_wrapper) {
if ($ttlconsider->has_expired()) {
$this->store->delete($parsedkey);
$result = false;
@@ -575,16 +565,16 @@ class cache implements cache_loader {
$actualversion = $result->version;
$result = $result->data;
}
- if ($result instanceof cache_cached_object) {
+ if ($result instanceof cached_object) {
$result = $result->restore_object();
}
}
// 4. Load if from the loader/datasource if we don't already have it.
$setaftervalidation = false;
- if (!cache_helper::result_found($result)) {
+ if (!helper::result_found($result)) {
if ($this->perfdebug) {
- cache_helper::record_cache_miss($this->store, $this->definition);
+ helper::record_cache_miss($this->store, $this->definition);
}
if ($this->loader !== false) {
// We must pass the original (unparsed) key to the next loader in the chain.
@@ -599,7 +589,7 @@ class cache implements cache_loader {
if ($requiredversion === self::VERSION_NONE) {
$result = $this->datasource->load_for_cache($key);
} else {
- if (!$this->datasource instanceof cache_data_source_versionable) {
+ if (!$this->datasource instanceof versionable_data_source_interface) {
throw new \coding_exception('Data source is not versionable');
}
$result = $this->datasource->load_for_cache_versioned($key, $requiredversion, $actualversion);
@@ -608,13 +598,13 @@ class cache implements cache_loader {
}
}
}
- $setaftervalidation = (cache_helper::result_found($result));
+ $setaftervalidation = (helper::result_found($result));
} else if ($this->perfdebug) {
$readbytes = $this->store->get_last_io_bytes();
- cache_helper::record_cache_hit($this->store, $this->definition, 1, $readbytes);
+ helper::record_cache_hit($this->store, $this->definition, 1, $readbytes);
}
// 5. Validate strictness.
- if ($strictness === MUST_EXIST && !cache_helper::result_found($result)) {
+ if ($strictness === MUST_EXIST && !helper::result_found($result)) {
throw new coding_exception('Requested key did not exist in any cache stores and could not be loaded.');
}
// 6. Set it to the store if we got it from the loader/datasource. Only set to this direct
@@ -639,7 +629,7 @@ class cache implements cache_loader {
}
}
// 7. Make sure we don't pass back anything that could be a reference.
- // We don't want people modifying the data in the cache.
+ // We don't want people modifying the data in the cache.
if (!$this->store->supports_dereferencing_objects() && !is_scalar($result)) {
// If data is an object it will be a reference.
// If data is an array if may contain references.
@@ -670,12 +660,12 @@ class cache implements cache_loader {
*/
public function get_many(array $keys, $strictness = IGNORE_MISSING) {
- $keysparsed = array();
- $parsedkeys = array();
- $resultpersist = array();
- $resultstore = array();
- $keystofind = array();
- $readbytes = cache_store::IO_BYTES_NOT_SUPPORTED;
+ $keysparsed = [];
+ $parsedkeys = [];
+ $resultpersist = [];
+ $resultstore = [];
+ $keystofind = [];
+ $readbytes = store::IO_BYTES_NOT_SUPPORTED;
// First up check the persist cache for each key.
$isusingpersist = $this->use_static_acceleration();
@@ -704,7 +694,7 @@ class cache implements cache_loader {
}
// Process each item in the result to "unwrap" it.
foreach ($resultstore as $key => $value) {
- if ($value instanceof cache_ttl_wrapper) {
+ if ($value instanceof ttl_wrapper) {
if ($value->has_expired()) {
$value = false;
} else {
@@ -714,7 +704,7 @@ class cache implements cache_loader {
if ($value !== false && $this->use_static_acceleration()) {
$this->static_acceleration_set($keystofind[$key], $value);
}
- if ($value instanceof cache_cached_object) {
+ if ($value instanceof cached_object) {
$value = $value->restore_object();
}
$resultstore[$key] = $value;
@@ -730,7 +720,7 @@ class cache implements cache_loader {
$usingloader = ($this->loader !== false);
$usingsource = (!$usingloader && ($this->datasource !== false));
if ($usingloader || $usingsource) {
- $missingkeys = array();
+ $missingkeys = [];
foreach ($result as $key => $value) {
if ($value === false) {
$missingkeys[] = $parsedkeys[$key];
@@ -765,7 +755,7 @@ class cache implements cache_loader {
}
// Create an array with the original keys and the found values. This will be what we return.
- $fullresult = array();
+ $fullresult = [];
foreach ($result as $key => $value) {
if (!is_scalar($value)) {
// If data is an object it will be a reference.
@@ -797,8 +787,8 @@ class cache implements cache_loader {
$hits++;
}
}
- cache_helper::record_cache_hit($this->store, $this->definition, $hits, $readbytes);
- cache_helper::record_cache_miss($this->store, $this->definition, $misses);
+ helper::record_cache_hit($this->store, $this->definition, $hits, $readbytes);
+ helper::record_cache_miss($this->store, $this->definition, $misses);
}
// Return the result. Phew!
@@ -872,8 +862,8 @@ class cache implements cache_loader {
}
$usestaticacceleration = $this->use_static_acceleration();
- if (is_object($data) && $data instanceof cacheable_object) {
- $data = new cache_cached_object($data);
+ if (is_object($data) && $data instanceof cacheable_object_interface) {
+ $data = new cached_object($data);
} else if (!$this->store->supports_dereferencing_objects() && !is_scalar($data)) {
// If data is an object it will be a reference.
// If data is an array if may contain references.
@@ -892,7 +882,7 @@ class cache implements cache_loader {
}
if ($this->has_a_ttl() && !$this->store_supports_native_ttl()) {
- $data = new cache_ttl_wrapper($data, $this->definition->get_ttl());
+ $data = new ttl_wrapper($data, $this->definition->get_ttl());
}
$parsedkey = $this->parse_key($key);
@@ -902,8 +892,12 @@ class cache implements cache_loader {
$success = $this->store->set($parsedkey, $data);
if ($this->perfdebug) {
- cache_helper::record_cache_set($this->store, $this->definition, 1,
- $this->store->get_last_io_bytes());
+ helper::record_cache_set(
+ $this->store,
+ $this->definition,
+ 1,
+ $this->store->get_last_io_bytes()
+ );
}
return $success;
}
@@ -1010,8 +1004,8 @@ class cache implements cache_loader {
$usestaticaccelerationarray = $this->use_static_acceleration();
$needsdereferencing = !$this->store->supports_dereferencing_objects();
foreach ($keyvaluearray as $key => $value) {
- if (is_object($value) && $value instanceof cacheable_object) {
- $value = new cache_cached_object($value);
+ if (is_object($value) && $value instanceof cacheable_object_interface) {
+ $value = new cached_object($value);
} else if ($needsdereferencing && !is_scalar($value)) {
// If data is an object it will be a reference.
// If data is an array if may contain references.
@@ -1023,17 +1017,21 @@ class cache implements cache_loader {
$this->static_acceleration_set($key, $value);
}
if ($simulatettl) {
- $value = new cache_ttl_wrapper($value, $this->definition->get_ttl());
+ $value = new ttl_wrapper($value, $this->definition->get_ttl());
}
- $data[$key] = array(
+ $data[$key] = [
'key' => $this->parse_key($key),
- 'value' => $value
- );
+ 'value' => $value,
+ ];
}
$successfullyset = $this->store->set_many($data);
if ($this->perfdebug && $successfullyset) {
- cache_helper::record_cache_set($this->store, $this->definition, $successfullyset,
- $this->store->get_last_io_bytes());
+ helper::record_cache_set(
+ $this->store,
+ $this->definition,
+ $successfullyset,
+ $this->store->get_last_io_bytes()
+ );
}
return $successfullyset;
}
@@ -1070,7 +1068,7 @@ class cache implements cache_loader {
// The data has a TTL and the store doesn't support it natively.
// We must fetch the data and expect a ttl wrapper.
$data = $this->store->get($parsedkey);
- $has = ($data instanceof cache_ttl_wrapper && !$data->has_expired());
+ $has = ($data instanceof ttl_wrapper && !$data->has_expired());
} else if (!$this->store_supports_key_awareness()) {
// The store doesn't support key awareness, get the data and check it manually... puke.
// Either no TTL is set of the store supports its handling natively.
@@ -1117,7 +1115,7 @@ class cache implements cache_loader {
}
return true;
}
- $parsedkeys = array_map(array($this, 'parse_key'), $keys);
+ $parsedkeys = array_map([$this, 'parse_key'], $keys);
return $this->store->has_all($parsedkeys);
}
@@ -1151,7 +1149,7 @@ class cache implements cache_loader {
}
}
}
- $parsedkeys = array_map(array($this, 'parse_key'), $keys);
+ $parsedkeys = array_map([$this, 'parse_key'], $keys);
return $this->store->has_any($parsedkeys);
}
@@ -1191,7 +1189,7 @@ class cache implements cache_loader {
// Delete from the bottom of the stack first.
$this->loader->delete_many($keys, $recurse);
}
- $parsedkeys = array_map(array($this, 'parse_key'), $keys);
+ $parsedkeys = array_map([$this, 'parse_key'], $keys);
return $this->store->delete_many($parsedkeys);
}
@@ -1225,8 +1223,8 @@ class cache implements cache_loader {
$result['key'] = $key;
return $result;
}
- // If not we need to generate a hash and to for that we use the cache_helper.
- return cache_helper::hash_key($key, $this->definition);
+ // If not we need to generate a hash and to for that we use the helper.
+ return helper::hash_key($key, $this->definition);
}
/**
@@ -1251,7 +1249,7 @@ class cache implements cache_loader {
/**
* Returns the cache definition.
*
- * @return cache_definition
+ * @return definition
*/
protected function get_definition() {
return $this->definition;
@@ -1260,7 +1258,7 @@ class cache implements cache_loader {
/**
* Returns the cache store
*
- * @return cache_store
+ * @return store
*/
protected function get_store() {
return $this->store;
@@ -1280,7 +1278,7 @@ class cache implements cache_loader {
* Returns the data source associated with this cache.
*
* @since Moodle 2.4.4
- * @return cache_data_source|false
+ * @return data_source_interface|false
*/
protected function get_datasource() {
return $this->datasource;
@@ -1293,7 +1291,7 @@ class cache implements cache_loader {
*/
protected function store_supports_key_awareness() {
if ($this->supportskeyawareness === null) {
- $this->supportskeyawareness = ($this->store instanceof cache_is_key_aware);
+ $this->supportskeyawareness = ($this->store instanceof key_aware_cache_interface);
}
return $this->supportskeyawareness;
}
@@ -1305,7 +1303,7 @@ class cache implements cache_loader {
*/
protected function store_supports_native_locking() {
if ($this->nativelocking === null) {
- $this->nativelocking = ($this->store instanceof cache_is_lockable);
+ $this->nativelocking = ($this->store instanceof lockable_cache_interface);
}
return $this->nativelocking;
}
@@ -1373,7 +1371,7 @@ class cache implements cache_loader {
} else {
$data = $this->staticaccelerationarray[$key]['data'];
- if ($data instanceof cache_cached_object) {
+ if ($data instanceof cached_object) {
$result = $data->restore_object();
} else if ($this->staticaccelerationarray[$key]['serialized']) {
$result = unserialize($data);
@@ -1381,9 +1379,9 @@ class cache implements cache_loader {
$result = $data;
}
}
- if (cache_helper::result_found($result)) {
+ if (helper::result_found($result)) {
if ($this->perfdebug) {
- cache_helper::record_cache_hit(cache_store::STATIC_ACCEL, $this->definition);
+ helper::record_cache_hit(store::STATIC_ACCEL, $this->definition);
}
if ($this->staticaccelerationsize > 1 && $this->staticaccelerationcount > 1) {
// Check to see if this is the last item on the static acceleration keys array.
@@ -1397,7 +1395,7 @@ class cache implements cache_loader {
return $result;
} else {
if ($this->perfdebug) {
- cache_helper::record_cache_miss(cache_store::STATIC_ACCEL, $this->definition);
+ helper::record_cache_miss(store::STATIC_ACCEL, $this->definition);
}
return false;
}
@@ -1429,8 +1427,10 @@ class cache implements cache_loader {
// 1. A known scalar safe value.
// 2. A definition that says it's simpledata. We trust it that it doesn't contain dangerous references.
// 3. An object that handles dereferencing by itself.
- if (is_scalar($data) || $this->definition->uses_simple_data()
- || $data instanceof cache_cached_object) {
+ if (
+ is_scalar($data) || $this->definition->uses_simple_data()
+ || $data instanceof cached_object
+ ) {
$this->staticaccelerationarray[$key]['data'] = $data;
$this->staticaccelerationarray[$key]['serialized'] = false;
} else {
@@ -1477,9 +1477,9 @@ class cache implements cache_loader {
* Purge the static acceleration cache.
*/
protected function static_acceleration_purge() {
- $this->staticaccelerationarray = array();
+ $this->staticaccelerationarray = [];
if ($this->staticaccelerationsize !== false) {
- $this->staticaccelerationkeys = array();
+ $this->staticaccelerationkeys = [];
$this->staticaccelerationcount = 0;
}
}
@@ -1542,10 +1542,10 @@ class cache implements cache_loader {
}
// The token for when the cache was last invalidated.
- list($atime) = explode('-', "{$tokena}-", 2);
+ [$atime] = explode('-', "{$tokena}-", 2);
// The token for this cache.
- list($btime) = explode('-', "{$tokenb}-", 2);
+ [$btime] = explode('-', "{$tokenb}-", 2);
if ($atime >= $btime) {
// Token A is newer.
@@ -1564,898 +1564,7 @@ class cache implements cache_loader {
}
}
-/**
- * An application cache.
- *
- * This class is used for application caches returned by the cache::make methods.
- * On top of the standard functionality it also allows locking to be required and or manually operated.
- *
- * This cache class should never be interacted with directly. Instead you should always use the cache::make methods.
- * It is technically possible to call those methods through this class however there is no guarantee that you will get an
- * instance of this class back again.
- *
- * @internal don't use me directly.
- *
- * @package core
- * @category cache
- * @copyright 2012 Sam Hemelryk
- * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
- */
-class cache_application extends cache implements cache_loader_with_locking {
-
- /**
- * Lock identifier.
- * This is used to ensure the lock belongs to the cache instance + definition + user.
- * @var string
- */
- protected $lockidentifier;
-
- /**
- * Gets set to true if the cache's primary store natively supports locking.
- * If it does then we use that, otherwise we need to instantiate a second store to use for locking.
- * @var cache_store
- */
- protected $nativelocking = null;
-
- /**
- * Gets set to true if the cache is going to be using locking.
- * This isn't a requirement, it doesn't need to use locking (most won't) and this bool is used to quickly check things.
- * If required then locking will be forced for the get|set|delete operation.
- * @var bool
- */
- protected $requirelocking = false;
-
- /**
- * Gets set to true if the cache writes (set|delete) must have a manual lock created first
- * @var bool
- */
- protected $requirelockingbeforewrite = false;
-
- /**
- * Gets set to a cache_store to use for locking if the caches primary store doesn't support locking natively.
- * @var cache_lock_interface
- */
- protected $cachelockinstance;
-
- /**
- * Store a list of locks acquired by this process.
- * @var array
- */
- protected $locks;
-
- /**
- * Overrides the cache construct method.
- *
- * You should not call this method from your code, instead you should use the cache::make methods.
- *
- * @param cache_definition $definition
- * @param cache_store $store
- * @param cache_loader|cache_data_source $loader
- */
- public function __construct(cache_definition $definition, cache_store $store, $loader = null) {
- parent::__construct($definition, $store, $loader);
- $this->nativelocking = $this->store_supports_native_locking();
- if ($definition->require_locking()) {
- $this->requirelocking = true;
- $this->requirelockingbeforewrite = $definition->require_locking_before_write();
- }
-
- $this->handle_invalidation_events();
- }
-
- /**
- * Returns the identifier to use
- *
- * @staticvar int $instances Counts the number of instances. Used as part of the lock identifier.
- * @return string
- */
- public function get_identifier() {
- static $instances = 0;
- if ($this->lockidentifier === null) {
- $this->lockidentifier = md5(
- $this->get_definition()->generate_definition_hash() .
- sesskey() .
- $instances++ .
- 'cache_application'
- );
- }
- return $this->lockidentifier;
- }
-
- /**
- * Fixes the instance up after a clone.
- */
- public function __clone() {
- // Force a new idenfitier.
- $this->lockidentifier = null;
- }
-
- /**
- * Acquires a lock on the given key.
- *
- * This is done automatically if the definition requires it.
- * It is recommended to use a definition if you want to have locking although it is possible to do locking without having
- * it required by the definition.
- * The problem with such an approach is that you cannot ensure that code will consistently use locking. You will need to
- * rely on the integrators review skills.
- *
- * @param string|int $key The key as given to get|set|delete
- * @return bool Always returns true
- * @throws moodle_exception If the lock cannot be obtained
- */
- public function acquire_lock($key) {
- $releaseparent = false;
- try {
- if ($this->get_loader() !== false) {
- $this->get_loader()->acquire_lock($key);
- // We need to release this lock later if the lock is not successful.
- $releaseparent = true;
- }
- $hashedkey = cache_helper::hash_key($key, $this->get_definition());
- $before = microtime(true);
- if ($this->nativelocking) {
- $lock = $this->get_store()->acquire_lock($hashedkey, $this->get_identifier());
- } else {
- $this->ensure_cachelock_available();
- $lock = $this->cachelockinstance->lock($hashedkey, $this->get_identifier());
- }
- $after = microtime(true);
- if ($lock) {
- $this->locks[$hashedkey] = $lock;
- if (MDL_PERF || $this->perfdebug) {
- \core\lock\timing_wrapper_lock_factory::record_lock_data($after, $before,
- $this->get_definition()->get_id(), $hashedkey, $lock, $this->get_identifier() . $hashedkey);
- }
- $releaseparent = false;
- return true;
- } else {
- throw new moodle_exception('ex_unabletolock', 'cache', '', null,
- 'store: ' . get_class($this->get_store()) . ', lock: ' . $hashedkey);
- }
- } finally {
- // Release the parent lock if we acquired it, then threw an exception.
- if ($releaseparent) {
- $this->get_loader()->release_lock($key);
- }
- }
- }
-
- /**
- * Checks if this cache has a lock on the given key.
- *
- * @param string|int $key The key as given to get|set|delete
- * @return bool|null Returns true if there is a lock and this cache has it, null if no one has a lock on that key, false if
- * someone else has the lock.
- */
- public function check_lock_state($key) {
- $key = cache_helper::hash_key($key, $this->get_definition());
- if (!empty($this->locks[$key])) {
- return true; // Shortcut to save having to make a call to the cache store if the lock is held by this process.
- }
- if ($this->nativelocking) {
- return $this->get_store()->check_lock_state($key, $this->get_identifier());
- } else {
- $this->ensure_cachelock_available();
- return $this->cachelockinstance->check_state($key, $this->get_identifier());
- }
- }
-
- /**
- * Releases the lock this cache has on the given key
- *
- * @param string|int $key
- * @return bool True if the operation succeeded, false otherwise.
- */
- public function release_lock($key) {
- $loaderkey = $key;
- $key = cache_helper::hash_key($key, $this->get_definition());
- if ($this->nativelocking) {
- $released = $this->get_store()->release_lock($key, $this->get_identifier());
- } else {
- $this->ensure_cachelock_available();
- $released = $this->cachelockinstance->unlock($key, $this->get_identifier());
- }
- if ($released && array_key_exists($key, $this->locks)) {
- unset($this->locks[$key]);
- if (MDL_PERF || $this->perfdebug) {
- \core\lock\timing_wrapper_lock_factory::record_lock_released_data($this->get_identifier() . $key);
- }
- }
- if ($this->get_loader() !== false) {
- $this->get_loader()->release_lock($loaderkey);
- }
- return $released;
- }
-
- /**
- * Ensure that the dedicated lock store is ready to go.
- *
- * This should only happen if the cache store doesn't natively support it.
- */
- protected function ensure_cachelock_available() {
- if ($this->cachelockinstance === null) {
- $this->cachelockinstance = cache_helper::get_cachelock_for_store($this->get_store());
- }
- }
-
- /**
- * Sends a key => value pair to the cache.
- *
- *
- * // This code will add four entries to the cache, one for each url.
- * $cache->set('main', 'http://moodle.org');
- * $cache->set('docs', 'http://docs.moodle.org');
- * $cache->set('tracker', 'http://tracker.moodle.org');
- * $cache->set('qa', 'http://qa.moodle.net');
- *
- *
- * @param string|int $key The key for the data being requested.
- * @param int $version Version number
- * @param mixed $data The data to set against the key.
- * @param bool $setparents If true, sets all parent loaders, otherwise only this one
- * @return bool True on success, false otherwise.
- * @throws coding_exception If a required lock has not beeen acquired
- */
- protected function set_implementation($key, int $version, $data, bool $setparents = true): bool {
- if ($this->requirelockingbeforewrite && !$this->check_lock_state($key)) {
- throw new coding_exception('Attempted to set cache key "' . $key . '" without a lock. '
- . 'Locking before writes is required for ' . $this->get_definition()->get_id());
- }
- return parent::set_implementation($key, $version, $data, $setparents);
- }
-
- /**
- * Sends several key => value pairs to the cache.
- *
- * Using this function comes with potential performance implications.
- * Not all cache stores will support get_many/set_many operations and in order to replicate this functionality will call
- * the equivalent singular method for each item provided.
- * This should not deter you from using this function as there is a performance benefit in situations where the cache store
- * does support it, but you should be aware of this fact.
- *
- *
- * // This code will add four entries to the cache, one for each url.
- * $cache->set_many(array(
- * 'main' => 'http://moodle.org',
- * 'docs' => 'http://docs.moodle.org',
- * 'tracker' => 'http://tracker.moodle.org',
- * 'qa' => ''http://qa.moodle.net'
- * ));
- *
- *
- * @param array $keyvaluearray An array of key => value pairs to send to the cache.
- * @return int The number of items successfully set. It is up to the developer to check this matches the number of items.
- * ... if they care that is.
- * @throws coding_exception If a required lock has not beeen acquired
- */
- public function set_many(array $keyvaluearray) {
- if ($this->requirelockingbeforewrite) {
- foreach ($keyvaluearray as $key => $value) {
- if (!$this->check_lock_state($key)) {
- throw new coding_exception('Attempted to set cache key "' . $key . '" without a lock. '
- . 'Locking before writes is required for ' . $this->get_definition()->get_id());
- }
- }
- }
- return parent::set_many($keyvaluearray);
- }
-
- /**
- * Delete the given key from the cache.
- *
- * @param string|int $key The key to delete.
- * @param bool $recurse When set to true the key will also be deleted from all stacked cache loaders and their stores.
- * This happens by default and ensure that all the caches are consistent. It is NOT recommended to change this.
- * @return bool True of success, false otherwise.
- * @throws coding_exception If a required lock has not beeen acquired
- */
- public function delete($key, $recurse = true) {
- if ($this->requirelockingbeforewrite && !$this->check_lock_state($key)) {
- throw new coding_exception('Attempted to delete cache key "' . $key . '" without a lock. '
- . 'Locking before writes is required for ' . $this->get_definition()->get_id());
- }
- return parent::delete($key, $recurse);
- }
-
- /**
- * Delete all of the given keys from the cache.
- *
- * @param array $keys The key to delete.
- * @param bool $recurse When set to true the key will also be deleted from all stacked cache loaders and their stores.
- * This happens by default and ensure that all the caches are consistent. It is NOT recommended to change this.
- * @return int The number of items successfully deleted.
- * @throws coding_exception If a required lock has not beeen acquired
- */
- public function delete_many(array $keys, $recurse = true) {
- if ($this->requirelockingbeforewrite) {
- foreach ($keys as $key) {
- if (!$this->check_lock_state($key)) {
- throw new coding_exception('Attempted to delete cache key "' . $key . '" without a lock. '
- . 'Locking before writes is required for ' . $this->get_definition()->get_id());
- }
- }
- }
- return parent::delete_many($keys, $recurse);
- }
-}
-
-/**
- * A session cache.
- *
- * This class is used for session caches returned by the cache::make methods.
- *
- * It differs from the application loader in a couple of noteable ways:
- * 1. Sessions are always expected to exist.
- * Because of this we don't ever use the static acceleration array.
- * 2. Session data for a loader instance (store + definition) is consolidate into a
- * single array for storage within the store.
- * Along with this we embed a lastaccessed time with the data. This way we can
- * check sessions for a last access time.
- * 3. Session stores are required to support key searching and must
- * implement cache_is_searchable. This ensures stores used for the cache can be
- * targetted for garbage collection of session data.
- *
- * This cache class should never be interacted with directly. Instead you should always use the cache::make methods.
- * It is technically possible to call those methods through this class however there is no guarantee that you will get an
- * instance of this class back again.
- *
- * @todo we should support locking in the session as well. Should be pretty simple to set up.
- *
- * @internal don't use me directly.
- * @method cache_store|cache_is_searchable get_store() Returns the cache store which must implement both cache_is_searchable.
- *
- * @package core
- * @category cache
- * @copyright 2012 Sam Hemelryk
- * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
- */
-class cache_session extends cache {
- /**
- * The user the session has been established for.
- * @var int
- */
- protected static $loadeduserid = null;
-
- /**
- * The userid this cache is currently using.
- * @var int
- */
- protected $currentuserid = null;
-
- /**
- * The session id we are currently using.
- * @var array
- */
- protected $sessionid = null;
-
- /**
- * The session data for the above session id.
- * @var array
- */
- protected $session = null;
-
- /**
- * Constant used to prefix keys.
- */
- const KEY_PREFIX = 'sess_';
-
- /**
- * This is the key used to track last access.
- */
- const LASTACCESS = '__lastaccess__';
-
- /**
- * Override the cache::construct method.
- *
- * This function gets overriden so that we can process any invalidation events if need be.
- * If the definition doesn't have any invalidation events then this occurs exactly as it would for the cache class.
- * Otherwise we look at the last invalidation time and then check the invalidation data for events that have occured
- * between then now.
- *
- * You should not call this method from your code, instead you should use the cache::make methods.
- *
- * @param cache_definition $definition
- * @param cache_store $store
- * @param cache_loader|cache_data_source $loader
- */
- public function __construct(cache_definition $definition, cache_store $store, $loader = null) {
- // First up copy the loadeduserid to the current user id.
- $this->currentuserid = self::$loadeduserid;
- $this->set_session_id();
- parent::__construct($definition, $store, $loader);
-
- // This will trigger check tracked user. If this gets removed a call to that will need to be added here in its place.
- $this->set(self::LASTACCESS, cache::now());
-
- $this->handle_invalidation_events();
- }
-
- /**
- * Sets the session id for the loader.
- */
- protected function set_session_id() {
- $this->sessionid = preg_replace('#[^a-zA-Z0-9_]#', '_', session_id());
- }
-
- /**
- * Returns the prefix used for all keys.
- * @return string
- */
- protected function get_key_prefix() {
- return 'u'.$this->currentuserid.'_'.$this->sessionid;
- }
-
- /**
- * Parses the key turning it into a string (or array is required) suitable to be passed to the cache store.
- *
- * This function is called for every operation that uses keys. For this reason we use this function to also check
- * that the current user is the same as the user who last used this cache.
- *
- * On top of that if prepends the string 'sess_' to the start of all keys. The _ ensures things are easily identifiable.
- *
- * @param string|int $key As passed to get|set|delete etc.
- * @return string|array String unless the store supports multi-identifiers in which case an array if returned.
- */
- protected function parse_key($key) {
- $prefix = $this->get_key_prefix();
- if ($key === self::LASTACCESS) {
- return $key.$prefix;
- }
- return $prefix.'_'.parent::parse_key($key);
- }
-
- /**
- * Check that this cache instance is tracking the current user.
- */
- protected function check_tracked_user() {
- if (isset($_SESSION['USER']->id) && $_SESSION['USER']->id !== null) {
- // Get the id of the current user.
- $new = $_SESSION['USER']->id;
- } else {
- // No user set up yet.
- $new = 0;
- }
- if ($new !== self::$loadeduserid) {
- // The current user doesn't match the tracked userid for this request.
- if (!is_null(self::$loadeduserid)) {
- // Purge the data we have for the old user.
- // This way we don't bloat the session.
- $this->purge();
- }
- self::$loadeduserid = $new;
- $this->currentuserid = $new;
- } else if ($new !== $this->currentuserid) {
- // The current user matches the loaded user but not the user last used by this cache.
- $this->purge_current_user();
- $this->currentuserid = $new;
- }
- }
-
- /**
- * Purges the session cache of all data belonging to the current user.
- */
- public function purge_current_user() {
- $keys = $this->get_store()->find_by_prefix($this->get_key_prefix());
- $this->get_store()->delete_many($keys);
- }
-
- /**
- * Retrieves the value for the given key from the cache.
- *
- * @param string|int $key The key for the data being requested.
- * It can be any structure although using a scalar string or int is recommended in the interests of performance.
- * In advanced cases an array may be useful such as in situations requiring the multi-key functionality.
- * @param int $requiredversion Minimum required version of the data or cache::VERSION_NONE
- * @param int $strictness One of IGNORE_MISSING | MUST_EXIST
- * @param mixed &$actualversion If specified, will be set to the actual version number retrieved
- * @return mixed|false The data from the cache or false if the key did not exist within the cache.
- * @throws coding_exception
- */
- protected function get_implementation($key, int $requiredversion, int $strictness, &$actualversion = null) {
- // Check the tracked user.
- $this->check_tracked_user();
-
- // Use parent code.
- return parent::get_implementation($key, $requiredversion, $strictness, $actualversion);
- }
-
- /**
- * Sends a key => value pair to the cache.
- *
- *
- * // This code will add four entries to the cache, one for each url.
- * $cache->set('main', 'http://moodle.org');
- * $cache->set('docs', 'http://docs.moodle.org');
- * $cache->set('tracker', 'http://tracker.moodle.org');
- * $cache->set('qa', 'http://qa.moodle.net');
- *
- *
- * @param string|int $key The key for the data being requested.
- * It can be any structure although using a scalar string or int is recommended in the interests of performance.
- * In advanced cases an array may be useful such as in situations requiring the multi-key functionality.
- * @param mixed $data The data to set against the key.
- * @return bool True on success, false otherwise.
- */
- public function set($key, $data) {
- $this->check_tracked_user();
- $loader = $this->get_loader();
- if ($loader !== false) {
- // We have a loader available set it there as well.
- // We have to let the loader do its own parsing of data as it may be unique.
- $loader->set($key, $data);
- }
- if (is_object($data) && $data instanceof cacheable_object) {
- $data = new cache_cached_object($data);
- } else if (!$this->get_store()->supports_dereferencing_objects() && !is_scalar($data)) {
- // If data is an object it will be a reference.
- // If data is an array if may contain references.
- // We want to break references so that the cache cannot be modified outside of itself.
- // Call the function to unreference it (in the best way possible).
- $data = $this->unref($data);
- }
- // We dont' support native TTL here as we consolidate data for sessions.
- if ($this->has_a_ttl() && !$this->store_supports_native_ttl()) {
- $data = new cache_ttl_wrapper($data, $this->get_definition()->get_ttl());
- }
- $success = $this->get_store()->set($this->parse_key($key), $data);
- if ($this->perfdebug) {
- cache_helper::record_cache_set($this->get_store(), $this->get_definition(), 1,
- $this->get_store()->get_last_io_bytes());
- }
- return $success;
- }
-
- /**
- * Delete the given key from the cache.
- *
- * @param string|int $key The key to delete.
- * @param bool $recurse When set to true the key will also be deleted from all stacked cache loaders and their stores.
- * This happens by default and ensure that all the caches are consistent. It is NOT recommended to change this.
- * @return bool True of success, false otherwise.
- */
- public function delete($key, $recurse = true) {
- $parsedkey = $this->parse_key($key);
- if ($recurse && $this->get_loader() !== false) {
- // Delete from the bottom of the stack first.
- $this->get_loader()->delete($key, $recurse);
- }
- return $this->get_store()->delete($parsedkey);
- }
-
- /**
- * Retrieves an array of values for an array of keys.
- *
- * Using this function comes with potential performance implications.
- * Not all cache stores will support get_many/set_many operations and in order to replicate this functionality will call
- * the equivalent singular method for each item provided.
- * This should not deter you from using this function as there is a performance benefit in situations where the cache store
- * does support it, but you should be aware of this fact.
- *
- * @param array $keys The keys of the data being requested.
- * Each key can be any structure although using a scalar string or int is recommended in the interests of performance.
- * In advanced cases an array may be useful such as in situations requiring the multi-key functionality.
- * @param int $strictness One of IGNORE_MISSING or MUST_EXIST.
- * @return array An array of key value pairs for the items that could be retrieved from the cache.
- * If MUST_EXIST was used and not all keys existed within the cache then an exception will be thrown.
- * Otherwise any key that did not exist will have a data value of false within the results.
- * @throws coding_exception
- */
- public function get_many(array $keys, $strictness = IGNORE_MISSING) {
- $this->check_tracked_user();
- $parsedkeys = array();
- $keymap = array();
- foreach ($keys as $key) {
- $parsedkey = $this->parse_key($key);
- $parsedkeys[$key] = $parsedkey;
- $keymap[$parsedkey] = $key;
- }
- $result = $this->get_store()->get_many($parsedkeys);
- if ($this->perfdebug) {
- $readbytes = $this->get_store()->get_last_io_bytes();
- }
- $return = array();
- $missingkeys = array();
- $hasmissingkeys = false;
- foreach ($result as $parsedkey => $value) {
- $key = $keymap[$parsedkey];
- if ($value instanceof cache_ttl_wrapper) {
- /* @var cache_ttl_wrapper $value */
- if ($value->has_expired()) {
- $this->delete($keymap[$parsedkey]);
- $value = false;
- } else {
- $value = $value->data;
- }
- }
- if ($value instanceof cache_cached_object) {
- /* @var cache_cached_object $value */
- $value = $value->restore_object();
- } else if (!$this->get_store()->supports_dereferencing_objects() && !is_scalar($value)) {
- // If data is an object it will be a reference.
- // If data is an array if may contain references.
- // We want to break references so that the cache cannot be modified outside of itself.
- // Call the function to unreference it (in the best way possible).
- $value = $this->unref($value);
- }
- $return[$key] = $value;
- if ($value === false) {
- $hasmissingkeys = true;
- $missingkeys[$parsedkey] = $key;
- }
- }
- if ($hasmissingkeys) {
- // We've got missing keys - we've got to check any loaders or data sources.
- $loader = $this->get_loader();
- $datasource = $this->get_datasource();
- if ($loader !== false) {
- foreach ($loader->get_many($missingkeys) as $key => $value) {
- if ($value !== false) {
- $return[$key] = $value;
- unset($missingkeys[$parsedkeys[$key]]);
- }
- }
- }
- $hasmissingkeys = count($missingkeys) > 0;
- if ($datasource !== false && $hasmissingkeys) {
- // We're still missing keys but we've got a datasource.
- foreach ($datasource->load_many_for_cache($missingkeys) as $key => $value) {
- if ($value !== false) {
- $return[$key] = $value;
- unset($missingkeys[$parsedkeys[$key]]);
- }
- }
- $hasmissingkeys = count($missingkeys) > 0;
- }
- }
- if ($hasmissingkeys && $strictness === MUST_EXIST) {
- throw new coding_exception('Requested key did not exist in any cache stores and could not be loaded.');
- }
- if ($this->perfdebug) {
- $hits = 0;
- $misses = 0;
- foreach ($return as $value) {
- if ($value === false) {
- $misses++;
- } else {
- $hits++;
- }
- }
- cache_helper::record_cache_hit($this->get_store(), $this->get_definition(), $hits, $readbytes);
- cache_helper::record_cache_miss($this->get_store(), $this->get_definition(), $misses);
- }
- return $return;
-
- }
-
- /**
- * Delete all of the given keys from the cache.
- *
- * @param array $keys The key to delete.
- * @param bool $recurse When set to true the key will also be deleted from all stacked cache loaders and their stores.
- * This happens by default and ensure that all the caches are consistent. It is NOT recommended to change this.
- * @return int The number of items successfully deleted.
- */
- public function delete_many(array $keys, $recurse = true) {
- $parsedkeys = array_map(array($this, 'parse_key'), $keys);
- if ($recurse && $this->get_loader() !== false) {
- // Delete from the bottom of the stack first.
- $this->get_loader()->delete_many($keys, $recurse);
- }
- return $this->get_store()->delete_many($parsedkeys);
- }
-
- /**
- * Sends several key => value pairs to the cache.
- *
- * Using this function comes with potential performance implications.
- * Not all cache stores will support get_many/set_many operations and in order to replicate this functionality will call
- * the equivalent singular method for each item provided.
- * This should not deter you from using this function as there is a performance benefit in situations where the cache store
- * does support it, but you should be aware of this fact.
- *
- *
- * // This code will add four entries to the cache, one for each url.
- * $cache->set_many(array(
- * 'main' => 'http://moodle.org',
- * 'docs' => 'http://docs.moodle.org',
- * 'tracker' => 'http://tracker.moodle.org',
- * 'qa' => ''http://qa.moodle.net'
- * ));
- *
- *
- * @param array $keyvaluearray An array of key => value pairs to send to the cache.
- * @return int The number of items successfully set. It is up to the developer to check this matches the number of items.
- * ... if they care that is.
- */
- public function set_many(array $keyvaluearray) {
- $this->check_tracked_user();
- $loader = $this->get_loader();
- if ($loader !== false) {
- // We have a loader available set it there as well.
- // We have to let the loader do its own parsing of data as it may be unique.
- $loader->set_many($keyvaluearray);
- }
- $data = array();
- $definitionid = $this->get_definition()->get_ttl();
- $simulatettl = $this->has_a_ttl() && !$this->store_supports_native_ttl();
- foreach ($keyvaluearray as $key => $value) {
- if (is_object($value) && $value instanceof cacheable_object) {
- $value = new cache_cached_object($value);
- } else if (!$this->get_store()->supports_dereferencing_objects() && !is_scalar($value)) {
- // If data is an object it will be a reference.
- // If data is an array if may contain references.
- // We want to break references so that the cache cannot be modified outside of itself.
- // Call the function to unreference it (in the best way possible).
- $value = $this->unref($value);
- }
- if ($simulatettl) {
- $value = new cache_ttl_wrapper($value, $definitionid);
- }
- $data[$key] = array(
- 'key' => $this->parse_key($key),
- 'value' => $value
- );
- }
- $successfullyset = $this->get_store()->set_many($data);
- if ($this->perfdebug && $successfullyset) {
- cache_helper::record_cache_set($this->get_store(), $this->get_definition(), $successfullyset,
- $this->get_store()->get_last_io_bytes());
- }
- return $successfullyset;
- }
-
- /**
- * Purges the cache store, and loader if there is one.
- *
- * @return bool True on success, false otherwise
- */
- public function purge() {
- $this->get_store()->purge();
- if ($this->get_loader()) {
- $this->get_loader()->purge();
- }
- return true;
- }
-
- /**
- * Test is a cache has a key.
- *
- * The use of the has methods is strongly discouraged. In a high load environment the cache may well change between the
- * test and any subsequent action (get, set, delete etc).
- * Instead it is recommended to write your code in such a way they it performs the following steps:
- *
- * - Attempt to retrieve the information.
- * - Generate the information.
- * - Attempt to set the information
- *
- *
- * Its also worth mentioning that not all stores support key tests.
- * For stores that don't support key tests this functionality is mimicked by using the equivalent get method.
- * Just one more reason you should not use these methods unless you have a very good reason to do so.
- *
- * @param string|int $key
- * @param bool $tryloadifpossible If set to true, the cache doesn't contain the key, and there is another cache loader or
- * data source then the code will try load the key value from the next item in the chain.
- * @return bool True if the cache has the requested key, false otherwise.
- */
- public function has($key, $tryloadifpossible = false) {
- $this->check_tracked_user();
- $parsedkey = $this->parse_key($key);
- $store = $this->get_store();
- if ($this->has_a_ttl() && !$this->store_supports_native_ttl()) {
- // The data has a TTL and the store doesn't support it natively.
- // We must fetch the data and expect a ttl wrapper.
- $data = $store->get($parsedkey);
- $has = ($data instanceof cache_ttl_wrapper && !$data->has_expired());
- } else if (!$this->store_supports_key_awareness()) {
- // The store doesn't support key awareness, get the data and check it manually... puke.
- // Either no TTL is set of the store supports its handling natively.
- $data = $store->get($parsedkey);
- $has = ($data !== false);
- } else {
- // The store supports key awareness, this is easy!
- // Either no TTL is set of the store supports its handling natively.
- /* @var cache_store|cache_is_key_aware $store */
- $has = $store->has($parsedkey);
- }
- if (!$has && $tryloadifpossible) {
- $result = null;
- if ($this->get_loader() !== false) {
- $result = $this->get_loader()->get($parsedkey);
- } else if ($this->get_datasource() !== null) {
- $result = $this->get_datasource()->load_for_cache($key);
- }
- $has = ($result !== null);
- if ($has) {
- $this->set($key, $result);
- }
- }
- return $has;
- }
-
- /**
- * Test is a cache has all of the given keys.
- *
- * It is strongly recommended to avoid the use of this function if not absolutely required.
- * In a high load environment the cache may well change between the test and any subsequent action (get, set, delete etc).
- *
- * Its also worth mentioning that not all stores support key tests.
- * For stores that don't support key tests this functionality is mimicked by using the equivalent get method.
- * Just one more reason you should not use these methods unless you have a very good reason to do so.
- *
- * @param array $keys
- * @return bool True if the cache has all of the given keys, false otherwise.
- */
- public function has_all(array $keys) {
- $this->check_tracked_user();
- if (($this->has_a_ttl() && !$this->store_supports_native_ttl()) || !$this->store_supports_key_awareness()) {
- foreach ($keys as $key) {
- if (!$this->has($key)) {
- return false;
- }
- }
- return true;
- }
- // The cache must be key aware and if support native ttl if it a ttl is set.
- /* @var cache_store|cache_is_key_aware $store */
- $store = $this->get_store();
- return $store->has_all(array_map(array($this, 'parse_key'), $keys));
- }
-
- /**
- * Test if a cache has at least one of the given keys.
- *
- * It is strongly recommended to avoid the use of this function if not absolutely required.
- * In a high load environment the cache may well change between the test and any subsequent action (get, set, delete etc).
- *
- * Its also worth mentioning that not all stores support key tests.
- * For stores that don't support key tests this functionality is mimicked by using the equivalent get method.
- * Just one more reason you should not use these methods unless you have a very good reason to do so.
- *
- * @param array $keys
- * @return bool True if the cache has at least one of the given keys
- */
- public function has_any(array $keys) {
- if (($this->has_a_ttl() && !$this->store_supports_native_ttl()) || !$this->store_supports_key_awareness()) {
- foreach ($keys as $key) {
- if ($this->has($key)) {
- return true;
- }
- }
- return false;
- }
- /* @var cache_store|cache_is_key_aware $store */
- $store = $this->get_store();
- return $store->has_any(array_map(array($this, 'parse_key'), $keys));
- }
-
- /**
- * The session loader never uses static acceleration.
- * Instead it stores things in the static $session variable. Shared between all session loaders.
- *
- * @return bool
- */
- protected function use_static_acceleration() {
- return false;
- }
-}
-
-/**
- * An request cache.
- *
- * This class is used for request caches returned by the cache::make methods.
- *
- * This cache class should never be interacted with directly. Instead you should always use the cache::make methods.
- * It is technically possible to call those methods through this class however there is no guarantee that you will get an
- * instance of this class back again.
- *
- * @internal don't use me directly.
- *
- * @package core
- * @category cache
- * @copyright 2012 Sam Hemelryk
- * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
- */
-class cache_request extends cache {
- // This comment appeases code pre-checker ;) !
-}
+// Alias this class to the old name.
+// This file will be autoloaded by the legacyclasses autoload system.
+// In future all uses of this class will be corrected and the legacy references will be removed.
+class_alias(cache::class, \cache::class);
diff --git a/cache/classes/cache_lock_interface.php b/cache/classes/cache_lock_interface.php
new file mode 100644
index 00000000000..9c792cba431
--- /dev/null
+++ b/cache/classes/cache_lock_interface.php
@@ -0,0 +1,85 @@
+.
+
+namespace core_cache;
+
+/**
+ * Cache lock interface.
+ *
+ * This interface needs to be inherited by all cache lock plugins.
+ *
+ * @package core_cache
+ * @copyright Sam Hemelryk
+ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+interface cache_lock_interface {
+ /**
+ * Constructs an instance of the cache lock given its name and its configuration data
+ *
+ * @param string $name The unique name of the lock instance
+ * @param array $configuration
+ */
+ public function __construct($name, array $configuration = []);
+
+ /**
+ * Acquires a lock on a given key.
+ *
+ * @param string $key The key to acquire a lock for.
+ * @param string $ownerid An unique identifier for the owner of this lock. It is entirely optional for the cache lock plugin
+ * to use this. Each implementation can decide for themselves.
+ * @param bool $block If set to true the application will wait until a lock can be acquired
+ * @return bool True if the lock can be acquired false otherwise.
+ */
+ public function lock($key, $ownerid, $block = false);
+
+ /**
+ * Releases the lock held on a certain key.
+ *
+ * @param string $key The key to release the lock for.
+ * @param string $ownerid An unique identifier for the owner of this lock. It is entirely optional for the cache lock plugin
+ * to use this. Each implementation can decide for themselves.
+ * @param bool $forceunlock If set to true the lock will be removed if it exists regardless of whether or not we own it.
+ */
+ public function unlock($key, $ownerid, $forceunlock = false);
+
+ /**
+ * Checks the state of the given key.
+ *
+ * Returns true if the key is locked and belongs to the ownerid.
+ * Returns false if the key is locked but does not belong to the ownerid.
+ * Returns null if there is no lock
+ *
+ * @param string $key The key we are checking for.
+ * @param string $ownerid The identifier so we can check if we have the lock or if it is someone else.
+ * @return bool True if this code has the lock, false if there is a lock but this code doesn't have it, null if there
+ * is no lock.
+ */
+ public function check_state($key, $ownerid);
+
+ /**
+ * Cleans up any left over locks.
+ *
+ * This function MUST clean up any locks that have been acquired and not released during processing.
+ * Although the situation of acquiring a lock and not releasing it should be insanely rare we need to deal with it.
+ * Things such as unfortunate timeouts etc could cause this situation.
+ */
+ public function __destruct();
+}
+
+// Alias this class to the old name.
+// This file will be autoloaded by the legacyclasses autoload system.
+// In future all uses of this class will be corrected and the legacy references will be removed.
+class_alias(cache_lock_interface::class, \cache_lock_interface::class);
diff --git a/cache/classes/cacheable_object_array.php b/cache/classes/cacheable_object_array.php
new file mode 100644
index 00000000000..edba68815c9
--- /dev/null
+++ b/cache/classes/cacheable_object_array.php
@@ -0,0 +1,102 @@
+.
+
+namespace core_cache;
+
+use core\exception\coding_exception;
+use ArrayObject;
+
+/**
+ * An array of cacheable objects.
+ *
+ * This class allows a developer to create an array of cacheable objects and store that.
+ * The cache API doesn't check items within an array to see whether they are cacheable. Such a check would be very costly to both
+ * arrays using cacheable object and those that don't.
+ * Instead the developer must explicitly use a cacheable_object_array instance.
+ *
+ * The following is one example of how this class can be used.
+ *
+ * $data = array();
+ * $data[] = new cacheable_object('one');
+ * $data[] = new cacheable_object('two');
+ * $data[] = new cacheable_object('three');
+ * $cache->set(new cacheable_object_array($data));
+ *
+ * Another example would be
+ *
+ * $data = new cacheable_object_array();
+ * $data[] = new cacheable_object('one');
+ * $data[] = new cacheable_object('two');
+ * $data[] = new cacheable_object('three');
+ * $cache->set($data);
+ *
+ *
+ * @copyright 2012 Sam Hemelryk
+ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ * @package core_cache
+ */
+class cacheable_object_array extends ArrayObject implements cacheable_object_interface {
+ /**
+ * Constructs a new array object instance.
+ * @param array $items
+ */
+ final public function __construct(array $items = []) {
+ parent::__construct($items, ArrayObject::STD_PROP_LIST);
+ }
+
+ /**
+ * Returns the data to cache for this object.
+ *
+ * @return cached_object[] An array of cached_object instances.
+ * @throws coding_exception
+ */
+ final public function prepare_to_cache() {
+ $result = [];
+ foreach ($this as $key => $value) {
+ if ($value instanceof cacheable_object_interface) {
+ $value = new cached_object($value);
+ } else {
+ throw new coding_exception('Only cacheable_object instances can be added to a cacheable_array');
+ }
+ $result[$key] = $value;
+ }
+ return $result;
+ }
+
+ /**
+ * Returns the cacheable_object_array that was originally sent to the cache.
+ *
+ * @param array $data
+ * @return self
+ * @throws coding_exception
+ */
+ final public static function wake_from_cache($data) {
+ if (!is_array($data)) {
+ throw new coding_exception('Invalid data type when reviving cacheable_array data');
+ }
+ $result = [];
+ foreach ($data as $key => $value) {
+ $result[$key] = $value->restore_object();
+ }
+ $class = __CLASS__;
+ return new $class($result);
+ }
+}
+
+// Alias this class to the old name.
+// This file will be autoloaded by the legacyclasses autoload system.
+// In future all uses of this class will be corrected and the legacy references will be removed.
+class_alias(cacheable_object_array::class, \cacheable_object_array::class);
diff --git a/cache/classes/cacheable_object_interface.php b/cache/classes/cacheable_object_interface.php
new file mode 100644
index 00000000000..d77574660f0
--- /dev/null
+++ b/cache/classes/cacheable_object_interface.php
@@ -0,0 +1,53 @@
+.
+
+namespace core_cache;
+
+/**
+ * Cacheable object.
+ *
+ * This interface can be implemented by any class that is going to be passed into a cache and allows it to take control of the
+ * structure and the information about to be cached, as well as how to deal with it when it is retrieved from a cache.
+ * Think of it like serialisation and the __sleep and __wakeup methods.
+ * This is used because cache stores are responsible for how they interact with data and what they do when storing it. This
+ * interface ensures there is always a guaranteed action.
+ *
+ * @package core_cache
+ * @copyright Sam Hemelryk
+ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+interface cacheable_object_interface {
+ /**
+ * Prepares the object for caching. Works like the __sleep method.
+ *
+ * @return mixed The data to cache, can be anything except a class that implements the cacheable_object... that would
+ * be dumb.
+ */
+ public function prepare_to_cache();
+
+ /**
+ * Takes the data provided by prepare_to_cache and reinitialises an instance of the associated from it.
+ *
+ * @param mixed $data
+ * @return object The instance for the given data.
+ */
+ public static function wake_from_cache($data);
+}
+
+// Alias this class to the old name.
+// This file will be autoloaded by the legacyclasses autoload system.
+// In future all uses of this class will be corrected and the legacy references will be removed.
+class_alias(cacheable_object_interface::class, \cacheable_object::class);
diff --git a/cache/classes/cached_object.php b/cache/classes/cached_object.php
new file mode 100644
index 00000000000..6c5558f26cc
--- /dev/null
+++ b/cache/classes/cached_object.php
@@ -0,0 +1,64 @@
+.
+
+namespace core_cache;
+
+/**
+ * A cached object wrapper.
+ *
+ * This class gets used when the data is an object that has implemented the cacheable_object_interface interface.
+ *
+ * @package core_cache
+ * @category cache
+ * @copyright 2012 Sam Hemelryk
+ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+class cached_object {
+ /**
+ * The class of the cacheable object
+ * @var string
+ */
+ protected $class;
+
+ /**
+ * The data returned by the cacheable_object_interface prepare_to_cache method.
+ * @var mixed
+ */
+ protected $data;
+
+ /**
+ * Constructs a cached object wrapper.
+ * @param cacheable_object_interface $obj
+ */
+ public function __construct(cacheable_object_interface $obj) {
+ $this->class = get_class($obj);
+ $this->data = $obj->prepare_to_cache();
+ }
+
+ /**
+ * Restores the data as an instance of the cacheable_object_interface class.
+ * @return object
+ */
+ public function restore_object() {
+ $class = $this->class;
+ return $class::wake_from_cache($this->data);
+ }
+}
+
+// Alias this class to the old name.
+// This file will be autoloaded by the legacyclasses autoload system.
+// In future all uses of this class will be corrected and the legacy references will be removed.
+class_alias(cached_object::class, \cache_cached_object::class);
diff --git a/cache/classes/config.php b/cache/classes/config.php
index ad192cae74b..85e2a0341bb 100644
--- a/cache/classes/config.php
+++ b/cache/classes/config.php
@@ -14,19 +14,9 @@
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see .
-/**
- * Cache configuration reader
- *
- * This file is part of Moodle's cache API, affectionately called MUC.
- * It contains the components that are requried in order to use caching.
- *
- * @package core
- * @category cache
- * @copyright 2012 Sam Hemelryk
- * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
- */
+namespace core_cache;
-defined('MOODLE_INTERNAL') || die();
+use core_cache\exception\cache_exception;
/**
* Cache configuration reader.
@@ -34,42 +24,41 @@ defined('MOODLE_INTERNAL') || die();
* This class is used to interact with the cache's configuration.
* The configuration is stored in the Moodle data directory.
*
- * @package core
+ * @package core_cache
* @category cache
* @copyright 2012 Sam Hemelryk
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
-class cache_config {
-
+class config {
/**
* The configured stores
* @var array
*/
- protected $configstores = array();
+ protected $configstores = [];
/**
* The configured mode mappings
* @var array
*/
- protected $configmodemappings = array();
+ protected $configmodemappings = [];
/**
* The configured definitions as picked up from cache.php files
* @var array
*/
- protected $configdefinitions = array();
+ protected $configdefinitions = [];
/**
* The definition mappings that have been configured.
* @var array
*/
- protected $configdefinitionmappings = array();
+ protected $configdefinitionmappings = [];
/**
* An array of configured cache lock instances.
* @var array
*/
- protected $configlocks = array();
+ protected $configlocks = [];
/**
* The site identifier used when the cache config was last saved.
@@ -78,19 +67,19 @@ class cache_config {
protected $siteidentifier = null;
/**
- * Please use cache_config::instance to get an instance of the cache config that is ready to be used.
+ * Please use config::instance to get an instance of the cache config that is ready to be used.
*/
public function __construct() {
// Nothing to do here but look pretty.
}
/**
- * Gets an instance of the cache_configuration class.
+ * Gets an instance of the cache config class.
*
- * @return cache_config
+ * @return self
*/
public static function instance() {
- $factory = cache_factory::instance();
+ $factory = factory::instance();
return $factory->create_config_instance();
}
@@ -115,14 +104,14 @@ class cache_config {
$path = $CFG->altcacheconfigpath;
if (is_dir($path) && is_writable($path)) {
// Its a writable directory, thats fine.
- return $path.'/cacheconfig.php';
+ return $path . '/cacheconfig.php';
} else if (is_writable(dirname($path)) && (!file_exists($path) || is_writable($path))) {
// Its a file, either it doesn't exist and the directory is writable or the file exists and is writable.
return $path;
}
}
// Return the default location within dataroot.
- return $CFG->dataroot.'/muc/config.php';
+ return $CFG->dataroot . '/muc/config.php';
}
/**
@@ -138,11 +127,11 @@ class cache_config {
$configuration = $this->include_configuration();
}
- $this->configstores = array();
- $this->configdefinitions = array();
- $this->configlocks = array();
- $this->configmodemappings = array();
- $this->configdefinitionmappings = array();
+ $this->configstores = [];
+ $this->configdefinitions = [];
+ $this->configlocks = [];
+ $this->configmodemappings = [];
+ $this->configdefinitionmappings = [];
$siteidentifier = 'unknown';
if (array_key_exists('siteidentifier', $configuration)) {
@@ -174,7 +163,7 @@ class cache_config {
}
// Filter the stores.
- $availableplugins = cache_helper::early_get_cache_plugins();
+ $availableplugins = helper::early_get_cache_plugins();
foreach ($configuration['stores'] as $store) {
if (!is_array($store) || !array_key_exists('name', $store) || !array_key_exists('plugin', $store)) {
// Not a valid instance configuration.
@@ -182,25 +171,25 @@ class cache_config {
continue;
}
$plugin = $store['plugin'];
- $class = 'cachestore_'.$plugin;
+ $class = 'cachestore_' . $plugin;
$exists = array_key_exists($plugin, $availableplugins);
if (!$exists) {
// Not a valid plugin, or has been uninstalled, just skip it an carry on.
debugging('Invalid cache store in config. Not an available plugin.', DEBUG_DEVELOPER);
continue;
}
- $file = $CFG->dirroot.'/cache/stores/'.$plugin.'/lib.php';
+ $file = $CFG->dirroot . '/cache/stores/' . $plugin . '/lib.php';
if (!class_exists($class) && file_exists($file)) {
require_once($file);
}
if (!class_exists($class)) {
continue;
}
- if (!array_key_exists('cache_store', class_parents($class))) {
+ if (!array_key_exists(store::class, class_parents($class))) {
continue;
}
if (!array_key_exists('configuration', $store) || !is_array($store['configuration'])) {
- $store['configuration'] = array();
+ $store['configuration'] = [];
}
$store['class'] = $class;
$store['default'] = !empty($store['default']);
@@ -226,26 +215,26 @@ class cache_config {
continue;
}
$conf['mode'] = (int)$conf['mode'];
- if ($conf['mode'] < cache_store::MODE_APPLICATION || $conf['mode'] > cache_store::MODE_REQUEST) {
+ if ($conf['mode'] < store::MODE_APPLICATION || $conf['mode'] > store::MODE_REQUEST) {
// Invalid cache mode used for the definition.
continue;
}
- if ($conf['mode'] === cache_store::MODE_SESSION || $conf['mode'] === cache_store::MODE_REQUEST) {
+ if ($conf['mode'] === store::MODE_SESSION || $conf['mode'] === store::MODE_REQUEST) {
// We force this for session and request caches.
// They are only allowed to use the default as we don't want people changing them.
- $conf['sharingoptions'] = cache_definition::SHARING_DEFAULT;
- $conf['selectedsharingoption'] = cache_definition::SHARING_DEFAULT;
+ $conf['sharingoptions'] = definition::SHARING_DEFAULT;
+ $conf['selectedsharingoption'] = definition::SHARING_DEFAULT;
$conf['userinputsharingkey'] = '';
} else {
// Default the sharing option as it was added for 2.5.
// This can be removed sometime after 2.5 is the minimum version someone can upgrade from.
if (!isset($conf['sharingoptions'])) {
- $conf['sharingoptions'] = cache_definition::SHARING_DEFAULTOPTIONS;
+ $conf['sharingoptions'] = definition::SHARING_DEFAULTOPTIONS;
}
// Default the selected sharing option as it was added for 2.5.
// This can be removed sometime after 2.5 is the minimum version someone can upgrade from.
if (!isset($conf['selectedsharingoption'])) {
- $conf['selectedsharingoption'] = cache_definition::SHARING_DEFAULT;
+ $conf['selectedsharingoption'] = definition::SHARING_DEFAULT;
}
// Default the user input sharing key as it was added for 2.5.
// This can be removed sometime after 2.5 is the minimum version someone can upgrade from.
@@ -299,8 +288,8 @@ class cache_config {
$this->configdefinitionmappings[] = $mapping;
}
- usort($this->configmodemappings, array($this, 'sort_mappings'));
- usort($this->configdefinitionmappings, array($this, 'sort_mappings'));
+ usort($this->configmodemappings, [$this, 'sort_mappings']);
+ usort($this->configdefinitionmappings, [$this, 'sort_mappings']);
return true;
}
@@ -338,19 +327,19 @@ class cache_config {
throw new cache_exception('Invalid cache configuration file');
}
if (!array_key_exists('stores', $configuration) || !is_array($configuration['stores'])) {
- $configuration['stores'] = array();
+ $configuration['stores'] = [];
}
if (!array_key_exists('modemappings', $configuration) || !is_array($configuration['modemappings'])) {
- $configuration['modemappings'] = array();
+ $configuration['modemappings'] = [];
}
if (!array_key_exists('definitions', $configuration) || !is_array($configuration['definitions'])) {
- $configuration['definitions'] = array();
+ $configuration['definitions'] = [];
}
if (!array_key_exists('definitionmappings', $configuration) || !is_array($configuration['definitionmappings'])) {
- $configuration['definitionmappings'] = array();
+ $configuration['definitionmappings'] = [];
}
if (!array_key_exists('locks', $configuration) || !is_array($configuration['locks'])) {
- $configuration['locks'] = array();
+ $configuration['locks'] = [];
}
return $configuration;
@@ -401,13 +390,13 @@ class cache_config {
* @return array Associative array of definitions, id=>definition
*/
public function get_definitions_by_store($storename) {
- $definitions = array();
+ $definitions = [];
// This function was accidentally made static at some stage in the past.
// It was converted to an instance method but to be backwards compatible
// we must step around this in code.
if (!isset($this)) {
- $config = cache_config::instance();
+ $config = self::instance();
} else {
$config = $this;
}
@@ -420,18 +409,18 @@ class cache_config {
$defmappings = $config->get_definition_mappings();
// Create an associative array for the definition mappings.
- $thedefmappings = array();
+ $thedefmappings = [];
foreach ($defmappings as $defmapping) {
$thedefmappings[$defmapping['definition']] = $defmapping;
}
// Search for matches in default mappings.
$defs = $config->get_definitions();
- foreach($config->get_mode_mappings() as $modemapping) {
+ foreach ($config->get_mode_mappings() as $modemapping) {
if ($modemapping['store'] !== $storename) {
continue;
}
- foreach($defs as $id => $definition) {
+ foreach ($defs as $id => $definition) {
if ($definition['mode'] !== $modemapping['mode']) {
continue;
}
@@ -443,7 +432,7 @@ class cache_config {
}
}
- // Search for matches in the custom definitions mapping
+ // Search for matches in the custom definitions mapping.
foreach ($defmappings as $defmapping) {
if ($defmapping['store'] !== $storename) {
continue;
@@ -460,12 +449,12 @@ class cache_config {
/**
* Returns all of the stores that are suitable for the given mode and requirements.
*
- * @param int $mode One of cache_store::MODE_*
+ * @param int $mode One of store::MODE_*
* @param int $requirements The requirements of the cache as a binary flag
* @return array An array of suitable stores.
*/
public function get_stores($mode, $requirements = 0) {
- $stores = array();
+ $stores = [];
foreach ($this->configstores as $name => $store) {
// If the mode is supported and all of the requirements are provided features.
if (($store['modes'] & $mode) && ($store['features'] & $requirements) === $requirements) {
@@ -478,23 +467,23 @@ class cache_config {
/**
* Gets all of the stores that are to be used for the given definition.
*
- * @param cache_definition $definition
- * @return array
+ * @param definition $definition
+ * @return array
*/
- public function get_stores_for_definition(cache_definition $definition) {
+ public function get_stores_for_definition(definition $definition) {
// Check if MUC has been disabled.
- $factory = cache_factory::instance();
+ $factory = factory::instance();
if ($factory->stores_disabled()) {
// Yip its been disabled.
// To facilitate this we are going to always return an empty array of stores to use.
// This will force all cache instances to use the cachestore_dummy.
// MUC will still be used essentially so that code using it will still continue to function but because no cache stores
// are being used interaction with MUC will be purely based around a static var.
- return array();
+ return [];
}
$availablestores = $this->get_stores($definition->get_mode(), $definition->get_requirements_bin());
- $stores = array();
+ $stores = [];
$id = $definition->get_id();
// Now get any mappings and give them priority.
@@ -594,3 +583,8 @@ class cache_config {
throw new cache_exception('ex_nodefaultlock');
}
}
+
+// Alias this class to the old name.
+// This file will be autoloaded by the legacyclasses autoload system.
+// In future all uses of this class will be corrected and the legacy references will be removed.
+class_alias(config::class, \cache_config::class);
diff --git a/cache/locallib.php b/cache/classes/config_writer.php
similarity index 84%
rename from cache/locallib.php
rename to cache/classes/config_writer.php
index 572e2f8e55c..7d0154c132d 100644
--- a/cache/locallib.php
+++ b/cache/classes/config_writer.php
@@ -14,35 +14,29 @@
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see .
-/**
- * The supplementary cache API.
- *
- * This file is part of Moodle's cache API, affectionately called MUC.
- * It contains elements of the API that are not required in order to use caching.
- * Things in here are more in line with administration and management of the cache setup and configuration.
- *
- * @package core
- * @category cache
- * @copyright 2012 Sam Hemelryk
- * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
- */
+namespace core_cache;
-defined('MOODLE_INTERNAL') || die();
+use core\exception\coding_exception;
+use core_cache\exception\cache_exception;
+use cachestore_static;
+use cachestore_session;
+use cachestore_file;
+use core_component;
+use ReflectionClass;
/**
* Cache configuration writer.
*
- * This class should only be used when you need to write to the config, all read operations exist within the cache_config.
+ * This class should only be used when you need to write to the config, all read operations exist within the cache config.
*
- * @package core
+ * @package core_cache
* @category cache
* @copyright 2012 Sam Hemelryk
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
-class cache_config_writer extends cache_config {
-
+class config_writer extends config {
/**
- * Switch that gets set to true when ever a cache_config_writer instance is saving the cache configuration file.
+ * Switch that gets set to true when ever a config_writer instance is saving the cache configuration file.
* If this is set to true when save is next called we must avoid the trying to save and instead return the
* generated config so that is may be used instead of the file.
* @var bool
@@ -52,10 +46,10 @@ class cache_config_writer extends cache_config {
/**
* Returns an instance of the configuration writer.
*
- * @return cache_config_writer
+ * @return config_writer
*/
public static function instance() {
- $factory = cache_factory::instance();
+ $factory = factory::instance();
return $factory->create_config_instance(true);
}
@@ -85,7 +79,7 @@ class cache_config_writer extends cache_config {
$configuration = $this->generate_configuration_array();
// Prepare the file content.
- $content = " 'cachelock_file_default',
'type' => 'cachelock_file',
'dir' => 'filelocks',
- 'default' => true
- );
+ 'default' => true,
+ ];
}
- $factory = cache_factory::instance();
+ $factory = factory::instance();
$locking = $factory->create_lock_instance($lockconf);
if ($locking->lock('configwrite', 'config', true)) {
$tempcachefile = "{$cachefile}.tmp";
@@ -133,7 +127,7 @@ class cache_config_writer extends cache_config {
* @return array
*/
protected function generate_configuration_array() {
- $configuration = array();
+ $configuration = [];
$configuration['siteidentifier'] = $this->siteidentifier;
$configuration['stores'] = $this->configstores;
$configuration['modemappings'] = $this->configmodemappings;
@@ -155,11 +149,11 @@ class cache_config_writer extends cache_config {
* @return bool
* @throws cache_exception
*/
- public function add_store_instance($name, $plugin, array $configuration = array()) {
+ public function add_store_instance($name, $plugin, array $configuration = []) {
if (array_key_exists($name, $this->configstores)) {
throw new cache_exception('Duplicate name specificed for cache plugin instance. You must provide a unique name.');
}
- $class = 'cachestore_'.$plugin;
+ $class = 'cachestore_' . $plugin;
if (!class_exists($class)) {
$plugins = core_component::get_plugin_list_with_file('cachestore', 'lib.php');
if (!array_key_exists($plugin, $plugins)) {
@@ -174,13 +168,13 @@ class cache_config_writer extends cache_config {
}
}
$reflection = new ReflectionClass($class);
- if (!$reflection->isSubclassOf('cache_store')) {
+ if (!$reflection->isSubclassOf(store::class)) {
throw new cache_exception('Invalid cache plugin specified. The plugin does not extend the required class.');
}
if (!$class::are_requirements_met()) {
throw new cache_exception('Unable to add new cache plugin instance. The requested plugin type is not supported.');
}
- $this->configstores[$name] = array(
+ $this->configstores[$name] = [
'name' => $name,
'plugin' => $plugin,
'configuration' => $configuration,
@@ -188,8 +182,8 @@ class cache_config_writer extends cache_config {
'modes' => $class::get_supported_modes($configuration),
'mappingsonly' => !empty($configuration['mappingsonly']),
'class' => $class,
- 'default' => false
- );
+ 'default' => false,
+ ];
if (array_key_exists('lock', $configuration)) {
$this->configstores[$name]['lock'] = $configuration['lock'];
unset($this->configstores[$name]['configuration']['lock']);
@@ -210,11 +204,11 @@ class cache_config_writer extends cache_config {
* @param string $configuration Configuration data from the config instance.
* @throws cache_exception
*/
- public function add_lock_instance($name, $plugin, $configuration = array()) {
+ public function add_lock_instance($name, $plugin, $configuration = []) {
if (array_key_exists($name, $this->configlocks)) {
throw new cache_exception('Duplicate name specificed for cache lock instance. You must provide a unique name.');
}
- $class = 'cachelock_'.$plugin;
+ $class = 'cachelock_' . $plugin;
if (!class_exists($class)) {
$plugins = core_component::get_plugin_list_with_file('cachelock', 'lib.php');
if (!array_key_exists($plugin, $plugins)) {
@@ -229,14 +223,14 @@ class cache_config_writer extends cache_config {
}
}
$reflection = new ReflectionClass($class);
- if (!$reflection->implementsInterface('cache_lock_interface')) {
+ if (!$reflection->implementsInterface(lockable_cache_interface::class)) {
throw new cache_exception('Invalid lock plugin specified. The plugin does not implement the required interface.');
}
- $this->configlocks[$name] = array_merge($configuration, array(
+ $this->configlocks[$name] = array_merge($configuration, [
'name' => $name,
- 'type' => 'cachelock_'.$plugin,
- 'default' => false
- ));
+ 'type' => 'cachelock_' . $plugin,
+ 'default' => false,
+ ]);
$this->config_save();
}
@@ -276,11 +270,11 @@ class cache_config_writer extends cache_config {
* @throws cache_exception
*/
public function set_mode_mappings(array $modemappings) {
- $mappings = array(
- cache_store::MODE_APPLICATION => array(),
- cache_store::MODE_SESSION => array(),
- cache_store::MODE_REQUEST => array(),
- );
+ $mappings = [
+ store::MODE_APPLICATION => [],
+ store::MODE_SESSION => [],
+ store::MODE_REQUEST => [],
+ ];
foreach ($modemappings as $mode => $stores) {
if (!array_key_exists($mode, $mappings)) {
throw new cache_exception('The cache mode for the new mapping does not exist');
@@ -293,17 +287,17 @@ class cache_config_writer extends cache_config {
if (array_key_exists($store, $mappings[$mode])) {
throw new cache_exception('This cache mapping already exists');
}
- $mappings[$mode][] = array(
+ $mappings[$mode][] = [
'store' => $store,
'mode' => $mode,
- 'sort' => $sort++
- );
+ 'sort' => $sort++,
+ ];
}
}
$this->configmodemappings = array_merge(
- $mappings[cache_store::MODE_APPLICATION],
- $mappings[cache_store::MODE_SESSION],
- $mappings[cache_store::MODE_REQUEST]
+ $mappings[store::MODE_APPLICATION],
+ $mappings[store::MODE_SESSION],
+ $mappings[store::MODE_REQUEST]
);
$this->config_save();
@@ -331,17 +325,19 @@ class cache_config_writer extends cache_config {
if (!array_key_exists($plugin, $plugins)) {
throw new cache_exception('Invalid plugin name specified. The plugin either does not exist or is not valid.');
}
- $class = 'cachestore_'.$plugin;
+ $class = 'cachestore_' . $plugin;
$file = $plugins[$plugin];
if (!class_exists($class)) {
if (file_exists($file)) {
require_once($file);
}
if (!class_exists($class)) {
- throw new cache_exception('Invalid cache plugin specified. The plugin does not contain the required class.'.$class);
+ throw new cache_exception(
+ "Invalid cache plugin specified. The plugin does not contain the required class {$class}",
+ );
}
}
- $this->configstores[$name] = array(
+ $this->configstores[$name] = [
'name' => $name,
'plugin' => $plugin,
'configuration' => $configuration,
@@ -349,8 +345,8 @@ class cache_config_writer extends cache_config {
'modes' => $class::get_supported_modes($configuration),
'mappingsonly' => !empty($configuration['mappingsonly']),
'class' => $class,
- 'default' => $this->configstores[$name]['default'] // Can't change the default.
- );
+ 'default' => $this->configstores[$name]['default'], // Can't change the default.
+ ];
if (array_key_exists('lock', $configuration)) {
$this->configstores[$name]['lock'] = $configuration['lock'];
unset($this->configstores[$name]['configuration']['lock']);
@@ -388,7 +384,7 @@ class cache_config_writer extends cache_config {
}
// Call instance_deleted()
- $class = 'cachestore_'.$this->configstores[$name]['plugin'];
+ $class = 'cachestore_' . $this->configstores[$name]['plugin'];
$store = new $class($name, $this->configstores[$name]['configuration']);
$store->instance_deleted();
@@ -411,42 +407,42 @@ class cache_config_writer extends cache_config {
// HACK ALERT.
// We probably need to come up with a better way to create the default stores, or at least ensure 100% that the
// default store plugins are protected from deletion.
- $writer = new self;
+ $writer = new self();
$writer->configstores = self::get_default_stores();
$writer->configdefinitions = self::locate_definitions();
- $writer->configmodemappings = array(
- array(
- 'mode' => cache_store::MODE_APPLICATION,
+ $writer->configmodemappings = [
+ [
+ 'mode' => store::MODE_APPLICATION,
'store' => 'default_application',
- 'sort' => -1
- ),
- array(
- 'mode' => cache_store::MODE_SESSION,
+ 'sort' => -1,
+ ],
+ [
+ 'mode' => store::MODE_SESSION,
'store' => 'default_session',
- 'sort' => -1
- ),
- array(
- 'mode' => cache_store::MODE_REQUEST,
+ 'sort' => -1,
+ ],
+ [
+ 'mode' => store::MODE_REQUEST,
'store' => 'default_request',
- 'sort' => -1
- )
- );
- $writer->configlocks = array(
- 'default_file_lock' => array(
+ 'sort' => -1,
+ ],
+ ];
+ $writer->configlocks = [
+ 'default_file_lock' => [
'name' => 'cachelock_file_default',
'type' => 'cachelock_file',
'dir' => 'filelocks',
- 'default' => true
- )
- );
+ 'default' => true,
+ ],
+ ];
- $factory = cache_factory::instance();
+ $factory = factory::instance();
// We expect the cache to be initialising presently. If its not then something has gone wrong and likely
// we are now in a loop.
- if (!$forcesave && $factory->get_state() !== cache_factory::STATE_INITIALISING) {
+ if (!$forcesave && $factory->get_state() !== factory::STATE_INITIALISING) {
return $writer->generate_configuration_array();
}
- $factory->set_state(cache_factory::STATE_SAVING);
+ $factory->set_state(factory::STATE_SAVING);
$writer->config_save();
return true;
}
@@ -459,43 +455,43 @@ class cache_config_writer extends cache_config {
protected static function get_default_stores() {
global $CFG;
- require_once($CFG->dirroot.'/cache/stores/file/lib.php');
- require_once($CFG->dirroot.'/cache/stores/session/lib.php');
- require_once($CFG->dirroot.'/cache/stores/static/lib.php');
+ require_once($CFG->dirroot . '/cache/stores/file/lib.php');
+ require_once($CFG->dirroot . '/cache/stores/session/lib.php');
+ require_once($CFG->dirroot . '/cache/stores/static/lib.php');
- return array(
- 'default_application' => array(
+ return [
+ 'default_application' => [
'name' => 'default_application',
'plugin' => 'file',
- 'configuration' => array(),
+ 'configuration' => [],
'features' => cachestore_file::get_supported_features(),
'modes' => cachestore_file::get_supported_modes(),
'default' => true,
- ),
- 'default_session' => array(
+ ],
+ 'default_session' => [
'name' => 'default_session',
'plugin' => 'session',
- 'configuration' => array(),
+ 'configuration' => [],
'features' => cachestore_session::get_supported_features(),
'modes' => cachestore_session::get_supported_modes(),
'default' => true,
- ),
- 'default_request' => array(
+ ],
+ 'default_request' => [
'name' => 'default_request',
'plugin' => 'static',
- 'configuration' => array(),
+ 'configuration' => [],
'features' => cachestore_static::get_supported_features(),
'modes' => cachestore_static::get_supported_modes(),
'default' => true,
- )
- );
+ ],
+ ];
}
/**
* Updates the default stores within the MUC config file.
*/
public static function update_default_config_stores() {
- $factory = cache_factory::instance();
+ $factory = factory::instance();
$factory->updating_started();
$config = $factory->create_config_instance(true);
$config->configstores = array_merge($config->configstores, self::get_default_stores());
@@ -511,7 +507,7 @@ class cache_config_writer extends cache_config {
* @param bool $coreonly If set to true only core definitions will be updated.
*/
public static function update_definitions($coreonly = false) {
- $factory = cache_factory::instance();
+ $factory = factory::instance();
$factory->updating_started();
$config = $factory->create_config_instance(true);
$config->write_definitions_to_cache(self::locate_definitions($coreonly));
@@ -527,9 +523,9 @@ class cache_config_writer extends cache_config {
protected static function locate_definitions($coreonly = false) {
global $CFG;
- $files = array();
- if (file_exists($CFG->dirroot.'/lib/db/caches.php')) {
- $files['core'] = $CFG->dirroot.'/lib/db/caches.php';
+ $files = [];
+ if (file_exists($CFG->dirroot . '/lib/db/caches.php')) {
+ $files['core'] = $CFG->dirroot . '/lib/db/caches.php';
}
if (!$coreonly) {
@@ -537,22 +533,22 @@ class cache_config_writer extends cache_config {
foreach ($plugintypes as $type => $location) {
$plugins = core_component::get_plugin_list_with_file($type, 'db/caches.php');
foreach ($plugins as $plugin => $filepath) {
- $component = clean_param($type.'_'.$plugin, PARAM_COMPONENT); // Standardised plugin name.
+ $component = clean_param($type . '_' . $plugin, PARAM_COMPONENT); // Standardised plugin name.
$files[$component] = $filepath;
}
}
}
- $definitions = array();
+ $definitions = [];
foreach ($files as $component => $file) {
$filedefs = self::load_caches_file($file);
foreach ($filedefs as $area => $definition) {
$area = clean_param($area, PARAM_AREA);
- $id = $component.'/'.$area;
+ $id = $component . '/' . $area;
$definition['component'] = $component;
$definition['area'] = $area;
if (array_key_exists($id, $definitions)) {
- debugging('Error: duplicate cache definition found with id: '.$id, DEBUG_DEVELOPER);
+ debugging('Error: duplicate cache definition found with id: ' . $id, DEBUG_DEVELOPER);
continue;
}
$definitions[$id] = $definition;
@@ -597,9 +593,9 @@ class cache_config_writer extends cache_config {
*/
private static function load_caches_file($file) {
if (!file_exists($file)) {
- return array();
+ return [];
}
- $definitions = array();
+ $definitions = [];
include($file);
return $definitions;
}
@@ -627,11 +623,11 @@ class cache_config_writer extends cache_config {
}
$sort = count($mappings);
foreach ($mappings as $store) {
- $this->configdefinitionmappings[] = array(
+ $this->configdefinitionmappings[] = [
'store' => $store,
'definition' => $definition,
- 'sort' => $sort
- );
+ 'sort' => $sort,
+ ];
$sort--;
}
@@ -672,3 +668,8 @@ class cache_config_writer extends cache_config {
$this->config_save();
}
}
+
+// Alias this class to the old name.
+// This file will be autoloaded by the legacyclasses autoload system.
+// In future all uses of this class will be corrected and the legacy references will be removed.
+class_alias(config_writer::class, \cache_config_writer::class);
diff --git a/cache/classes/configurable_cache_interface.php b/cache/classes/configurable_cache_interface.php
new file mode 100644
index 00000000000..8fc7b247ba5
--- /dev/null
+++ b/cache/classes/configurable_cache_interface.php
@@ -0,0 +1,56 @@
+.
+
+namespace core_cache;
+
+use moodleform;
+use stdClass;
+
+/**
+ * Cache store feature: configurable.
+ *
+ * This feature should be implemented by all cache stores that are configurable when adding an instance.
+ * It requires the implementation of methods required to convert form data into the a configuration array for the
+ * store instance, and then the reverse converting configuration data into an array that can be used to set the
+ * data for the edit form.
+ *
+ * Can be implemented by classes already implementing store.
+ * @package core_cache
+ * @copyright Sam Hemelryk
+ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+interface configurable_cache_interface {
+ /**
+ * Given the data from the add instance form this function creates a configuration array.
+ *
+ * @param stdClass $data
+ * @return array
+ */
+ public static function config_get_configuration_array($data);
+
+ /**
+ * Allows the cache store to set its data against the edit form before it is shown to the user.
+ *
+ * @param moodleform $editform
+ * @param array $config
+ */
+ public static function config_set_edit_form_data(moodleform $editform, array $config);
+}
+
+// Alias this class to the old name.
+// This file will be autoloaded by the legacyclasses autoload system.
+// In future all uses of this class will be corrected and the legacy references will be removed.
+class_alias(configurable_cache_interface::class, \cache_is_configurable::class);
diff --git a/cache/classes/data_source_interface.php b/cache/classes/data_source_interface.php
new file mode 100644
index 00000000000..39770bf2e87
--- /dev/null
+++ b/cache/classes/data_source_interface.php
@@ -0,0 +1,66 @@
+.
+
+namespace core_cache;
+
+/**
+ * Cache Data Source.
+ *
+ * The cache data source interface can be implemented by any class within Moodle.
+ * If implemented then the class can be reference in a cache definition and will be used to load information that cannot be
+ * retrieved from the cache. As part of its retrieval that information will also be loaded into the cache.
+ *
+ * This allows developers to created a complete cache solution that can be used through code ensuring consistent cache
+ * interaction and loading. Allowing them in turn to centralise code and help keeps things more easily maintainable.
+ *
+ * Can be implemented by any class.
+ *
+ * @package core_cache
+ * @category cache
+ * @copyright 2012 Sam Hemelryk
+ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+interface data_source_interface {
+ /**
+ * Returns an instance of the data source class that the cache can use for loading data using the other methods
+ * specified by this interface.
+ *
+ * @param definition $definition
+ * @return object
+ */
+ public static function get_instance_for_cache(definition $definition);
+
+ /**
+ * Loads the data for the key provided ready formatted for caching.
+ *
+ * @param string|int $key The key to load.
+ * @return mixed What ever data should be returned, or false if it can't be loaded.
+ */
+ public function load_for_cache($key);
+
+ /**
+ * Loads several keys for the cache.
+ *
+ * @param array $keys An array of keys each of which will be string|int.
+ * @return array An array of matching data items.
+ */
+ public function load_many_for_cache(array $keys);
+}
+
+// Alias this class to the old name.
+// This file will be autoloaded by the legacyclasses autoload system.
+// In future all uses of this class will be corrected and the legacy references will be removed.
+class_alias(data_source_interface::class, \cache_data_source::class);
diff --git a/cache/classes/definition.php b/cache/classes/definition.php
index 588566f1f9c..8ab083074fd 100644
--- a/cache/classes/definition.php
+++ b/cache/classes/definition.php
@@ -14,19 +14,10 @@
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see .
-/**
- * Cache definition class
- *
- * This file is part of Moodle's cache API, affectionately called MUC.
- * It contains the components that are requried in order to use caching.
- *
- * @package core
- * @category cache
- * @copyright 2012 Sam Hemelryk
- * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
- */
+namespace core_cache;
-defined('MOODLE_INTERNAL') || die();
+use core\exception\coding_exception;
+use lang_string;
/**
* The cache definition class.
@@ -36,7 +27,7 @@ defined('MOODLE_INTERNAL') || die();
*
* Required settings:
* + mode
- * [int] Sets the mode for the definition. Must be one of cache_store::MODE_*
+ * [int] Sets the mode for the definition. Must be one of store::MODE_*
*
* Optional settings:
* + simplekeys
@@ -61,14 +52,14 @@ defined('MOODLE_INTERNAL') || die();
* + overrideclass
* [string] A class to use as the loader for this cache. This is an advanced setting and will allow the developer of the
* definition to take 100% control of the caching solution.
- * Any class used here must inherit the cache_loader interface and must extend default cache loader for the mode they are
+ * Any class used here must inherit the cache loader_interface and must extend default cache loader for the mode they are
* using.
* + overrideclassfile
* [string] Suplements the above setting indicated the file containing the class to be used. This file is included when
* required.
* + datasource
* [string] A class to use as the data loader for this definition.
- * Any class used here must inherit the cache_data_loader interface.
+ * Any class used here must inherit the \core_cache\data_source_interface interface.
* + datasourcefile
* [string] Supplements the above setting indicating the file containing the class to be used. This file is included when
* required.
@@ -103,13 +94,12 @@ defined('MOODLE_INTERNAL') || die();
*
* For examples take a look at lib/db/caches.php
*
- * @package core
+ * @package core_cache
* @category cache
* @copyright 2012 Sam Hemelryk
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
-class cache_definition {
-
+class definition {
/** The cache can be shared with everyone */
const SHARING_ALL = 1;
/** The cache can be shared with other sites using the same siteid. */
@@ -137,7 +127,7 @@ class cache_definition {
protected $id;
/**
- * The mode for the defintion. One of cache_store::MODE_*
+ * The mode for the defintion. One of store::MODE_*
* @var int
*/
protected $mode;
@@ -170,7 +160,7 @@ class cache_definition {
* An array of identifiers that must be provided when the definition is used to create a cache.
* @var array
*/
- protected $requireidentifiers = array();
+ protected $requireidentifiers = [];
/**
* If set to true then only stores that guarantee data may be used with this definition.
@@ -263,7 +253,7 @@ class cache_definition {
* An array of events that should cause this cache to invalidate.
* @var array
*/
- protected $invalidationevents = array();
+ protected $invalidationevents = [];
/**
* An array of identifiers provided to this cache when it was initialised.
@@ -319,7 +309,7 @@ class cache_definition {
* @param string $id
* @param array $definition
* @param string $unused Used to be datasourceaggregate but that was removed and this is now unused.
- * @return cache_definition
+ * @return definition
* @throws coding_exception
*/
public static function load($id, array $definition, $unused = null) {
@@ -341,11 +331,11 @@ class cache_definition {
// Set the defaults.
$simplekeys = false;
$simpledata = false;
- $requireidentifiers = array();
+ $requireidentifiers = [];
$requiredataguarantee = false;
$requiremultipleidentifiers = false;
$requirelockingbeforewrite = false;
- $requiresearchable = ($mode === cache_store::MODE_SESSION) ? true : false;
+ $requiresearchable = ($mode === store::MODE_SESSION) ? true : false;
$maxsize = null;
$overrideclass = null;
$overrideclassfile = null;
@@ -355,7 +345,7 @@ class cache_definition {
$staticaccelerationsize = false;
$ttl = 0;
$mappingsonly = false;
- $invalidationevents = array();
+ $invalidationevents = [];
$sharingoptions = self::SHARING_DEFAULT;
$selectedsharingoption = self::SHARING_DEFAULT;
$userinputsharingkey = '';
@@ -378,13 +368,17 @@ class cache_definition {
}
if (array_key_exists('requirelockingread', $definition)) {
- debugging('The cache option requirelockingread is deprecated and now has no effect.',
- DEBUG_DEVELOPER);
+ debugging(
+ 'The cache option requirelockingread is deprecated and now has no effect.',
+ DEBUG_DEVELOPER
+ );
}
if (array_key_exists('requirelockingwrite', $definition)) {
- debugging('The cache option requirelockingwrite is deprecated and now has no effect. ' .
+ debugging(
+ 'The cache option requirelockingwrite is deprecated and now has no effect. ' .
"Consider removing the option, or using requirelockingbeforewrite for the $component:$area definition",
- DEBUG_DEVELOPER);
+ DEBUG_DEVELOPER
+ );
}
if (array_key_exists('requirelockingbeforewrite', $definition)) {
$requirelockingbeforewrite = (bool)$definition['requirelockingbeforewrite'];
@@ -465,7 +459,7 @@ class cache_definition {
if (!is_null($overrideclass)) {
if (!is_null($overrideclassfile)) {
if (strpos($overrideclassfile, $CFG->dirroot) !== 0) {
- $overrideclassfile = $CFG->dirroot.'/'.$overrideclassfile;
+ $overrideclassfile = $CFG->dirroot . '/' . $overrideclassfile;
}
if (strpos($overrideclassfile, '../') !== false) {
throw new coding_exception('No path craziness allowed within override class file path.');
@@ -480,7 +474,7 @@ class cache_definition {
}
// Make sure that the provided class extends the default class for the mode.
- if (get_parent_class($overrideclass) !== cache_helper::get_class_for_mode($mode)) {
+ if (get_parent_class($overrideclass) !== helper::get_class_for_mode($mode)) {
throw new coding_exception('The override class does not immediately extend the relevant cache class.');
}
}
@@ -488,7 +482,7 @@ class cache_definition {
if (!is_null($datasource)) {
if (!is_null($datasourcefile)) {
if (strpos($datasourcefile, $CFG->dirroot) !== 0) {
- $datasourcefile = $CFG->dirroot.'/'.$datasourcefile;
+ $datasourcefile = $CFG->dirroot . '/' . $datasourcefile;
}
if (strpos($datasourcefile, '../') !== false) {
throw new coding_exception('No path craziness allowed within data source file path.');
@@ -501,12 +495,12 @@ class cache_definition {
if (!class_exists($datasource)) {
throw new coding_exception('The data source class does not exist.');
}
- if (!array_key_exists('cache_data_source', class_implements($datasource))) {
- throw new coding_exception('Cache data source classes must implement the cache_data_source interface');
+ if (!is_a($datasource, data_source_interface::class, true)) {
+ throw new coding_exception('Cache data source classes must implement the data_source_interface interface');
}
}
- $cachedefinition = new cache_definition();
+ $cachedefinition = new self();
$cachedefinition->id = $id;
$cachedefinition->mode = $mode;
$cachedefinition->component = $component;
@@ -543,7 +537,7 @@ class cache_definition {
* Please note that when using an adhoc definition you cannot set any of the optional params.
* This is because we cannot guarantee consistent access and we don't want to mislead people into thinking that.
*
- * @param int $mode One of cache_store::MODE_*
+ * @param int $mode One of store::MODE_*
* @param string $component The component this definition relates to.
* @param string $area The area this definition relates to.
* @param array $options An array of options, available options are:
@@ -552,15 +546,15 @@ class cache_definition {
* - overrideclass : The class to use as the loader.
* - staticacceleration : If set to true the cache will hold onto data passing through it.
* - staticaccelerationsize : Set it to an int to limit the size of the staticacceleration cache.
- * @return cache_application|cache_session|cache_request
+ * @return self
*/
- public static function load_adhoc($mode, $component, $area, array $options = array()) {
- $id = 'adhoc/'.$component.'_'.$area;
- $definition = array(
+ public static function load_adhoc($mode, $component, $area, array $options = []) {
+ $id = 'adhoc/' . $component . '_' . $area;
+ $definition = [
'mode' => $mode,
'component' => $component,
'area' => $area,
- );
+ ];
if (!empty($options['simplekeys'])) {
$definition['simplekeys'] = $options['simplekeys'];
}
@@ -594,7 +588,7 @@ class cache_definition {
if (!is_null($this->overrideclass)) {
return $this->overrideclass;
}
- return cache_helper::get_class_for_mode($this->mode);
+ return helper::get_class_for_mode($this->mode);
}
/**
@@ -610,7 +604,7 @@ class cache_definition {
* @return string
*/
public function get_name() {
- $identifier = 'cachedef_'.clean_param($this->area, PARAM_STRINGID);
+ $identifier = 'cachedef_' . clean_param($this->area, PARAM_STRINGID);
$component = $this->component;
if ($component === 'core') {
$component = 'cache';
@@ -620,7 +614,7 @@ class cache_definition {
/**
* Returns the mode of this definition
- * @return int One more cache_store::MODE_
+ * @return int One more store::MODE_
*/
public function get_mode() {
return $this->mode;
@@ -659,7 +653,7 @@ class cache_definition {
*/
public function get_identifiers() {
if (!isset($this->identifiers)) {
- return array();
+ return [];
}
return $this->identifiers;
}
@@ -757,14 +751,14 @@ class cache_definition {
/**
* Returns an instance of the data source class used for this definition.
*
- * @return cache_data_source
+ * @return data_source_interface
* @throws coding_exception
*/
public function get_data_source() {
if (!$this->has_data_source()) {
throw new coding_exception('This cache does not use a data source.');
}
- return forward_static_call(array($this->datasource, 'get_instance_for_cache'), $this);
+ return forward_static_call([$this->datasource, 'get_instance_for_cache'], $this);
}
/**
@@ -774,7 +768,7 @@ class cache_definition {
* @return bool false if no identifiers where changed, true otherwise.
* @throws coding_exception
*/
- public function set_identifiers(array $identifiers = array()) {
+ public function set_identifiers(array $identifiers = []) {
if ($this->identifiers !== null) {
throw new coding_exception("You can only set identifiers on initial definition creation." .
" Define a new cache to set different identifiers.");
@@ -785,11 +779,11 @@ class cache_definition {
foreach ($this->requireidentifiers as $identifier) {
if (!isset($identifiers[$identifier])) {
- throw new coding_exception('Identifier required for cache has not been provided: '.$identifier);
+ throw new coding_exception('Identifier required for cache has not been provided: ' . $identifier);
}
}
- $this->identifiers = array();
+ $this->identifiers = [];
foreach ($identifiers as $name => $value) {
$this->identifiers[$name] = (string)$value;
@@ -808,26 +802,26 @@ class cache_definition {
public function get_requirements_bin() {
$requires = 0;
if ($this->require_data_guarantee()) {
- $requires += cache_store::SUPPORTS_DATA_GUARANTEE;
+ $requires += store::SUPPORTS_DATA_GUARANTEE;
}
if ($this->require_multiple_identifiers()) {
- $requires += cache_store::SUPPORTS_MULTIPLE_IDENTIFIERS;
+ $requires += store::SUPPORTS_MULTIPLE_IDENTIFIERS;
}
if ($this->require_searchable()) {
- $requires += cache_store::IS_SEARCHABLE;
+ $requires += store::IS_SEARCHABLE;
}
return $requires;
}
/**
- * Please call {@link cache_definition::use_static_acceleration()} instead.
+ * Please call {@link definition::use_static_acceleration()} instead.
*
- * @see cache_definition::use_static_acceleration()
+ * @see definition::use_static_acceleration()
* @deprecated since 2.6
*/
public function should_be_persistent() {
- throw new coding_exception('cache_definition::should_be_persistent() can not be used anymore.' .
- ' Please use cache_definition::use_static_acceleration() instead.');
+ throw new coding_exception('definition::should_be_persistent() can not be used anymore.' .
+ ' Please use definition::use_static_acceleration() instead.');
}
/**
@@ -839,7 +833,7 @@ class cache_definition {
* @return bool
*/
public function use_static_acceleration() {
- if ($this->mode === cache_store::MODE_REQUEST) {
+ if ($this->mode === store::MODE_REQUEST) {
// Request caches should never use static acceleration - it just doesn't make sense.
return false;
}
@@ -847,14 +841,14 @@ class cache_definition {
}
/**
- * Please call {@link cache_definition::get_static_acceleration_size()} instead.
+ * Please call {@link definition::get_static_acceleration_size()} instead.
*
- * @see cache_definition::get_static_acceleration_size()
+ * @see definition::get_static_acceleration_size()
* @deprecated since 2.6
*/
public function get_persistent_max_size() {
- throw new coding_exception('cache_definition::get_persistent_max_size() can not be used anymore.' .
- ' Please use cache_definition::get_static_acceleration_size() instead.');
+ throw new coding_exception('definition::get_persistent_max_size() can not be used anymore.' .
+ ' Please use definition::get_static_acceleration_size() instead.');
}
/**
@@ -883,12 +877,12 @@ class cache_definition {
*/
public function generate_single_key_prefix() {
if ($this->keyprefixsingle === null) {
- $this->keyprefixsingle = $this->mode.'/'.$this->component.'/'.$this->area;
- $this->keyprefixsingle .= '/'.$this->get_cache_identifier();
+ $this->keyprefixsingle = $this->mode . '/' . $this->component . '/' . $this->area;
+ $this->keyprefixsingle .= '/' . $this->get_cache_identifier();
$identifiers = $this->get_identifiers();
if ($identifiers) {
foreach ($identifiers as $key => $value) {
- $this->keyprefixsingle .= '/'.$key.'='.$value;
+ $this->keyprefixsingle .= '/' . $key . '=' . $value;
}
}
$this->keyprefixsingle = md5($this->keyprefixsingle);
@@ -903,16 +897,16 @@ class cache_definition {
*/
public function generate_multi_key_parts() {
if ($this->keyprefixmulti === null) {
- $this->keyprefixmulti = array(
+ $this->keyprefixmulti = [
'mode' => $this->mode,
'component' => $this->component,
'area' => $this->area,
- 'siteidentifier' => $this->get_cache_identifier()
- );
+ 'siteidentifier' => $this->get_cache_identifier(),
+ ];
if (isset($this->identifiers) && !empty($this->identifiers)) {
- $identifiers = array();
+ $identifiers = [];
foreach ($this->identifiers as $key => $value) {
- $identifiers[] = htmlentities($key, ENT_QUOTES, 'UTF-8').'='.htmlentities($value, ENT_QUOTES, 'UTF-8');
+ $identifiers[] = htmlentities($key, ENT_QUOTES, 'UTF-8') . '=' . htmlentities($value, ENT_QUOTES, 'UTF-8');
}
$this->keyprefixmulti['identifiers'] = join('&', $identifiers);
}
@@ -954,15 +948,15 @@ class cache_definition {
* @return string A string to be used as part of keys.
*/
protected function get_cache_identifier() {
- $identifiers = array();
+ $identifiers = [];
if ($this->selectedsharingoption & self::SHARING_ALL) {
// Nothing to do here.
} else {
if ($this->selectedsharingoption & self::SHARING_SITEID) {
- $identifiers[] = cache_helper::get_site_identifier();
+ $identifiers[] = helper::get_site_identifier();
}
if ($this->selectedsharingoption & self::SHARING_VERSION) {
- $identifiers[] = cache_helper::get_site_version();
+ $identifiers[] = helper::get_site_version();
}
if ($this->selectedsharingoption & self::SHARING_INPUT && !empty($this->userinputsharingkey)) {
$identifiers[] = $this->userinputsharingkey;
@@ -1007,3 +1001,8 @@ class cache_definition {
return $this->selectedsharingoption;
}
}
+
+// Alias this class to the old name.
+// This file will be autoloaded by the legacyclasses autoload system.
+// In future all uses of this class will be corrected and the legacy references will be removed.
+class_alias(definition::class, \cache_definition::class);
diff --git a/cache/classes/disabled_cache.php b/cache/classes/disabled_cache.php
new file mode 100644
index 00000000000..27fc8f36b66
--- /dev/null
+++ b/cache/classes/disabled_cache.php
@@ -0,0 +1,223 @@
+.
+
+namespace core_cache;
+
+use core\exception\coding_exception;
+
+/**
+ * The cache loader class used when the Cache has been disabled.
+ *
+ * @package core_cache
+ * @copyright 2012 Sam Hemelryk
+ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+class disabled_cache extends cache implements loader_with_locking_interface {
+ /**
+ * Constructs the cache.
+ *
+ * @param definition $definition
+ * @param store $store
+ * @param null $loader Unused.
+ */
+ public function __construct(definition $definition, store $store, $loader = null) {
+ if ($loader instanceof data_source_interface) {
+ // Set the data source to allow data sources to work when caching is entirely disabled.
+ $this->set_data_source($loader);
+ }
+
+ // No other features are handled.
+ }
+
+ /**
+ * Gets a key from the cache.
+ *
+ * @param int|string $key
+ * @param int $requiredversion Minimum required version of the data or cache::VERSION_NONE
+ * @param int $strictness Unused.
+ * @param mixed &$actualversion If specified, will be set to the actual version number retrieved
+ * @return bool
+ */
+ protected function get_implementation($key, int $requiredversion, int $strictness, &$actualversion = null) {
+ $datasource = $this->get_datasource();
+ if ($datasource !== false) {
+ if ($requiredversion === cache::VERSION_NONE) {
+ return $datasource->load_for_cache($key);
+ } else {
+ if (!$datasource instanceof versionable_data_source_interface) {
+ throw new coding_exception('Data source is not versionable');
+ }
+ $result = $datasource->load_for_cache_versioned($key, $requiredversion, $actualversion);
+ if ($result && $actualversion < $requiredversion) {
+ throw new coding_exception('Data source returned outdated version');
+ }
+ return $result;
+ }
+ }
+ return false;
+ }
+
+ /**
+ * Gets many keys at once from the cache.
+ *
+ * @param array $keys
+ * @param int $strictness Unused.
+ * @return array
+ */
+ public function get_many(array $keys, $strictness = IGNORE_MISSING) {
+ if ($this->get_datasource() !== false) {
+ return $this->get_datasource()->load_many_for_cache($keys);
+ }
+
+ return array_combine($keys, array_fill(0, count($keys), false));
+ }
+
+ /**
+ * Sets a key value pair in the cache.
+ *
+ * @param int|string $key Unused.
+ * @param int $version Unused.
+ * @param mixed $data Unused.
+ * @param bool $setparents Unused.
+ * @return bool
+ */
+ protected function set_implementation($key, int $version, $data, bool $setparents = true): bool {
+ return false;
+ }
+
+ /**
+ * Sets many key value pairs in the cache at once.
+ *
+ * @param array $keyvaluearray Unused.
+ * @return int
+ */
+ public function set_many(array $keyvaluearray) {
+ return 0;
+ }
+
+ /**
+ * Deletes an item from the cache.
+ *
+ * @param int|string $key Unused.
+ * @param bool $recurse Unused.
+ * @return bool
+ */
+ public function delete($key, $recurse = true) {
+ return false;
+ }
+
+ /**
+ * Deletes many items at once from the cache.
+ *
+ * @param array $keys Unused.
+ * @param bool $recurse Unused.
+ * @return int
+ */
+ public function delete_many(array $keys, $recurse = true) {
+ return 0;
+ }
+
+ /**
+ * Checks if the cache has the requested key.
+ *
+ * @param int|string $key Unused.
+ * @param bool $tryloadifpossible Unused.
+ * @return bool
+ */
+ public function has($key, $tryloadifpossible = false) {
+ $result = $this->get($key);
+
+ return $result !== false;
+ }
+
+ /**
+ * Checks if the cache has all of the requested keys.
+ * @param array $keys Unused.
+ * @return bool
+ */
+ public function has_all(array $keys) {
+ if (!$this->get_datasource()) {
+ return false;
+ }
+
+ foreach ($keys as $key) {
+ if (!$this->has($key)) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ /**
+ * Checks if the cache has any of the requested keys.
+ *
+ * @param array $keys Unused.
+ * @return bool
+ */
+ public function has_any(array $keys) {
+ foreach ($keys as $key) {
+ if ($this->has($key)) {
+ return true;
+ }
+ }
+
+ return false;
+ }
+
+ /**
+ * Purges all items from the cache.
+ *
+ * @return bool
+ */
+ public function purge() {
+ return true;
+ }
+
+ /**
+ * Pretend that we got a lock to avoid errors.
+ *
+ * @param int|string $key
+ * @return bool
+ */
+ public function acquire_lock($key): bool {
+ return true;
+ }
+
+ /**
+ * Pretend that we released a lock to avoid errors.
+ *
+ * @param int|string $key
+ * @return bool
+ */
+ public function release_lock($key): bool {
+ return true;
+ }
+
+ /**
+ * Pretend that we have a lock to avoid errors.
+ *
+ * @param int|string $key
+ * @return bool
+ */
+ public function check_lock_state($key): bool {
+ return true;
+ }
+}
+
+// Alias this class to the old name.
+// This file will be autoloaded by the legacyclasses autoload system.
+// In future all uses of this class will be corrected and the legacy references will be removed.
+class_alias(disabled_cache::class, \cache_disabled::class);
diff --git a/cache/classes/disabled_config.php b/cache/classes/disabled_config.php
new file mode 100644
index 00000000000..af017db37df
--- /dev/null
+++ b/cache/classes/disabled_config.php
@@ -0,0 +1,220 @@
+.
+
+namespace core_cache;
+
+use core\exception\coding_exception;
+use core_cache\exception\cache_exception;
+use cachestore_static;
+use cachestore_session;
+use cachestore_file;
+
+/**
+ * The cache config class used when the Cache has been disabled.
+ *
+ * @package core_cache
+ * @copyright 2012 Sam Hemelryk
+ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+class disabled_config extends config_writer {
+ /**
+ * Returns an instance of the configuration writer.
+ *
+ * @return disabled_config
+ */
+ public static function instance() {
+ $factory = factory::instance();
+ return $factory->create_config_instance(true);
+ }
+
+ /**
+ * Saves the current configuration.
+ */
+ protected function config_save() {
+ // Nothing to do here.
+ }
+
+ /**
+ * Generates a configuration array suitable to be written to the config file.
+ *
+ * @return array
+ */
+ protected function generate_configuration_array() {
+ $configuration = [];
+ $configuration['stores'] = $this->configstores;
+ $configuration['modemappings'] = $this->configmodemappings;
+ $configuration['definitions'] = $this->configdefinitions;
+ $configuration['definitionmappings'] = $this->configdefinitionmappings;
+ $configuration['locks'] = $this->configlocks;
+ return $configuration;
+ }
+
+ /**
+ * Adds a plugin instance.
+ *
+ * @param string $name Unused.
+ * @param string $plugin Unused.
+ * @param array $configuration Unused.
+ * @return bool
+ * @throws cache_exception
+ */
+ public function add_store_instance($name, $plugin, array $configuration = []) {
+ return false;
+ }
+
+ /**
+ * Sets the mode mappings.
+ *
+ * @param array $modemappings Unused.
+ * @return bool
+ * @throws cache_exception
+ */
+ public function set_mode_mappings(array $modemappings) {
+ return false;
+ }
+
+ /**
+ * Edits a give plugin instance.
+ *
+ * @param string $name Unused.
+ * @param string $plugin Unused.
+ * @param array $configuration Unused.
+ * @return bool
+ * @throws cache_exception
+ */
+ public function edit_store_instance($name, $plugin, $configuration) {
+ return false;
+ }
+
+ /**
+ * Deletes a store instance.
+ *
+ * @param string $name Unused.
+ * @return bool
+ * @throws cache_exception
+ */
+ public function delete_store_instance($name) {
+ return false;
+ }
+
+ /**
+ * Creates the default configuration and saves it.
+ *
+ * @param bool $forcesave Ignored because we are disabled!
+ * @return array
+ */
+ public static function create_default_configuration($forcesave = false) {
+ global $CFG;
+
+ // HACK ALERT.
+ // We probably need to come up with a better way to create the default stores, or at least ensure 100% that the
+ // default store plugins are protected from deletion.
+ require_once($CFG->dirroot . '/cache/stores/file/lib.php');
+ require_once($CFG->dirroot . '/cache/stores/session/lib.php');
+ require_once($CFG->dirroot . '/cache/stores/static/lib.php');
+
+ $writer = new self();
+ $writer->configstores = [
+ 'default_application' => [
+ 'name' => 'default_application',
+ 'plugin' => 'file',
+ 'configuration' => [],
+ 'features' => cachestore_file::get_supported_features(),
+ 'modes' => store::MODE_APPLICATION,
+ 'default' => true,
+ ],
+ 'default_session' => [
+ 'name' => 'default_session',
+ 'plugin' => 'session',
+ 'configuration' => [],
+ 'features' => cachestore_session::get_supported_features(),
+ 'modes' => store::MODE_SESSION,
+ 'default' => true,
+ ],
+ 'default_request' => [
+ 'name' => 'default_request',
+ 'plugin' => 'static',
+ 'configuration' => [],
+ 'features' => cachestore_static::get_supported_features(),
+ 'modes' => store::MODE_REQUEST,
+ 'default' => true,
+ ],
+ ];
+ $writer->configdefinitions = [];
+ $writer->configmodemappings = [
+ [
+ 'mode' => store::MODE_APPLICATION,
+ 'store' => 'default_application',
+ 'sort' => -1,
+ ],
+ [
+ 'mode' => store::MODE_SESSION,
+ 'store' => 'default_session',
+ 'sort' => -1,
+ ],
+ [
+ 'mode' => store::MODE_REQUEST,
+ 'store' => 'default_request',
+ 'sort' => -1,
+ ],
+ ];
+ $writer->configlocks = [
+ 'default_file_lock' => [
+ 'name' => 'cachelock_file_default',
+ 'type' => 'cachelock_file',
+ 'dir' => 'filelocks',
+ 'default' => true,
+ ],
+ ];
+
+ return $writer->generate_configuration_array();
+ }
+
+ /**
+ * Updates the definition in the configuration from those found in the cache files.
+ *
+ * @param bool $coreonly Unused.
+ */
+ public static function update_definitions($coreonly = false) {
+ // Nothing to do here.
+ }
+
+ /**
+ * Locates all of the definition files.
+ *
+ * @param bool $coreonly Unused.
+ * @return array
+ */
+ protected static function locate_definitions($coreonly = false) {
+ return [];
+ }
+
+ /**
+ * Sets the mappings for a given definition.
+ *
+ * @param string $definition Unused.
+ * @param array $mappings Unused.
+ * @throws coding_exception
+ */
+ public function set_definition_mappings($definition, $mappings) {
+ // Nothing to do here.
+ }
+}
+
+// Alias this class to the old name.
+// This file will be autoloaded by the legacyclasses autoload system.
+// In future all uses of this class will be corrected and the legacy references will be removed.
+class_alias(disabled_config::class, \cache_config_disabled::class);
diff --git a/cache/classes/disabled_factory.php b/cache/classes/disabled_factory.php
new file mode 100644
index 00000000000..d2f3fc2c15d
--- /dev/null
+++ b/cache/classes/disabled_factory.php
@@ -0,0 +1,208 @@
+.
+
+namespace core_cache;
+
+use cachestore_static;
+use core\exception\coding_exception;
+
+/**
+ * The cache factory class used when the Cache has been disabled.
+ *
+ * @package core_cache
+ * @copyright 2012 Sam Hemelryk
+ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+class disabled_factory extends factory {
+ /** @var array Array of temporary caches in use. */
+ protected static $tempcaches = [];
+
+ /**
+ * Returns an instance of the factory method.
+ *
+ * @param bool $forcereload Unused.
+ * @return factory
+ * @throws coding_exception
+ */
+ public static function instance($forcereload = false) {
+ throw new coding_exception('You must not call to this cache factory within your code.');
+ }
+
+ /**
+ * Creates a definition instance or returns the existing one if it has already been created.
+ *
+ * @param string $component
+ * @param string $area
+ * @param string $unused Used to be datasourceaggregate but that was removed and this is now unused.
+ * @return definition
+ */
+ public function create_definition($component, $area, $unused = null) {
+ $definition = parent::create_definition($component, $area);
+ if ($definition->has_data_source()) {
+ return $definition;
+ }
+
+ return definition::load_adhoc(store::MODE_REQUEST, $component, $area);
+ }
+
+ /**
+ * Common public method to create a cache instance given a definition.
+ *
+ * @param definition $definition
+ * @return application_cache|session_cache|store
+ * @throws coding_exception
+ */
+ public function create_cache(definition $definition) {
+ $loader = null;
+ if ($definition->has_data_source()) {
+ $loader = $definition->get_data_source();
+ }
+ return new disabled_cache($definition, $this->create_dummy_store($definition), $loader);
+ }
+
+ /**
+ * Creates a cache object given the parameters for a definition.
+ *
+ * @param string $component
+ * @param string $area
+ * @param array $identifiers
+ * @param string $unused Used to be datasourceaggregate but that was removed and this is now unused.
+ * @return application_cache|session_cache|request_cache
+ */
+ public function create_cache_from_definition($component, $area, array $identifiers = [], $unused = null) {
+ // Temporary in-memory caches are sometimes allowed when caching is disabled.
+ if (\core_cache\allow_temporary_caches::is_allowed() && !$identifiers) {
+ $key = $component . '/' . $area;
+ if (array_key_exists($key, self::$tempcaches)) {
+ $cache = self::$tempcaches[$key];
+ } else {
+ $definition = $this->create_definition($component, $area);
+ // The cachestore_static class returns true to all three 'SUPPORTS_' checks so it
+ // can be used with all definitions.
+ $store = new cachestore_static('TEMP:' . $component . '/' . $area);
+ $store->initialise($definition);
+ // We need to use a cache loader wrapper rather than directly returning the store,
+ // or it wouldn't have support for versioning. The application_cache class is used
+ // (rather than request_cache which might make more sense logically) because it
+ // includes support for locking, which might be necessary for some caches.
+ $cache = new application_cache($definition, $store);
+ self::$tempcaches[$key] = $cache;
+ }
+ return $cache;
+ }
+
+ // Regular cache definitions are cached inside create_definition(). This is not the case for disabledlib.php
+ // definitions as they use load_adhoc(). They are built as a new object on each call.
+ // We do not need to clone the definition because we know it's new.
+ $definition = $this->create_definition($component, $area);
+ $definition->set_identifiers($identifiers);
+ $cache = $this->create_cache($definition);
+ return $cache;
+ }
+
+ /**
+ * Removes all temporary caches.
+ *
+ * Don't call this directly - used by {@see \core_cache\allow_temporary_caches}.
+ */
+ public static function clear_temporary_caches(): void {
+ self::$tempcaches = [];
+ }
+
+ /**
+ * Creates an ad-hoc cache from the given param.
+ *
+ * @param int $mode
+ * @param string $component
+ * @param string $area
+ * @param array $identifiers
+ * @param array $options An array of options, available options are:
+ * - simplekeys : Set to true if the keys you will use are a-zA-Z0-9_
+ * - simpledata : Set to true if the type of the data you are going to store is scalar, or an array of scalar vars
+ * - staticacceleration : If set to true the cache will hold onto all data passing through it.
+ * - staticaccelerationsize : Sets the max size of the static acceleration array.
+ * @return application_cache|session_cache|request_cache
+ */
+ public function create_cache_from_params($mode, $component, $area, array $identifiers = [], array $options = []) {
+ // Regular cache definitions are cached inside create_definition(). This is not the case for disabledlib.php
+ // definitions as they use load_adhoc(). They are built as a new object on each call.
+ // We do not need to clone the definition because we know it's new.
+ $definition = definition::load_adhoc($mode, $component, $area, $options);
+ $definition->set_identifiers($identifiers);
+ $cache = $this->create_cache($definition);
+ return $cache;
+ }
+
+ /**
+ * Creates a store instance given its name and configuration.
+ *
+ * @param string $name Unused.
+ * @param array $details Unused.
+ * @param definition $definition
+ * @return boolean|store
+ */
+ public function create_store_from_config($name, array $details, definition $definition) {
+ return $this->create_dummy_store($definition);
+ }
+
+ /**
+ * Creates a cache config instance with the ability to write if required.
+ *
+ * @param bool $writer Unused.
+ * @return disabled_config|config_writer
+ */
+ public function create_config_instance($writer = false) {
+ // We are always going to use the disabled_config class for all regular request.
+ // However if the code has requested the writer then likely something is changing and
+ // we're going to need to interact with the config.php file.
+ // In this case we will still use the config_writer.
+ $class = disabled_config::class;
+ if ($writer) {
+ // If the writer was requested then something is changing.
+ $class = config_writer::class;
+ }
+ if (!array_key_exists($class, $this->configs)) {
+ self::set_state(factory::STATE_INITIALISING);
+ if ($class === disabled_config::class) {
+ $configuration = $class::create_default_configuration();
+ $this->configs[$class] = new $class();
+ } else {
+ $configuration = false;
+ // If we need a writer, we should get the classname from the generic factory.
+ // This is so alternative classes can be used if a different writer is required.
+ $this->configs[$class] = parent::get_disabled_writer();
+ }
+ $this->configs[$class]->load($configuration);
+ }
+ self::set_state(factory::STATE_READY);
+
+ // Return the instance.
+ return $this->configs[$class];
+ }
+
+ /**
+ * Returns true if the cache API has been disabled.
+ *
+ * @return bool
+ */
+ public function is_disabled() {
+ return true;
+ }
+}
+// Alias this class to the old name.
+// This file will be autoloaded by the legacyclasses autoload system.
+// In future all uses of this class will be corrected and the legacy references will be removed.
+class_alias(disabled_factory::class, \cache_factory_disabled::class);
diff --git a/cache/classes/dummystore.php b/cache/classes/dummy_cachestore.php
similarity index 77%
rename from cache/classes/dummystore.php
rename to cache/classes/dummy_cachestore.php
index f268cef50c9..a63d2e2a489 100644
--- a/cache/classes/dummystore.php
+++ b/cache/classes/dummy_cachestore.php
@@ -14,31 +14,16 @@
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see .
-/**
- * Cache dummy store.
- *
- * This dummy store is used when a load has no other stores that it can make use of.
- * This shouldn't happen in normal operation... I think.
- *
- * This file is part of Moodle's cache API, affectionately called MUC.
- * It contains the components that are requried in order to use caching.
- *
- * @package core
- * @category cache
- * @copyright 2012 Sam Hemelryk
- * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
- */
-
-defined('MOODLE_INTERNAL') || die();
+namespace core_cache;
/**
* The cache dummy store.
*
* @copyright 2012 Sam Hemelryk
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ * @package core_cache
*/
-class cachestore_dummy extends cache_store {
-
+class dummy_cachestore extends store {
/**
* The name of this store.
* @var string
@@ -57,11 +42,11 @@ class cachestore_dummy extends cache_store {
* The stored data array
* @var array
*/
- protected $store = array();
+ protected $store = [];
/**
* Cache definition
- * @var cache_definition
+ * @var definition
*/
protected $definition;
@@ -70,7 +55,7 @@ class cachestore_dummy extends cache_store {
* @param string $name
* @param array $configuration
*/
- public function __construct($name = 'Dummy store', array $configuration = array()) {
+ public function __construct($name = 'Dummy store', array $configuration = []) {
$this->name = $name;
}
@@ -95,8 +80,8 @@ class cachestore_dummy extends cache_store {
* @param array $configuration
* @return int
*/
- public static function get_supported_features(array $configuration = array()) {
- return self::SUPPORTS_NATIVE_TTL;
+ public static function get_supported_features(array $configuration = []) {
+ return store::SUPPORTS_NATIVE_TTL;
}
/**
@@ -104,22 +89,22 @@ class cachestore_dummy extends cache_store {
* @param array $configuration
* @return int
*/
- public static function get_supported_modes(array $configuration = array()) {
- return self::MODE_APPLICATION + self::MODE_REQUEST + self::MODE_SESSION;
+ public static function get_supported_modes(array $configuration = []) {
+ return store::MODE_APPLICATION + store::MODE_REQUEST + store::MODE_SESSION;
}
/**
* Initialises the store instance for a definition.
- * @param cache_definition $definition
+ * @param definition $definition
*/
- public function initialise(cache_definition $definition) {
+ public function initialise(definition $definition) {
// If the definition isn't using static acceleration then we need to be store data here.
// The reasoning behind this is that:
- // - If the definition is using static acceleration then the cache loader is going to
- // store things in its static array.
- // - If the definition is not using static acceleration then the cache loader won't try to store anything
- // and we will need to store it here in order to make sure it is accessible.
- if ($definition->get_mode() !== self::MODE_APPLICATION) {
+ // - If the definition is using static acceleration then the cache loader is going to
+ // store things in its static array.
+ // - If the definition is not using static acceleration then the cache loader won't try to store anything
+ // and we will need to store it here in order to make sure it is accessible.
+ if ($definition->get_mode() !== store::MODE_APPLICATION) {
// Neither the request cache nor the session cache provide static acceleration.
$this->persist = true;
} else {
@@ -164,7 +149,7 @@ class cachestore_dummy extends cache_store {
* @return bool
*/
public function get_many($keys) {
- $return = array();
+ $return = [];
foreach ($keys as $key) {
if ($this->persist && array_key_exists($key, $this->store)) {
$return[$key] = $this->store[$key];
@@ -198,7 +183,6 @@ class cachestore_dummy extends cache_store {
foreach ($keyvaluearray as $pair) {
$this->store[$pair['key']] = $pair['value'];
}
-
}
return count($keyvaluearray);
}
@@ -231,7 +215,7 @@ class cachestore_dummy extends cache_store {
* @return bool
*/
public function purge() {
- $this->store = array();
+ $this->store = [];
return true;
}
@@ -239,11 +223,13 @@ class cachestore_dummy extends cache_store {
* Performs any necessary clean up when the store instance is being deleted.
*
* @deprecated since 3.2
- * @see cachestore_dummy::instance_deleted()
+ * @see dummy_cachestore::instance_deleted()
*/
public function cleanup() {
- debugging('cachestore_dummy::cleanup() is deprecated. Please use cachestore_dummy::instance_deleted() instead.',
- DEBUG_DEVELOPER);
+ debugging(
+ 'dummy_cachestore::cleanup() is deprecated. Please use dummy_cachestore::instance_deleted() instead.',
+ DEBUG_DEVELOPER
+ );
$this->instance_deleted();
}
@@ -261,11 +247,11 @@ class cachestore_dummy extends cache_store {
/**
* Generates an instance of the cache store that can be used for testing.
*
- * @param cache_definition $definition
- * @return false
+ * @param definition $definition
+ * @return self
*/
- public static function initialise_test_instance(cache_definition $definition) {
- $cache = new cachestore_dummy('Dummy store test');
+ public static function initialise_test_instance(definition $definition) {
+ $cache = new dummy_cachestore('Dummy store test');
if ($cache->is_ready()) {
$cache->initialise($definition);
}
@@ -289,3 +275,8 @@ class cachestore_dummy extends cache_store {
return $this->name;
}
}
+
+// Alias this class to the old name.
+// This file will be autoloaded by the legacyclasses autoload system.
+// In future all uses of this class will be corrected and the legacy references will be removed.
+class_alias(dummy_cachestore::class, \cachestore_dummy::class);
diff --git a/cache/classes/exception/cache_exception.php b/cache/classes/exception/cache_exception.php
new file mode 100644
index 00000000000..205caea990d
--- /dev/null
+++ b/cache/classes/exception/cache_exception.php
@@ -0,0 +1,48 @@
+.
+
+namespace core_cache\exception;
+
+use core\exception\moodle_exception;
+
+/**
+ * A cache exception class. Just allows people to catch cache exceptions.
+ *
+ * @package core_cache
+ * @category cache
+ * @copyright 2012 Sam Hemelryk
+ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+class cache_exception extends moodle_exception {
+ /**
+ * Constructs a new exception
+ *
+ * @param string $errorcode
+ * @param string $module
+ * @param string $link
+ * @param mixed $a
+ * @param mixed $debuginfo
+ */
+ public function __construct($errorcode, $module = 'cache', $link = '', $a = null, $debuginfo = null) {
+ // This may appear like a useless override but you will notice that we have set a MUCH more useful default for $module.
+ parent::__construct($errorcode, $module, $link, $a, $debuginfo);
+ }
+}
+
+// Alias this class to the old name.
+// This file will be autoloaded by the legacyclasses autoload system.
+// In future all uses of this class will be corrected and the legacy references will be removed.
+class_alias(cache_exception::class, \cache_exception::class);
diff --git a/cache/classes/factory.php b/cache/classes/factory.php
index 116b1b36258..bfc85b9dc7a 100644
--- a/cache/classes/factory.php
+++ b/cache/classes/factory.php
@@ -14,19 +14,11 @@
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see .
-/**
- * This file contains the cache factory class.
- *
- * This file is part of Moodle's cache API, affectionately called MUC.
- * It contains the components that are requried in order to use caching.
- *
- * @package core
- * @category cache
- * @copyright 2012 Sam Hemelryk
- * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
- */
+namespace core_cache;
-defined('MOODLE_INTERNAL') || die();
+use core\exception\coding_exception;
+use cache_config_testing;
+use cache_phpunit_factory;
/**
* The cache factory class.
@@ -37,9 +29,9 @@ defined('MOODLE_INTERNAL') || die();
*
* @copyright 2012 Sam Hemelryk
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ * @package core_cache
*/
-class cache_factory {
-
+class factory {
/** The cache has not been initialised yet. */
const STATE_UNINITIALISED = 0;
/** The cache is in the process of initialising itself. */
@@ -58,8 +50,8 @@ class cache_factory {
const STATE_STORES_DISABLED = 11;
/**
- * An instance of the cache_factory class created upon the first request.
- * @var cache_factory
+ * An instance of the factory class created upon the first request.
+ * @var factory
*/
protected static $instance;
@@ -67,43 +59,43 @@ class cache_factory {
* An array containing caches created for definitions
* @var array
*/
- protected $cachesfromdefinitions = array();
+ protected $cachesfromdefinitions = [];
/**
* Array of caches created by parameters, ad-hoc definitions will have been used.
* @var array
*/
- protected $cachesfromparams = array();
+ protected $cachesfromparams = [];
/**
* An array of stores organised by definitions.
* @var array
*/
- protected $definitionstores = array();
+ protected $definitionstores = [];
/**
* An array of instantiated stores.
* @var array
*/
- protected $stores = array();
+ protected $stores = [];
/**
* An array of configuration instances
* @var array
*/
- protected $configs = array();
+ protected $configs = [];
/**
* An array of initialised definitions
* @var array
*/
- protected $definitions = array();
+ protected $definitions = [];
/**
* An array of lock plugins.
* @var array
*/
- protected $lockplugins = array();
+ protected $lockplugins = [];
/**
* The current state of the cache API.
@@ -118,10 +110,10 @@ class cache_factory {
protected static $displayhelper = null;
/**
- * Returns an instance of the cache_factory class.
+ * Returns an instance of the factory class.
*
- * @param bool $forcereload If set to true a new cache_factory instance will be created and used.
- * @return cache_factory
+ * @param bool $forcereload If set to true a new factory instance will be created and used.
+ * @return factory
*/
public static function instance($forcereload = false) {
global $CFG;
@@ -130,23 +122,21 @@ class cache_factory {
if (defined('CACHE_DISABLE_ALL') && CACHE_DISABLE_ALL !== false) {
// The cache has been disabled. Load disabledlib and start using the factory designed to handle this
// situation. It will use disabled alternatives where available.
- require_once($CFG->dirroot.'/cache/disabledlib.php');
- self::$instance = new cache_factory_disabled();
+ self::$instance = new disabled_factory();
} else if ((defined('PHPUNIT_TEST') && PHPUNIT_TEST) || defined('BEHAT_SITE_RUNNING')) {
// We're using the test factory.
- require_once($CFG->dirroot.'/cache/tests/fixtures/lib.php');
+ require_once($CFG->dirroot . '/cache/tests/fixtures/lib.php');
self::$instance = new cache_phpunit_factory();
if (defined('CACHE_DISABLE_STORES') && CACHE_DISABLE_STORES !== false) {
// The cache stores have been disabled.
self::$instance->set_state(self::STATE_STORES_DISABLED);
}
-
} else if (!empty($CFG->alternative_cache_factory_class)) {
$factoryclass = $CFG->alternative_cache_factory_class;
self::$instance = new $factoryclass();
} else {
// We're using the regular factory.
- self::$instance = new cache_factory();
+ self::$instance = new factory();
if (defined('CACHE_DISABLE_STORES') && CACHE_DISABLE_STORES !== false) {
// The cache stores have been disabled.
self::$instance->set_state(self::STATE_STORES_DISABLED);
@@ -169,10 +159,10 @@ class cache_factory {
public static function reset() {
$factory = self::instance();
$factory->reset_cache_instances();
- $factory->configs = array();
- $factory->definitions = array();
- $factory->definitionstores = array();
- $factory->lockplugins = array(); // MUST be null in order to force its regeneration.
+ $factory->configs = [];
+ $factory->definitions = [];
+ $factory->definitionstores = [];
+ $factory->lockplugins = []; // MUST be null in order to force its regeneration.
// Reset the state to uninitialised.
$factory->state = self::STATE_UNINITIALISED;
}
@@ -184,9 +174,9 @@ class cache_factory {
* however all future requests for a cache/store will lead to a new instance being re-initialised.
*/
public function reset_cache_instances() {
- $this->cachesfromdefinitions = array();
- $this->cachesfromparams = array();
- $this->stores = array();
+ $this->cachesfromdefinitions = [];
+ $this->cachesfromparams = [];
+ $this->stores = [];
}
/**
@@ -198,11 +188,11 @@ class cache_factory {
* @param string $area
* @param array $identifiers
* @param string $unused Used to be data source aggregate however that was removed and this is now unused.
- * @return cache_application|cache_session|cache_request
+ * @return application_cache|session_cache|request_cache
*/
- public function create_cache_from_definition($component, $area, array $identifiers = array(), $unused = null) {
- $identifierstring = empty($identifiers) ? '' : '/'.http_build_query($identifiers);
- $definitionname = $component.'/'.$area.$identifierstring;
+ public function create_cache_from_definition($component, $area, array $identifiers = [], $unused = null) {
+ $identifierstring = empty($identifiers) ? '' : '/' . http_build_query($identifiers);
+ $definitionname = $component . '/' . $area . $identifierstring;
if (isset($this->cachesfromdefinitions[$definitionname])) {
$cache = $this->cachesfromdefinitions[$definitionname];
return $cache;
@@ -232,10 +222,10 @@ class cache_factory {
* - simpledata : Set to true if the type of the data you are going to store is scalar, or an array of scalar vars
* - staticacceleration : If set to true the cache will hold onto data passing through it.
* - staticaccelerationsize : The maximum number of items to hold onto for acceleration purposes.
- * @return cache_application|cache_session|cache_request
+ * @return application_cache|session_cache|request_cache
*/
- public function create_cache_from_params($mode, $component, $area, array $identifiers = array(), array $options = array()) {
- $identifierstring = empty($identifiers) ? '' : '_'.http_build_query($identifiers);
+ public function create_cache_from_params($mode, $component, $area, array $identifiers = [], array $options = []) {
+ $identifierstring = empty($identifiers) ? '' : '_' . http_build_query($identifiers);
$key = "{$mode}_{$component}_{$area}{$identifierstring}";
if (isset($this->cachesfromparams[$key])) {
return $this->cachesfromparams[$key];
@@ -243,7 +233,7 @@ class cache_factory {
// Regular cache definitions are cached inside create_definition(). This is not the case for Adhoc definitions
// using load_adhoc(). They are built as a new object on each call.
// We do not need to clone the definition because we know it's new.
- $definition = cache_definition::load_adhoc($mode, $component, $area, $options);
+ $definition = definition::load_adhoc($mode, $component, $area, $options);
$definition->set_identifiers($identifiers);
$cache = $this->create_cache($definition);
$this->cachesfromparams[$key] = $cache;
@@ -255,13 +245,13 @@ class cache_factory {
*
* This is used by the static make methods.
*
- * @param cache_definition $definition
- * @return cache_application|cache_session|cache_store
+ * @param definition $definition
+ * @return application_cache|session_cache|store
* @throws coding_exception
*/
- public function create_cache(cache_definition $definition) {
+ public function create_cache(definition $definition) {
$class = $definition->get_cache_class();
- $stores = cache_helper::get_stores_suitable_for_definition($definition);
+ $stores = helper::get_stores_suitable_for_definition($definition);
foreach ($stores as $key => $store) {
if (!$store::are_requirements_met()) {
unset($stores[$key]);
@@ -288,10 +278,10 @@ class cache_factory {
*
* @param string $name The name of the store (must be unique remember)
* @param array $details
- * @param cache_definition $definition The definition to instantiate it for.
- * @return boolean|cache_store
+ * @param definition $definition The definition to instantiate it for.
+ * @return boolean|store
*/
- public function create_store_from_config($name, array $details, cache_definition $definition) {
+ public function create_store_from_config($name, array $details, definition $definition) {
if (!array_key_exists($name, $this->stores)) {
// Properties: name, plugin, configuration, class.
$class = $details['class'];
@@ -301,7 +291,7 @@ class cache_factory {
$store = new $class($details['name'], $details['configuration']);
$this->stores[$name] = $store;
}
- /* @var cache_store $store */
+ /* @var store $store */
$store = $this->stores[$name];
// We check are_requirements_met although we expect is_ready is going to check as well.
if (!$store::are_requirements_met() || !$store->is_ready() || !$store->is_supported_mode($definition->get_mode())) {
@@ -317,7 +307,7 @@ class cache_factory {
$store->initialise($definition);
$definitionid = $definition->get_id();
if (!isset($this->definitionstores[$definitionid])) {
- $this->definitionstores[$definitionid] = array();
+ $this->definitionstores[$definitionid] = [];
}
$this->definitionstores[$definitionid][] = $store;
return $store;
@@ -325,13 +315,13 @@ class cache_factory {
/**
* Returns an array of cache stores that have been initialised for use in definitions.
- * @param cache_definition $definition
+ * @param definition $definition
* @return array
*/
- public function get_store_instances_in_use(cache_definition $definition) {
+ public function get_store_instances_in_use(definition $definition) {
$id = $definition->get_id();
if (!isset($this->definitionstores[$id])) {
- return array();
+ return [];
}
return $this->definitionstores[$id];
}
@@ -348,7 +338,7 @@ class cache_factory {
/**
* Gets all adhoc caches that have been used within this request.
*
- * @return cache_store[] Caches currently in use
+ * @return store[] Caches currently in use
*/
public function get_adhoc_caches_in_use() {
return $this->cachesfromparams;
@@ -358,31 +348,29 @@ class cache_factory {
* Creates a cache config instance with the ability to write if required.
*
* @param bool $writer If set to true an instance that can update the configuration will be returned.
- * @return cache_config|cache_config_writer
+ * @return config|config_writer
*/
public function create_config_instance($writer = false) {
global $CFG;
// The class to use.
- $class = 'cache_config';
+ $class = config::class;
// Are we running tests of some form?
$testing = (defined('PHPUNIT_TEST') && PHPUNIT_TEST) || defined('BEHAT_SITE_RUNNING');
// Check if this is a PHPUnit test and redirect to the phpunit config classes if it is.
if ($testing) {
- require_once($CFG->dirroot.'/cache/locallib.php');
- require_once($CFG->dirroot.'/cache/tests/fixtures/lib.php');
+ require_once($CFG->dirroot . '/cache/tests/fixtures/lib.php');
// We have just a single class for PHP unit tests. We don't care enough about its
// performance to do otherwise and having a single method allows us to inject things into it
// while testing.
- $class = 'cache_config_testing';
+ $class = cache_config_testing::class;
}
// Check if we need to create a config file with defaults.
$needtocreate = !$class::config_file_exists();
if ($writer || $needtocreate) {
- require_once($CFG->dirroot.'/cache/locallib.php');
if (!$testing) {
$class .= '_writer';
}
@@ -393,12 +381,12 @@ class cache_factory {
// Create the default configuration.
// Update the state, we are now initialising the cache.
self::set_state(self::STATE_INITIALISING);
- /** @var cache_config_writer $class */
+ /** @var config_writer $class */
$configuration = $class::create_default_configuration();
if ($configuration !== true) {
// Failed to create the default configuration. Disable the cache stores and update the state.
self::set_state(self::STATE_ERROR_INITIALISING);
- $this->configs[$class] = new $class;
+ $this->configs[$class] = new $class();
$this->configs[$class]->load($configuration);
$error = true;
}
@@ -406,7 +394,7 @@ class cache_factory {
if (!array_key_exists($class, $this->configs)) {
// Create a new instance and call it to load it.
- $this->configs[$class] = new $class;
+ $this->configs[$class] = new $class();
$this->configs[$class]->load();
}
@@ -425,17 +413,17 @@ class cache_factory {
* @param string $area
* @param string $unused This used to be data source aggregate - however that functionality has been removed and
* this argument is now unused.
- * @return cache_definition
+ * @return definition
* @throws coding_exception If the definition cannot be found.
*/
public function create_definition($component, $area, $unused = null) {
- $id = $component.'/'.$area;
+ $id = $component . '/' . $area;
if (!isset($this->definitions[$id])) {
// This is the first time this definition has been requested.
if ($this->is_initialising()) {
// We're initialising the cache right now. Don't try to create another config instance.
// We'll just use an ad-hoc cache for the time being.
- $definition = cache_definition::load_adhoc(cache_store::MODE_REQUEST, $component, $area);
+ $definition = definition::load_adhoc(store::MODE_REQUEST, $component, $area);
} else {
// Load all the known definitions and find the desired one.
$instance = $this->create_config_instance();
@@ -450,7 +438,7 @@ class cache_factory {
// This means that the cache initialisation has requested something from a cache (I had recursive nightmares about this).
// To serve this purpose and avoid errors we are going to make use of an ad-hoc cache rather than
// search for the definition which would possibly cause an infitite loop trying to initialise the cache.
- $definition = cache_definition::load_adhoc(cache_store::MODE_REQUEST, $component, $area);
+ $definition = definition::load_adhoc(store::MODE_REQUEST, $component, $area);
} else {
// Either a typo of the developer has just created the definition and is using it for the first time.
$this->reset();
@@ -458,16 +446,16 @@ class cache_factory {
$instance->update_definitions();
$definition = $instance->get_definition_by_id($id);
if (!$definition) {
- throw new coding_exception('The requested cache definition does not exist.'. $id, $id);
+ throw new coding_exception('The requested cache definition does not exist.' . $id, $id);
}
if (!$this->is_disabled()) {
debugging('Cache definitions reparsed causing cache reset in order to locate definition.
You should bump the version number to ensure definitions are reprocessed.', DEBUG_DEVELOPER);
}
- $definition = cache_definition::load($id, $definition);
+ $definition = definition::load($id, $definition);
}
} else {
- $definition = cache_definition::load($id, $definition);
+ $definition = definition::load($id, $definition);
}
}
$this->definitions[$id] = $definition;
@@ -478,13 +466,11 @@ class cache_factory {
/**
* Creates a dummy store object for use when a loader has no potential stores to use.
*
- * @param cache_definition $definition
- * @return cachestore_dummy
+ * @param definition $definition
+ * @return dummy_cachestore
*/
- protected function create_dummy_store(cache_definition $definition) {
- global $CFG;
- require_once($CFG->dirroot.'/cache/classes/dummystore.php');
- $store = new cachestore_dummy();
+ protected function create_dummy_store(definition $definition) {
+ $store = new dummy_cachestore();
$store->initialise($definition);
return $store;
}
@@ -493,7 +479,7 @@ class cache_factory {
* Returns a lock instance ready for use.
*
* @param array $config
- * @return cache_lock_interface
+ * @return lockable_cache_interface
*/
public function create_lock_instance(array $config) {
global $CFG;
@@ -507,7 +493,7 @@ class cache_factory {
if (!isset($this->lockplugins[$type])) {
$pluginname = substr($type, 10);
- $file = $CFG->dirroot."/cache/locks/{$pluginname}/lib.php";
+ $file = $CFG->dirroot . "/cache/locks/{$pluginname}/lib.php";
if (file_exists($file) && is_readable($file)) {
require_once($file);
}
@@ -611,9 +597,7 @@ class cache_factory {
* MUC it was decided that this was just to risky and abusable.
*/
protected static function disable() {
- global $CFG;
- require_once($CFG->dirroot.'/cache/disabledlib.php');
- self::$instance = new cache_factory_disabled();
+ self::$instance = new disabled_factory();
}
/**
@@ -635,9 +619,9 @@ class cache_factory {
* In order to re-enable the cache you must call the cache factories static reset method:
*
* // Disable the cache factory.
- * cache_factory::disable_stores();
+ * factory::disable_stores();
* // Re-enable the cache factory by resetting it.
- * cache_factory::reset();
+ * factory::reset();
*
*/
public static function disable_stores() {
@@ -650,9 +634,9 @@ class cache_factory {
/**
* Returns an instance of the current display_helper.
*
- * @return core_cache\administration_helper
+ * @return administration_helper
*/
- public static function get_administration_display_helper(): core_cache\administration_helper {
+ public static function get_administration_display_helper(): administration_helper {
if (is_null(self::$displayhelper)) {
self::$displayhelper = new \core_cache\local\administration_display_helper();
}
@@ -660,12 +644,12 @@ class cache_factory {
}
/**
- * Gets the cache_config_writer to use when caching is disabled.
- * This should only be called from cache_factory_disabled.
+ * Gets the config_writer to use when caching is disabled.
+ * This should only be called from disabled_factory.
*
- * @return cache_config_writer
+ * @return config_writer
*/
- public static function get_disabled_writer(): cache_config_writer {
+ public static function get_disabled_writer(): config_writer {
global $CFG;
// Figure out if we are in a recursive loop using late static binding.
@@ -680,14 +664,19 @@ class cache_factory {
$factoryinstance = new $CFG->alternative_cache_factory_class();
return $factoryinstance::get_disabled_writer();
} else {
- // We got here from cache_factory_disabled.
+ // We got here from disabled_factory.
// We should use the default writer here.
// Make sure we have a default config if needed.
- if (!cache_config::config_file_exists()) {
- cache_config_writer::create_default_configuration(true);
+ if (!config::config_file_exists()) {
+ config_writer::create_default_configuration(true);
}
- return new cache_config_writer();
+ return new config_writer();
}
}
}
+
+// Alias this class to the old name.
+// This file will be autoloaded by the legacyclasses autoload system.
+// In future all uses of this class will be corrected and the legacy references will be removed.
+class_alias(factory::class, \cache_factory::class);
diff --git a/cache/classes/form/cache_definition_mappings_form.php b/cache/classes/form/cache_definition_mappings_form.php
new file mode 100644
index 00000000000..8ce1aadbca3
--- /dev/null
+++ b/cache/classes/form/cache_definition_mappings_form.php
@@ -0,0 +1,102 @@
+.
+
+namespace core_cache\form;
+
+use core_cache\administration_helper;
+use core_cache\store;
+use html_writer;
+use moodleform;
+
+/**
+ * Form to set definition mappings
+ *
+ * @package core_cache
+ * @category cache
+ * @copyright 2012 Sam Hemelryk
+ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+class cache_definition_mappings_form extends moodleform {
+ /**
+ * The definition of the form
+ */
+ final protected function definition() {
+ global $OUTPUT;
+
+ $definition = $this->_customdata['definition'];
+ $form = $this->_form;
+
+ [$component, $area] = explode('/', $definition, 2);
+ [$currentstores, $storeoptions, $defaults] =
+ administration_helper::get_definition_store_options($component, $area);
+
+ $storedata = administration_helper::get_definition_summaries();
+ if ($storedata[$definition]['mode'] != store::MODE_REQUEST) {
+ if (isset($storedata[$definition]['canuselocalstore']) && $storedata[$definition]['canuselocalstore']) {
+ $form->addElement('html', $OUTPUT->notification(get_string('localstorenotification', 'cache'), 'notifymessage'));
+ } else {
+ $form->addElement('html', $OUTPUT->notification(get_string('sharedstorenotification', 'cache'), 'notifymessage'));
+ }
+ }
+ $form->addElement('hidden', 'definition', $definition);
+ $form->setType('definition', PARAM_SAFEPATH);
+ $form->addElement('hidden', 'action', 'editdefinitionmapping');
+ $form->setType('action', PARAM_ALPHA);
+
+ $requiredoptions = max(3, count($currentstores) + 1);
+ $requiredoptions = min($requiredoptions, count($storeoptions));
+
+ $options = ['' => get_string('none')];
+ foreach ($storeoptions as $option => $def) {
+ $options[$option] = $option;
+ if ($def['default']) {
+ $options[$option] .= ' ' . get_string('mappingdefault', 'cache');
+ }
+ }
+
+ for ($i = 0; $i < $requiredoptions; $i++) {
+ $title = '...';
+ if ($i === 0) {
+ $title = get_string('mappingprimary', 'cache');
+ } else if ($i === $requiredoptions - 1) {
+ $title = get_string('mappingfinal', 'cache');
+ }
+ $form->addElement('select', 'mappings[' . $i . ']', $title, $options);
+ }
+ $i = 0;
+ foreach ($currentstores as $store => $def) {
+ $form->setDefault('mappings[' . $i . ']', $store);
+ $i++;
+ }
+
+ if (!empty($defaults)) {
+ $form->addElement(
+ 'static',
+ 'defaults',
+ get_string('defaultmappings', 'cache'),
+ html_writer::tag('strong', join(', ', $defaults))
+ );
+ $form->addHelpButton('defaults', 'defaultmappings', 'cache');
+ }
+
+ $this->add_action_buttons();
+ }
+}
+
+// Alias this class to the old name.
+// This file will be autoloaded by the legacyclasses autoload system.
+// In future all uses of this class will be corrected and the legacy references will be removed.
+class_alias(cache_definition_mappings_form::class, \cache_definition_mappings_form::class);
diff --git a/cache/classes/form/cache_definition_sharing_form.php b/cache/classes/form/cache_definition_sharing_form.php
new file mode 100644
index 00000000000..3f011da7313
--- /dev/null
+++ b/cache/classes/form/cache_definition_sharing_form.php
@@ -0,0 +1,105 @@
+.
+
+namespace core_cache\form;
+
+use core_cache\administration_helper;
+use core_cache\definition;
+use moodleform;
+
+/**
+ * Form to set definition sharing option
+ *
+ * @package core_cache
+ * @category cache
+ * @copyright 2013 Sam Hemelryk
+ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+class cache_definition_sharing_form extends moodleform {
+ /**
+ * The definition of the form
+ */
+ final protected function definition() {
+ $definition = $this->_customdata['definition'];
+ $sharingoptions = $this->_customdata['sharingoptions'];
+ $form = $this->_form;
+
+ $form->addElement('hidden', 'definition', $definition);
+ $form->setType('definition', PARAM_SAFEPATH);
+ $form->addElement('hidden', 'action', 'editdefinitionsharing');
+ $form->setType('action', PARAM_ALPHA);
+
+ // We use a group here for validation.
+ $count = 0;
+ $group = [];
+ foreach ($sharingoptions as $value => $text) {
+ $count++;
+ $group[] = $form->createElement('checkbox', $value, null, $text);
+ }
+ $form->addGroup($group, 'sharing', get_string('sharing', 'cache'), '
');
+ $form->setType('sharing', PARAM_INT);
+
+ $form->addElement('text', 'userinputsharingkey', get_string('userinputsharingkey', 'cache'));
+ $form->addHelpButton('userinputsharingkey', 'userinputsharingkey', 'cache');
+ $form->disabledIf('userinputsharingkey', 'sharing[' . definition::SHARING_INPUT . ']', 'notchecked');
+ $form->setType('userinputsharingkey', PARAM_ALPHANUMEXT);
+
+ $values = array_keys($sharingoptions);
+ if (in_array(definition::SHARING_ALL, $values)) {
+ // If you share with all thenthe other options don't really make sense.
+ foreach ($values as $value) {
+ $form->disabledIf('sharing[' . $value . ']', 'sharing[' . definition::SHARING_ALL . ']', 'checked');
+ }
+ $form->disabledIf('userinputsharingkey', 'sharing[' . definition::SHARING_ALL . ']', 'checked');
+ }
+
+ $this->add_action_buttons();
+ }
+
+ /**
+ * Sets the data for this form.
+ *
+ * @param array $data
+ */
+ public function set_data($data) {
+ if (!isset($data['sharing'])) {
+ // Set the default value here. mforms doesn't handle defaults very nicely.
+ $data['sharing'] = administration_helper::get_definition_sharing_options(definition::SHARING_DEFAULT);
+ }
+ parent::set_data($data);
+ }
+
+ /**
+ * Validates this form
+ *
+ * @param array $data
+ * @param array $files
+ * @return array
+ */
+ public function validation($data, $files) {
+ $errors = parent::validation($data, $files);
+ if (count($errors) === 0 && !isset($data['sharing'])) {
+ // They must select at least one sharing option.
+ $errors['sharing'] = get_string('sharingrequired', 'cache');
+ }
+ return $errors;
+ }
+}
+
+// Alias this class to the old name.
+// This file will be autoloaded by the legacyclasses autoload system.
+// In future all uses of this class will be corrected and the legacy references will be removed.
+class_alias(cache_definition_sharing_form::class, \cache_definition_sharing_form::class);
diff --git a/cache/classes/form/cache_lock_form.php b/cache/classes/form/cache_lock_form.php
new file mode 100644
index 00000000000..c323327245f
--- /dev/null
+++ b/cache/classes/form/cache_lock_form.php
@@ -0,0 +1,96 @@
+.
+
+namespace core_cache\form;
+
+use core_cache\config as cache_config;
+use moodleform;
+
+/**
+ * Form to add a cache lock instance.
+ *
+ * All cache lock plugins that wish to have custom configuration should override
+ * this form, and more explicitly the plugin_definition and plugin_validation methods.
+ *
+ * @package core_cache
+ * @category cache
+ * @copyright 2013 Sam Hemelryk
+ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+class cache_lock_form extends moodleform {
+ /**
+ * Defines this form.
+ */
+ final public function definition() {
+ $plugin = $this->_customdata['lock'];
+
+ $this->_form->addElement('hidden', 'action', 'newlockinstance');
+ $this->_form->setType('action', PARAM_ALPHANUMEXT);
+ $this->_form->addElement('hidden', 'lock', $plugin);
+ $this->_form->setType('lock', PARAM_COMPONENT);
+ $this->_form->addElement('text', 'name', get_string('lockname', 'cache'));
+ $this->_form->setType('name', PARAM_ALPHANUMEXT);
+ $this->_form->addRule('name', get_string('required'), 'required');
+ $this->_form->addElement('static', 'namedesc', '', get_string('locknamedesc', 'cache'));
+
+ $this->plugin_definition();
+
+ $this->add_action_buttons();
+ }
+
+ /**
+ * Validates this form.
+ *
+ * @param array $data
+ * @param array $files
+ * @return array
+ */
+ final public function validation($data, $files) {
+ $errors = parent::validation($data, $files);
+ if (!isset($errors['name'])) {
+ $config = cache_config::instance();
+ if (in_array($data['name'], array_keys($config->get_locks()))) {
+ $errors['name'] = get_string('locknamenotunique', 'cache');
+ }
+ }
+ $errors = $this->plugin_validation($data, $files, $errors);
+ return $errors;
+ }
+
+ /**
+ * Plugin specific definition.
+ */
+ public function plugin_definition() {
+ // No custom validation going on here.
+ }
+
+ /**
+ * Plugin specific validation.
+ *
+ * @param array $data
+ * @param array $files
+ * @param array $errors
+ * @return array
+ */
+ public function plugin_validation($data, $files, array $errors) {
+ return $errors;
+ }
+}
+
+// Alias this class to the old name.
+// This file will be autoloaded by the legacyclasses autoload system.
+// In future all uses of this class will be corrected and the legacy references will be removed.
+class_alias(cache_lock_form::class, \cache_lock_form::class);
diff --git a/cache/classes/form/cache_mode_mappings_form.php b/cache/classes/form/cache_mode_mappings_form.php
new file mode 100644
index 00000000000..174871ca85a
--- /dev/null
+++ b/cache/classes/form/cache_mode_mappings_form.php
@@ -0,0 +1,68 @@
+.
+
+namespace core_cache\form;
+
+use core_cache\store;
+use moodleform;
+
+/**
+ * Form to set the mappings for a mode.
+ *
+ * @package core_cache
+ * @category cache
+ * @copyright 2012 Sam Hemelryk
+ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+class cache_mode_mappings_form extends moodleform {
+ /**
+ * The definition of the form
+ */
+ protected function definition() {
+ $form = $this->_form;
+ $stores = $this->_customdata;
+
+ $options = [
+ store::MODE_APPLICATION => [],
+ store::MODE_SESSION => [],
+ store::MODE_REQUEST => [],
+ ];
+ foreach ($stores as $storename => $store) {
+ foreach ($store['modes'] as $mode => $enabled) {
+ if ($enabled && ($mode !== store::MODE_SESSION || $store['supports']['searchable'])) {
+ if (empty($store['default'])) {
+ $options[$mode][$storename] = $store['name'];
+ } else {
+ $options[$mode][$storename] = get_string('store_' . $store['name'], 'cache');
+ }
+ }
+ }
+ }
+
+ $form->addElement('hidden', 'action', 'editmodemappings');
+ $form->setType('action', PARAM_ALPHA);
+ foreach ($options as $mode => $optionset) {
+ $form->addElement('select', 'mode_' . $mode, get_string('mode_' . $mode, 'cache'), $optionset);
+ }
+
+ $this->add_action_buttons();
+ }
+}
+
+// Alias this class to the old name.
+// This file will be autoloaded by the legacyclasses autoload system.
+// In future all uses of this class will be corrected and the legacy references will be removed.
+class_alias(cache_mode_mappings_form::class, \cache_mode_mappings_form::class);
diff --git a/cache/classes/form/cachestore_addinstance_form.php b/cache/classes/form/cachestore_addinstance_form.php
new file mode 100644
index 00000000000..742c37f50bb
--- /dev/null
+++ b/cache/classes/form/cachestore_addinstance_form.php
@@ -0,0 +1,109 @@
+.
+
+namespace core_cache\form;
+
+use core_cache\administration_helper;
+use moodleform;
+
+/**
+ * Add store instance form.
+ *
+ * @package core_cache
+ * @category cache
+ * @copyright 2012 Sam Hemelryk
+ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+class cachestore_addinstance_form extends moodleform {
+ #[\Override]
+ final protected function definition() {
+ $form = $this->_form;
+ $store = $this->_customdata['store'];
+ $plugin = $this->_customdata['plugin'];
+ $locks = $this->_customdata['locks'];
+
+ $form->addElement('hidden', 'plugin', $plugin);
+ $form->setType('plugin', PARAM_PLUGIN);
+ $form->addElement('hidden', 'editing', !empty($this->_customdata['store']));
+ $form->setType('editing', PARAM_BOOL);
+
+ if (!$store) {
+ $form->addElement('text', 'name', get_string('storename', 'cache'));
+ $form->addHelpButton('name', 'storename', 'cache');
+ $form->addRule('name', get_string('required'), 'required');
+ $form->setType('name', PARAM_NOTAGS);
+ } else {
+ $form->addElement('hidden', 'name', $store);
+ $form->addElement('static', 'name-value', get_string('storename', 'cache'), $store);
+ $form->setType('name', PARAM_NOTAGS);
+ }
+
+ if (is_array($locks)) {
+ $form->addElement('select', 'lock', get_string('locking', 'cache'), $locks);
+ $form->addHelpButton('lock', 'locking', 'cache');
+ $form->setType('lock', PARAM_ALPHANUMEXT);
+ } else {
+ $form->addElement('hidden', 'lock', '');
+ $form->setType('lock', PARAM_ALPHANUMEXT);
+ $form->addElement(
+ 'static',
+ 'lock-value',
+ get_string('locking', 'cache'),
+ '' . get_string('nativelocking', 'cache') . ''
+ );
+ }
+
+ if (method_exists($this, 'configuration_definition')) {
+ $form->addElement('header', 'storeconfiguration', get_string('storeconfiguration', 'cache'));
+ $this->configuration_definition();
+ }
+
+ $this->add_action_buttons();
+ }
+
+ #[\Override]
+ public function validation($data, $files) {
+ $errors = parent::validation($data, $files);
+
+ if (!array_key_exists('name', $errors)) {
+ if (!preg_match('#^[a-zA-Z0-9\-_ ]+$#', $data['name'])) {
+ $errors['name'] = get_string('storenameinvalid', 'cache');
+ } else if (empty($this->_customdata['store'])) {
+ $stores = administration_helper::get_store_instance_summaries();
+ if (array_key_exists($data['name'], $stores)) {
+ $errors['name'] = get_string('storenamealreadyused', 'cache');
+ }
+ }
+ }
+
+ if (method_exists($this, 'configuration_validation')) {
+ $newerrors = $this->configuration_validation($data, $files, $errors);
+ // We need to selectiviliy merge here.
+ foreach ($newerrors as $element => $error) {
+ if (!array_key_exists($element, $errors)) {
+ $errors[$element] = $error;
+ }
+ }
+ }
+
+ return $errors;
+ }
+}
+
+// Alias this class to the old name.
+// This file will be autoloaded by the legacyclasses autoload system.
+// In future all uses of this class will be corrected and the legacy references will be removed.
+class_alias(cachestore_addinstance_form::class, \cachestore_addinstance_form::class);
diff --git a/cache/classes/helper.php b/cache/classes/helper.php
index d65b55252fc..8b7faa9b7a6 100644
--- a/cache/classes/helper.php
+++ b/cache/classes/helper.php
@@ -14,19 +14,11 @@
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see .
-/**
- * Cache helper class
- *
- * This file is part of Moodle's cache API, affectionately called MUC.
- * It contains the components that are requried in order to use caching.
- *
- * @package core
- * @category cache
- * @copyright 2012 Sam Hemelryk
- * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
- */
+namespace core_cache;
-defined('MOODLE_INTERNAL') || die();
+use core_cache\administration_helper;
+use core\exception\coding_exception;
+use DirectoryIterator;
/**
* The cache helper class.
@@ -34,23 +26,22 @@ defined('MOODLE_INTERNAL') || die();
* The cache helper class provides common functionality to the cache API and is useful to developers within to interact with
* the cache API in a general way.
*
- * @package core
+ * @package core_cache
* @category cache
* @copyright 2012 Sam Hemelryk
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
-class cache_helper {
-
+class helper {
/**
* Statistics gathered by the cache API during its operation will be used here.
* @static
* @var array
*/
- protected static $stats = array();
+ protected static $stats = [];
/**
* The instance of the cache helper.
- * @var cache_helper
+ * @var self
*/
protected static $instance;
@@ -70,25 +61,25 @@ class cache_helper {
* @return bool
*/
public static function ready_for_early_init() {
- return cache_config::config_file_exists();
+ return config::config_file_exists();
}
/**
- * Returns an instance of the cache_helper.
+ * Returns an instance of the helper.
*
* This is designed for internal use only and acts as a static store.
* @staticvar null $instance
- * @return cache_helper
+ * @return self
*/
protected static function instance() {
if (is_null(self::$instance)) {
- self::$instance = new cache_helper();
+ self::$instance = new self();
}
return self::$instance;
}
/**
- * Constructs an instance of the cache_helper class. Again for internal use only.
+ * Constructs an instance of the helper class. Again for internal use only.
*/
protected function __construct() {
// Nothing to do here, just making sure you can't get an instance of this.
@@ -98,41 +89,41 @@ class cache_helper {
* Used as a data store for initialised definitions.
* @var array
*/
- protected $definitions = array();
+ protected $definitions = [];
/**
* Used as a data store for initialised cache stores
* We use this because we want to avoid establishing multiple instances of a single store.
* @var array
*/
- protected $stores = array();
+ protected $stores = [];
/**
* Returns the class for use as a cache loader for the given mode.
*
- * @param int $mode One of cache_store::MODE_
+ * @param int $mode One of store::MODE_
* @return string
* @throws coding_exception
*/
public static function get_class_for_mode($mode) {
switch ($mode) {
- case cache_store::MODE_APPLICATION :
- return 'cache_application';
- case cache_store::MODE_REQUEST :
- return 'cache_request';
- case cache_store::MODE_SESSION :
- return 'cache_session';
+ case store::MODE_APPLICATION:
+ return application_cache::class;
+ case store::MODE_REQUEST:
+ return request_cache::class;
+ case store::MODE_SESSION:
+ return session_cache::class;
}
- throw new coding_exception('Unknown cache mode passed. Must be one of cache_store::MODE_*');
+ throw new coding_exception('Unknown cache mode passed. Must be one of store::MODE_*');
}
/**
* Returns the cache stores to be used with the given definition.
- * @param cache_definition $definition
+ * @param definition $definition
* @return array
*/
- public static function get_cache_stores(cache_definition $definition) {
- $instance = cache_config::instance();
+ public static function get_cache_stores(definition $definition) {
+ $instance = config::instance();
$stores = $instance->get_stores_for_definition($definition);
$stores = self::initialise_cachestore_instances($stores, $definition);
return $stores;
@@ -142,12 +133,12 @@ class cache_helper {
* Internal function for initialising an array of stores against a given cache definition.
*
* @param array $stores
- * @param cache_definition $definition
- * @return cache_store[]
+ * @param definition $definition
+ * @return store[]
*/
- protected static function initialise_cachestore_instances(array $stores, cache_definition $definition) {
- $return = array();
- $factory = cache_factory::instance();
+ protected static function initialise_cachestore_instances(array $stores, definition $definition) {
+ $return = [];
+ $factory = factory::instance();
foreach ($stores as $name => $details) {
$store = $factory->create_store_from_config($name, $details, $definition);
if ($store !== false) {
@@ -158,15 +149,15 @@ class cache_helper {
}
/**
- * Returns a cache_lock instance suitable for use with the store.
+ * Returns a locakable_cache_interface instance suitable for use with the store.
*
- * @param cache_store $store
- * @return cache_lock_interface
+ * @param store $store
+ * @return lockable_cache_interface
*/
- public static function get_cachelock_for_store(cache_store $store) {
- $instance = cache_config::instance();
+ public static function get_cachelock_for_store(store $store) {
+ $instance = config::instance();
$lockconf = $instance->get_lock_for_store($store->my_name());
- $factory = cache_factory::instance();
+ $factory = factory::instance();
return $factory->create_lock_instance($lockconf);
}
@@ -180,9 +171,9 @@ class cache_helper {
*/
public static function early_get_cache_plugins() {
global $CFG;
- $result = array();
- $ignored = array('CVS', '_vti_cnf', 'simpletest', 'db', 'yui', 'tests');
- $fulldir = $CFG->dirroot.'/cache/stores';
+ $result = [];
+ $ignored = ['CVS', '_vti_cnf', 'simpletest', 'db', 'yui', 'tests'];
+ $fulldir = $CFG->dirroot . '/cache/stores';
$items = new DirectoryIterator($fulldir);
foreach ($items as $item) {
if ($item->isDot() or !$item->isDir()) {
@@ -196,7 +187,7 @@ class cache_helper {
// Better ignore plugins with problematic names here.
continue;
}
- $result[$pluginname] = $fulldir.'/'.$pluginname;
+ $result[$pluginname] = $fulldir . '/' . $pluginname;
unset($item);
}
unset($items);
@@ -215,14 +206,14 @@ class cache_helper {
* @return boolean
* @throws coding_exception
*/
- public static function invalidate_by_definition($component, $area, array $identifiers = array(), $keys = array()) {
+ public static function invalidate_by_definition($component, $area, array $identifiers = [], $keys = []) {
$cache = cache::make($component, $area, $identifiers);
if (is_array($keys)) {
$cache->delete_many($keys);
} else if (is_scalar($keys)) {
$cache->delete($keys);
} else {
- throw new coding_exception('cache_helper::invalidate_by_definition only accepts $keys as array, or scalar.');
+ throw new coding_exception('helper::invalidate_by_definition only accepts $keys as array, or scalar.');
}
return true;
}
@@ -237,17 +228,17 @@ class cache_helper {
* @param array $keys
*/
public static function invalidate_by_event($event, array $keys) {
- $instance = cache_config::instance();
+ $instance = config::instance();
$invalidationeventset = false;
- $factory = cache_factory::instance();
+ $factory = factory::instance();
$inuse = $factory->get_caches_in_use();
$purgetoken = null;
foreach ($instance->get_definitions() as $name => $definitionarr) {
- $definition = cache_definition::load($name, $definitionarr);
+ $definition = definition::load($name, $definitionarr);
if ($definition->invalidates_on_event($event)) {
// First up check if there is a cache loader for this definition already.
// If there is we need to invalidate the keys from there.
- $definitionkey = $definition->get_component().'/'.$definition->get_area();
+ $definitionkey = $definition->get_component() . '/' . $definition->get_area();
if (isset($inuse[$definitionkey])) {
$inuse[$definitionkey]->delete_many($keys);
}
@@ -256,7 +247,7 @@ class cache_helper {
// Request caches shouldn't have events as all data is lost at the end of the request.
// Events should only be logged once of course and likely several definitions are watching so we
// track its logging with $invalidationeventset.
- $logevent = ($invalidationeventset === false && $definition->get_mode() !== cache_store::MODE_REQUEST);
+ $logevent = ($invalidationeventset === false && $definition->get_mode() !== store::MODE_REQUEST);
if ($logevent) {
// Get the event invalidation cache.
@@ -265,7 +256,7 @@ class cache_helper {
$data = $cache->get($event);
if ($data === false) {
// There are none.
- $data = array();
+ $data = [];
}
// Add our keys to them with the current cache timestamp.
if (null === $purgetoken) {
@@ -291,12 +282,12 @@ class cache_helper {
* @param array $identifiers
* @return bool
*/
- public static function purge_by_definition($component, $area, array $identifiers = array()) {
+ public static function purge_by_definition($component, $area, array $identifiers = []) {
// Create the cache.
$cache = cache::make($component, $area, $identifiers);
// Initialise, in case of a store.
- if ($cache instanceof cache_store) {
- $factory = cache_factory::instance();
+ if ($cache instanceof store) {
+ $factory = factory::instance();
$definition = $factory->create_definition($component, $area, null);
$cacheddefinition = clone $definition;
$cacheddefinition->set_identifiers($identifiers);
@@ -316,17 +307,17 @@ class cache_helper {
* @param string $event
*/
public static function purge_by_event($event) {
- $instance = cache_config::instance();
+ $instance = config::instance();
$invalidationeventset = false;
- $factory = cache_factory::instance();
+ $factory = factory::instance();
$inuse = $factory->get_caches_in_use();
$purgetoken = null;
foreach ($instance->get_definitions() as $name => $definitionarr) {
- $definition = cache_definition::load($name, $definitionarr);
+ $definition = definition::load($name, $definitionarr);
if ($definition->invalidates_on_event($event)) {
// First up check if there is a cache loader for this definition already.
// If there is we need to invalidate the keys from there.
- $definitionkey = $definition->get_component().'/'.$definition->get_area();
+ $definitionkey = $definition->get_component() . '/' . $definition->get_area();
if (isset($inuse[$definitionkey])) {
$inuse[$definitionkey]->purge();
} else {
@@ -337,7 +328,7 @@ class cache_helper {
// Request caches shouldn't have events as all data is lost at the end of the request.
// Events should only be logged once of course and likely several definitions are watching so we
// track its logging with $invalidationeventset.
- $logevent = ($invalidationeventset === false && $definition->get_mode() !== cache_store::MODE_REQUEST);
+ $logevent = ($invalidationeventset === false && $definition->get_mode() !== store::MODE_REQUEST);
// We need to flag the event in the "Event invalidation" cache if it hasn't already happened.
if ($logevent && $invalidationeventset === false) {
@@ -347,9 +338,9 @@ class cache_helper {
if (null === $purgetoken) {
$purgetoken = cache::get_purge_token(true);
}
- $data = array(
+ $data = [
'purged' => $purgetoken,
- );
+ ];
// Set that data back to the cache.
$cache->set($event, $data);
// This only needs to occur once.
@@ -364,9 +355,9 @@ class cache_helper {
* @param string $store
* @param string $storeclass
* @param string $definition A string that identifies the definition.
- * @param int $mode One of cache_store::MODE_*. Since 2.9.
+ * @param int $mode One of store::MODE_*. Since 2.9.
*/
- protected static function ensure_ready_for_stats($store, $storeclass, $definition, $mode = cache_store::MODE_APPLICATION) {
+ protected static function ensure_ready_for_stats($store, $storeclass, $definition, $mode = store::MODE_APPLICATION) {
// This function is performance-sensitive, so exit as quickly as possible
// if we do not need to do anything.
if (isset(self::$stats[$definition]['stores'][$store])) {
@@ -374,28 +365,28 @@ class cache_helper {
}
if (!array_key_exists($definition, self::$stats)) {
- self::$stats[$definition] = array(
+ self::$stats[$definition] = [
'mode' => $mode,
- 'stores' => array(
- $store => array(
+ 'stores' => [
+ $store => [
'class' => $storeclass,
'hits' => 0,
'misses' => 0,
'sets' => 0,
- 'iobytes' => cache_store::IO_BYTES_NOT_SUPPORTED,
+ 'iobytes' => store::IO_BYTES_NOT_SUPPORTED,
'locks' => 0,
- )
- )
- );
+ ],
+ ],
+ ];
} else if (!array_key_exists($store, self::$stats[$definition]['stores'])) {
- self::$stats[$definition]['stores'][$store] = array(
+ self::$stats[$definition]['stores'][$store] = [
'class' => $storeclass,
'hits' => 0,
'misses' => 0,
'sets' => 0,
- 'iobytes' => cache_store::IO_BYTES_NOT_SUPPORTED,
+ 'iobytes' => store::IO_BYTES_NOT_SUPPORTED,
'locks' => 0,
- );
+ ];
}
}
@@ -406,47 +397,52 @@ class cache_helper {
* It is backwards compatible when a string is passed but is not accurate.
*
* @since 2.9
- * @param cache_definition|string $definition
+ * @param definition|string $definition
* @return string
*/
protected static function get_definition_stat_id_and_mode($definition) {
- if (!($definition instanceof cache_definition)) {
+ if (!($definition instanceof definition)) {
// All core calls to this method have been updated, this is the legacy state.
// We'll use application as the default as that is the most common, really this is not accurate of course but
// at this point we can only guess and as it only affects calls to cache stat outside of core (of which there should
// be none) I think that is fine.
debugging('Please update you cache stat calls to pass the definition rather than just its ID.', DEBUG_DEVELOPER);
- return array((string)$definition, cache_store::MODE_APPLICATION);
+ return [(string)$definition, store::MODE_APPLICATION];
}
- return array($definition->get_id(), $definition->get_mode());
+ return [$definition->get_id(), $definition->get_mode()];
}
/**
* Record a cache hit in the stats for the given store and definition.
*
* In Moodle 2.9 the $definition argument changed from accepting only a string to accepting a string or a
- * cache_definition instance. It is preferable to pass a cache definition instance.
+ * definition instance. It is preferable to pass a cache definition instance.
*
- * In Moodle 3.9 the first argument changed to also accept a cache_store.
+ * In Moodle 3.9 the first argument changed to also accept a store.
*
* @internal
- * @param string|cache_store $store
- * @param cache_definition $definition You used to be able to pass a string here, however that is deprecated please pass the
- * actual cache_definition object now.
+ * @param string|store $store
+ * @param definition $definition You used to be able to pass a string here, however that is deprecated please pass the
+ * actual definition object now.
* @param int $hits The number of hits to record (by default 1)
- * @param int $readbytes Number of bytes read from the cache or cache_store::IO_BYTES_NOT_SUPPORTED
+ * @param int $readbytes Number of bytes read from the cache or store::IO_BYTES_NOT_SUPPORTED
*/
- public static function record_cache_hit($store, $definition, int $hits = 1, int $readbytes = cache_store::IO_BYTES_NOT_SUPPORTED): void {
+ public static function record_cache_hit(
+ $store,
+ $definition,
+ int $hits = 1,
+ int $readbytes = store::IO_BYTES_NOT_SUPPORTED,
+ ): void {
$storeclass = '';
- if ($store instanceof cache_store) {
+ if ($store instanceof store) {
$storeclass = get_class($store);
$store = $store->my_name();
}
- list($definitionstr, $mode) = self::get_definition_stat_id_and_mode($definition);
+ [$definitionstr, $mode] = self::get_definition_stat_id_and_mode($definition);
self::ensure_ready_for_stats($store, $storeclass, $definitionstr, $mode);
self::$stats[$definitionstr]['stores'][$store]['hits'] += $hits;
- if ($readbytes !== cache_store::IO_BYTES_NOT_SUPPORTED) {
- if (self::$stats[$definitionstr]['stores'][$store]['iobytes'] === cache_store::IO_BYTES_NOT_SUPPORTED) {
+ if ($readbytes !== store::IO_BYTES_NOT_SUPPORTED) {
+ if (self::$stats[$definitionstr]['stores'][$store]['iobytes'] === store::IO_BYTES_NOT_SUPPORTED) {
self::$stats[$definitionstr]['stores'][$store]['iobytes'] = $readbytes;
} else {
self::$stats[$definitionstr]['stores'][$store]['iobytes'] += $readbytes;
@@ -458,23 +454,23 @@ class cache_helper {
* Record a cache miss in the stats for the given store and definition.
*
* In Moodle 2.9 the $definition argument changed from accepting only a string to accepting a string or a
- * cache_definition instance. It is preferable to pass a cache definition instance.
+ * definition instance. It is preferable to pass a cache definition instance.
*
- * In Moodle 3.9 the first argument changed to also accept a cache_store.
+ * In Moodle 3.9 the first argument changed to also accept a store.
*
* @internal
- * @param string|cache_store $store
- * @param cache_definition $definition You used to be able to pass a string here, however that is deprecated please pass the
- * actual cache_definition object now.
+ * @param string|store $store
+ * @param definition $definition You used to be able to pass a string here, however that is deprecated please pass the
+ * actual definition object now.
* @param int $misses The number of misses to record (by default 1)
*/
public static function record_cache_miss($store, $definition, $misses = 1) {
$storeclass = '';
- if ($store instanceof cache_store) {
+ if ($store instanceof store) {
$storeclass = get_class($store);
$store = $store->my_name();
}
- list($definitionstr, $mode) = self::get_definition_stat_id_and_mode($definition);
+ [$definitionstr, $mode] = self::get_definition_stat_id_and_mode($definition);
self::ensure_ready_for_stats($store, $storeclass, $definitionstr, $mode);
self::$stats[$definitionstr]['stores'][$store]['misses'] += $misses;
}
@@ -483,29 +479,33 @@ class cache_helper {
* Record a cache set in the stats for the given store and definition.
*
* In Moodle 2.9 the $definition argument changed from accepting only a string to accepting a string or a
- * cache_definition instance. It is preferable to pass a cache definition instance.
+ * definition instance. It is preferable to pass a cache definition instance.
*
- * In Moodle 3.9 the first argument changed to also accept a cache_store.
+ * In Moodle 3.9 the first argument changed to also accept a store.
*
* @internal
- * @param string|cache_store $store
- * @param cache_definition $definition You used to be able to pass a string here, however that is deprecated please pass the
- * actual cache_definition object now.
+ * @param string|store $store
+ * @param definition $definition You used to be able to pass a string here, however that is deprecated please pass the
+ * actual definition object now.
* @param int $sets The number of sets to record (by default 1)
- * @param int $writebytes Number of bytes written to the cache or cache_store::IO_BYTES_NOT_SUPPORTED
+ * @param int $writebytes Number of bytes written to the cache or store::IO_BYTES_NOT_SUPPORTED
*/
- public static function record_cache_set($store, $definition, int $sets = 1,
- int $writebytes = cache_store::IO_BYTES_NOT_SUPPORTED) {
+ public static function record_cache_set(
+ $store,
+ $definition,
+ int $sets = 1,
+ int $writebytes = store::IO_BYTES_NOT_SUPPORTED
+ ) {
$storeclass = '';
- if ($store instanceof cache_store) {
+ if ($store instanceof store) {
$storeclass = get_class($store);
$store = $store->my_name();
}
- list($definitionstr, $mode) = self::get_definition_stat_id_and_mode($definition);
+ [$definitionstr, $mode] = self::get_definition_stat_id_and_mode($definition);
self::ensure_ready_for_stats($store, $storeclass, $definitionstr, $mode);
self::$stats[$definitionstr]['stores'][$store]['sets'] += $sets;
- if ($writebytes !== cache_store::IO_BYTES_NOT_SUPPORTED) {
- if (self::$stats[$definitionstr]['stores'][$store]['iobytes'] === cache_store::IO_BYTES_NOT_SUPPORTED) {
+ if ($writebytes !== store::IO_BYTES_NOT_SUPPORTED) {
+ if (self::$stats[$definitionstr]['stores'][$store]['iobytes'] === store::IO_BYTES_NOT_SUPPORTED) {
self::$stats[$definitionstr]['stores'][$store]['iobytes'] = $writebytes;
} else {
self::$stats[$definitionstr]['stores'][$store]['iobytes'] += $writebytes;
@@ -528,13 +528,13 @@ class cache_helper {
* anything. This will involve full setup of the cache + the purge operation. On a site using caching heavily this WILL be
* painful.
*
- * @param bool $usewriter If set to true the cache_config_writer class is used. This class is special as it avoids
+ * @param bool $usewriter If set to true the config_writer class is used. This class is special as it avoids
* it is still usable when caches have been disabled.
* Please use this option only if you really must. It's purpose is to allow the cache to be purged when it would be
* otherwise impossible.
*/
public static function purge_all($usewriter = false) {
- $factory = cache_factory::instance();
+ $factory = factory::instance();
$config = $factory->create_config_instance($usewriter);
foreach ($config->get_all_stores() as $store) {
self::purge_store($store['name'], $config);
@@ -548,12 +548,12 @@ class cache_helper {
* Purges a store given its name.
*
* @param string $storename
- * @param cache_config $config
+ * @param config|null $config
* @return bool
*/
- public static function purge_store($storename, ?cache_config $config = null) {
+ public static function purge_store($storename, ?config $config = null) {
if ($config === null) {
- $config = cache_config::instance();
+ $config = config::instance();
}
$stores = $config->get_all_stores();
@@ -571,14 +571,14 @@ class cache_helper {
return false;
}
// Found the store: is it ready?
- /* @var cache_store $instance */
+ /* @var store $instance */
$instance = new $class($store['name'], $store['configuration']);
if (!$instance->is_ready()) {
unset($instance);
return false;
}
foreach ($config->get_definitions_by_store($storename) as $id => $definition) {
- $definition = cache_definition::load($id, $definition);
+ $definition = definition::load($id, $definition);
$definitioninstance = clone($instance);
$definitioninstance->initialise($definition);
$definitioninstance->purge();
@@ -591,7 +591,7 @@ class cache_helper {
/**
* Purges all of the stores used by a definition.
*
- * Unlike cache_helper::purge_by_definition this purges all of the data from the stores not
+ * Unlike helper::purge_by_definition this purges all of the data from the stores not
* just the data relating to the definition.
* This function is useful when you must purge a definition that requires setup but you don't
* want to set it up.
@@ -600,7 +600,7 @@ class cache_helper {
* @param string $area
*/
public static function purge_stores_used_by_definition($component, $area) {
- $factory = cache_factory::instance();
+ $factory = factory::instance();
$config = $factory->create_config_instance();
$definition = $factory->create_definition($component, $area);
$stores = $config->get_stores_for_definition($definition);
@@ -612,14 +612,14 @@ class cache_helper {
/**
* Returns the translated name of the definition.
*
- * @param cache_definition $definition
+ * @param definition $definition
* @return lang_string
*/
public static function get_definition_name($definition) {
- if ($definition instanceof cache_definition) {
+ if ($definition instanceof definition) {
return $definition->get_name();
}
- $identifier = 'cachedef_'.clean_param($definition['area'], PARAM_STRINGID);
+ $identifier = 'cachedef_' . clean_param($definition['area'], PARAM_STRINGID);
$component = $definition['component'];
if ($component === 'core') {
$component = 'cache';
@@ -630,13 +630,16 @@ class cache_helper {
/**
* Hashes a descriptive key to make it shorter and still unique.
* @param string|int $key
- * @param cache_definition $definition
+ * @param definition $definition
* @return string
*/
- public static function hash_key($key, cache_definition $definition) {
+ public static function hash_key($key, definition $definition) {
if ($definition->uses_simple_keys()) {
if (debugging() && preg_match('#[^a-zA-Z0-9_]#', $key ?? '')) {
- throw new coding_exception('Cache definition '.$definition->get_id().' requires simple keys. Invalid key provided.', $key);
+ throw new coding_exception(
+ 'Cache definition ' . $definition->get_id() . ' requires simple keys. Invalid key provided.',
+ $key,
+ );
}
// We put the key first so that we can be sure the start of the key changes.
return (string)$key . '-' . $definition->generate_single_key_prefix();
@@ -651,13 +654,10 @@ class cache_helper {
* @param bool $coreonly If set to true only core definitions will be updated.
*/
public static function update_definitions($coreonly = false) {
- global $CFG;
- // Include locallib.
- require_once($CFG->dirroot.'/cache/locallib.php');
// First update definitions
- cache_config_writer::update_definitions($coreonly);
+ config_writer::update_definitions($coreonly);
// Second reset anything we have already initialised to ensure we're all up to date.
- cache_factory::reset();
+ factory::reset();
}
/**
@@ -667,15 +667,12 @@ class cache_helper {
* @return string The new site identifier.
*/
public static function update_site_identifier($siteidentifier) {
- global $CFG;
- // Include locallib.
- require_once($CFG->dirroot.'/cache/locallib.php');
- $factory = cache_factory::instance();
+ $factory = factory::instance();
$factory->updating_started();
$config = $factory->create_config_instance(true);
$siteidentifier = $config->update_site_identifier($siteidentifier);
$factory->updating_finished();
- cache_factory::reset();
+ factory::reset();
return $siteidentifier;
}
@@ -690,7 +687,7 @@ class cache_helper {
return self::$siteidentifier;
}
// If site identifier hasn't been collected yet attempt to get it from the cache config.
- $factory = cache_factory::instance();
+ $factory = factory::instance();
// If the factory is initialising then we don't want to try to get it from the config or we risk
// causing the cache to enter an infinite initialisation loop.
if (!$factory->is_initialising()) {
@@ -739,13 +736,13 @@ class cache_helper {
if ($output) {
mtrace('Cleaning up stale session data from cache stores.');
}
- $factory = cache_factory::instance();
+ $factory = factory::instance();
$config = $factory->create_config_instance();
$definitions = $config->get_definitions();
$purgetime = time() - $CFG->sessiontimeout;
foreach ($definitions as $definitionarray) {
// We are only interested in session caches.
- if (!($definitionarray['mode'] & cache_store::MODE_SESSION)) {
+ if (!($definitionarray['mode'] & store::MODE_SESSION)) {
continue;
}
$definition = $factory->create_definition($definitionarray['component'], $definitionarray['area']);
@@ -755,18 +752,18 @@ class cache_helper {
// Initialise all of the stores used for that definition.
foreach ($stores as $store) {
// If the store doesn't support searching we can skip it.
- if (!($store instanceof cache_is_searchable)) {
+ if (!($store instanceof searchable_cache_interface)) {
debugging('Cache stores used for session definitions should ideally be searchable.', DEBUG_DEVELOPER);
continue;
}
// Get all of the last access keys.
- $keys = $store->find_by_prefix(cache_session::LASTACCESS);
+ $keys = $store->find_by_prefix(session_cache::LASTACCESS);
$todelete = [];
foreach ($store->get_many($keys) as $key => $value) {
$expiresvalue = 0;
if ($value instanceof cache_ttl_wrapper) {
$expiresvalue = $value->data;
- } else if ($value instanceof cache_cached_object) {
+ } else if ($value instanceof cached_object) {
$expiresvalue = $value->restore_object();
} else {
$expiresvalue = $value;
@@ -774,13 +771,13 @@ class cache_helper {
$expires = (int) $expiresvalue;
if ($expires > 0 && $expires < $purgetime) {
- $prefix = substr($key, strlen(cache_session::LASTACCESS));
+ $prefix = substr($key, strlen(session_cache::LASTACCESS));
$foundbyprefix = $store->find_by_prefix($prefix);
$todelete = array_merge($todelete, [$key], $foundbyprefix);
}
}
if ($todelete) {
- $outcome = (int)$store->delete_many($todelete);
+ $outcome = (int) store->delete_many($todelete);
if ($output) {
$strdef = s($definition->get_id());
$strstore = s($store->my_name());
@@ -799,14 +796,14 @@ class cache_helper {
* @return array[] An array of stores, keys are the store names.
*/
public static function get_stores_suitable_for_mode_default() {
- $factory = cache_factory::instance();
+ $factory = factory::instance();
$config = $factory->create_config_instance();
$requirements = 0;
foreach ($config->get_definitions() as $definition) {
- $definition = cache_definition::load($definition['component'].'/'.$definition['area'], $definition);
+ $definition = definition::load($definition['component'] . '/' . $definition['area'], $definition);
$requirements = $requirements | $definition->get_requirements_bin();
}
- $stores = array();
+ $stores = [];
foreach ($config->get_all_stores() as $name => $store) {
if (!empty($store['features']) && ($store['features'] & $requirements)) {
$stores[$name] = $store;
@@ -818,12 +815,12 @@ class cache_helper {
/**
* Returns stores suitable for use with a given definition.
*
- * @param cache_definition $definition
- * @return cache_store[]
+ * @param definition $definition
+ * @return store[]
*/
- public static function get_stores_suitable_for_definition(cache_definition $definition) {
- $factory = cache_factory::instance();
- $stores = array();
+ public static function get_stores_suitable_for_definition(definition $definition) {
+ $factory = factory::instance();
+ $stores = [];
if ($factory->is_initialising() || $factory->stores_disabled()) {
// No suitable stores here.
return $stores;
@@ -857,12 +854,10 @@ class cache_helper {
* @return string[]
*/
public static function warnings(?array $stores = null) {
- global $CFG;
if ($stores === null) {
- require_once($CFG->dirroot.'/cache/locallib.php');
- $stores = core_cache\administration_helper::get_store_instance_summaries();
+ $stores = administration_helper::get_store_instance_summaries();
}
- $warnings = array();
+ $warnings = [];
foreach ($stores as $store) {
if (!empty($store['warnings'])) {
$warnings = array_merge($warnings, $store['warnings']);
@@ -892,3 +887,8 @@ class cache_helper {
return class_exists('RedisCluster');
}
}
+
+// Alias this class to the old name.
+// This file will be autoloaded by the legacyclasses autoload system.
+// In future all uses of this class will be corrected and the legacy references will be removed.
+class_alias(helper::class, \cache_helper::class);
diff --git a/cache/classes/interfaces.php b/cache/classes/interfaces.php
deleted file mode 100644
index e0dff287f64..00000000000
--- a/cache/classes/interfaces.php
+++ /dev/null
@@ -1,605 +0,0 @@
-.
-
-/**
- * Cache API interfaces
- *
- * This file is part of Moodle's cache API, affectionately called MUC.
- * It contains the components that are requried in order to use caching.
- *
- * @package core
- * @category cache
- * @copyright 2012 Sam Hemelryk
- * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
- */
-
-defined('MOODLE_INTERNAL') || die();
-
-/**
- * Cache Loader.
- *
- * This cache loader interface provides the required structure for classes that wish to be interacted with as a
- * means of accessing and interacting with a cache.
- *
- * Can be implemented by any class wishing to be a cache loader.
- */
-interface cache_loader {
-
- /**
- * Retrieves the value for the given key from the cache.
- *
- * @param string|int $key The key for the data being requested.
- * @param int $strictness One of IGNORE_MISSING or MUST_EXIST.
- * @return mixed The data retrieved from the cache, or false if the key did not exist within the cache.
- * If MUST_EXIST was used then an exception will be thrown if the key does not exist within the cache.
- */
- public function get($key, $strictness = IGNORE_MISSING);
-
- /**
- * Retrieves the value and actual version for the given key, with at least the required version.
- *
- * If there is no value for the key, or there is a value but it doesn't have the required
- * version, then this function will return false (or throw an exception if you set strictness
- * to MUST_EXIST).
- *
- * This function can be used to make it easier to support localisable caches (where the cache
- * could be stored on a local server as well as a shared cache). Specifying the version means
- * that it will automatically retrieve the correct version if available, either from the local
- * server or [if that has an older version] from the shared server.
- *
- * If the cached version is newer than specified version, it will be returned regardless. For
- * example, if you request version 4, but the locally cached version is 5, it will be returned.
- * If you request version 6, and the locally cached version is 5, then the system will look in
- * higher-level caches (if any); if there still isn't a version 6 or greater, it will return
- * null.
- *
- * You must use this function if you use set_versioned.
- *
- * @param string|int $key The key for the data being requested.
- * @param int $requiredversion Minimum required version of the data
- * @param int $strictness One of IGNORE_MISSING or MUST_EXIST.
- * @param mixed $actualversion If specified, will be set to the actual version number retrieved
- * @return mixed Data from the cache, or false if the key did not exist or was too old
- */
- public function get_versioned($key, int $requiredversion, int $strictness = IGNORE_MISSING, &$actualversion = null);
-
- /**
- * Retrieves an array of values for an array of keys.
- *
- * Using this function comes with potential performance implications.
- * Not all cache stores will support get_many/set_many operations and in order to replicate this functionality will call
- * the equivalent singular method for each item provided.
- * This should not deter you from using this function as there is a performance benefit in situations where the cache
- * store does support it, but you should be aware of this fact.
- *
- * @param array $keys The keys of the data being requested.
- * @param int $strictness One of IGNORE_MISSING or MUST_EXIST.
- * @return array An array of key value pairs for the items that could be retrieved from the cache.
- * If MUST_EXIST was used and not all keys existed within the cache then an exception will be thrown.
- * Otherwise any key that did not exist will have a data value of false within the results.
- */
- public function get_many(array $keys, $strictness = IGNORE_MISSING);
-
- /**
- * Sends a key => value pair to the cache.
- *
- *
- * // This code will add four entries to the cache, one for each url.
- * $cache->set('main', 'http://moodle.org');
- * $cache->set('docs', 'http://docs.moodle.org');
- * $cache->set('tracker', 'http://tracker.moodle.org');
- * $cache->set('qa', 'http://qa.moodle.net');
- *
- *
- * @param string|int $key The key for the data being requested.
- * @param mixed $data The data to set against the key.
- * @return bool True on success, false otherwise.
- */
- public function set($key, $data);
-
- /**
- * Sets the value for the given key with the given version.
- *
- * The cache does not store multiple versions - any existing version will be overwritten with
- * this one. This function should only be used if there is a known 'current version' (e.g.
- * stored in a database table). It only ensures that the cache does not return outdated data.
- *
- * This function can be used to help implement localisable caches (where the cache could be
- * stored on a local server as well as a shared cache). The version will be recorded alongside
- * the item and get_versioned will always return the correct version.
- *
- * The version number must be an integer that always increases. This could be based on the
- * current time, or a stored value that increases by 1 each time it changes, etc.
- *
- * If you use this function you must use get_versioned to retrieve the data.
- *
- * @param string|int $key The key for the data being set.
- * @param int $version Integer for the version of the data
- * @param mixed $data The data to set against the key.
- * @return bool True on success, false otherwise.
- */
- public function set_versioned($key, int $version, $data): bool;
-
- /**
- * Sends several key => value pairs to the cache.
- *
- * Using this function comes with potential performance implications.
- * Not all cache stores will support get_many/set_many operations and in order to replicate this functionality will call
- * the equivalent singular method for each item provided.
- * This should not deter you from using this function as there is a performance benefit in situations where the cache store
- * does support it, but you should be aware of this fact.
- *
- *
- * // This code will add four entries to the cache, one for each url.
- * $cache->set_many(array(
- * 'main' => 'http://moodle.org',
- * 'docs' => 'http://docs.moodle.org',
- * 'tracker' => 'http://tracker.moodle.org',
- * 'qa' => ''http://qa.moodle.net'
- * ));
- *
- *
- * @param array $keyvaluearray An array of key => value pairs to send to the cache.
- * @return int The number of items successfully set. It is up to the developer to check this matches the number of items.
- * ... if they care that is.
- */
- public function set_many(array $keyvaluearray);
-
- /**
- * Test is a cache has a key.
- *
- * The use of the has methods is strongly discouraged. In a high load environment the cache may well change between the
- * test and any subsequent action (get, set, delete etc).
- * Instead it is recommended to write your code in such a way they it performs the following steps:
- *
- * - Attempt to retrieve the information.
- * - Generate the information.
- * - Attempt to set the information
- *
- *
- * Its also worth mentioning that not all stores support key tests.
- * For stores that don't support key tests this functionality is mimicked by using the equivalent get method.
- * Just one more reason you should not use these methods unless you have a very good reason to do so.
- *
- * @param string|int $key
- * @return bool True if the cache has the requested key, false otherwise.
- */
- public function has($key);
-
- /**
- * Test if a cache has at least one of the given keys.
- *
- * It is strongly recommended to avoid the use of this function if not absolutely required.
- * In a high load environment the cache may well change between the test and any subsequent action (get, set, delete etc).
- *
- * Its also worth mentioning that not all stores support key tests.
- * For stores that don't support key tests this functionality is mimicked by using the equivalent get method.
- * Just one more reason you should not use these methods unless you have a very good reason to do so.
- *
- * @param array $keys
- * @return bool True if the cache has at least one of the given keys
- */
- public function has_any(array $keys);
-
- /**
- * Test is a cache has all of the given keys.
- *
- * It is strongly recommended to avoid the use of this function if not absolutely required.
- * In a high load environment the cache may well change between the test and any subsequent action (get, set, delete etc).
- *
- * Its also worth mentioning that not all stores support key tests.
- * For stores that don't support key tests this functionality is mimicked by using the equivalent get method.
- * Just one more reason you should not use these methods unless you have a very good reason to do so.
- *
- * @param array $keys
- * @return bool True if the cache has all of the given keys, false otherwise.
- */
- public function has_all(array $keys);
-
- /**
- * Delete the given key from the cache.
- *
- * @param string|int $key The key to delete.
- * @param bool $recurse When set to true the key will also be deleted from all stacked cache loaders and their stores.
- * This happens by default and ensure that all the caches are consistent. It is NOT recommended to change this.
- * @return bool True of success, false otherwise.
- */
- public function delete($key, $recurse = true);
-
- /**
- * Delete all of the given keys from the cache.
- *
- * @param array $keys The key to delete.
- * @param bool $recurse When set to true the key will also be deleted from all stacked cache loaders and their stores.
- * This happens by default and ensure that all the caches are consistent. It is NOT recommended to change this.
- * @return int The number of items successfully deleted.
- */
- public function delete_many(array $keys, $recurse = true);
-}
-
-/**
- * Cache Loader supporting locking.
- *
- * This interface should be given to classes already implementing cache_loader that also wish to support locking.
- * It outlines the required structure for utilising locking functionality when using a cache.
- *
- * Can be implemented by any class already implementing the cache_loader interface.
- */
-interface cache_loader_with_locking {
-
- /**
- * Acquires a lock for the given key.
- *
- * Please note that this happens automatically if the cache definition requires locking.
- * it is still made a public method so that adhoc caches can use it if they choose.
- * However this doesn't guarantee consistent access. It will become the responsibility of the calling code to ensure
- * locks are acquired, checked, and released.
- *
- * Prior to Moodle 4,3 this function used to return false if the lock cannot be obtained. It
- * now always returns true, and throws an exception if the lock cannot be obtained.
- *
- * @param string|int $key
- * @return bool Always returns true (for backwards compatibility)
- * @throws moodle_exception If the lock cannot be obtained after a timeout
- */
- public function acquire_lock($key);
-
- /**
- * Checks if the cache loader owns the lock for the given key.
- *
- * Please note that this happens automatically if the cache definition requires locking.
- * it is still made a public method so that adhoc caches can use it if they choose.
- * However this doesn't guarantee consistent access. It will become the responsibility of the calling code to ensure
- * locks are acquired, checked, and released.
- *
- * @param string|int $key
- * @return bool True if this code has the lock, false if there is a lock but this code doesn't have it,
- * null if there is no lock.
- */
- public function check_lock_state($key);
-
- /**
- * Releases the lock for the given key.
- *
- * Please note that this happens automatically if the cache definition requires locking.
- * it is still made a public method so that adhoc caches can use it if they choose.
- * However this doesn't guarantee consistent access. It will become the responsibility of the calling code to ensure
- * locks are acquired, checked, and released.
- *
- * @param string|int $key
- * @return bool True if the lock has been released, false if there was a problem releasing the lock.
- */
- public function release_lock($key);
-}
-
-/**
- * Cache store feature: locking
- *
- * This is a feature that cache stores can implement if they wish to support locking themselves rather
- * than having the cache loader handle it for them.
- *
- * Can be implemented by classes already implementing cache_store.
- */
-interface cache_is_lockable {
-
- /**
- * Acquires a lock on the given key for the given identifier.
- *
- * @param string $key The key we are locking.
- * @param string $ownerid The identifier so we can check if we have the lock or if it is someone else.
- * The use of this property is entirely optional and implementations can act as they like upon it.
- * @return bool True if the lock could be acquired, false otherwise.
- */
- public function acquire_lock($key, $ownerid);
-
- /**
- * Test if there is already a lock for the given key and if there is whether it belongs to the calling code.
- *
- * @param string $key The key we are locking.
- * @param string $ownerid The identifier so we can check if we have the lock or if it is someone else.
- * @return bool True if this code has the lock, false if there is a lock but this code doesn't have it, null if there
- * is no lock.
- */
- public function check_lock_state($key, $ownerid);
-
- /**
- * Releases the lock on the given key.
- *
- * @param string $key The key we are locking.
- * @param string $ownerid The identifier so we can check if we have the lock or if it is someone else.
- * The use of this property is entirely optional and implementations can act as they like upon it.
- * @return bool True if the lock has been released, false if there was a problem releasing the lock.
- */
- public function release_lock($key, $ownerid);
-}
-
-/**
- * Cache store feature: key awareness.
- *
- * This is a feature that cache stores and cache loaders can both choose to implement.
- * If a cache store implements this then it will be made responsible for tests for items within the cache.
- * If the cache store being used doesn't implement this then it will be the responsibility of the cache loader to use the
- * equivalent get methods to mimick the functionality of these tests.
- *
- * Cache stores should only override these methods if they natively support such features or if they have a better performing
- * means of performing these tests than the handling that would otherwise take place in the cache_loader.
- *
- * Can be implemented by classes already implementing cache_store.
- */
-interface cache_is_key_aware {
-
- /**
- * Test is a cache has a key.
- *
- * The use of the has methods is strongly discouraged. In a high load environment the cache may well change between the
- * test and any subsequent action (get, set, delete etc).
- * Instead it is recommended to write your code in such a way they it performs the following steps:
- *
- * - Attempt to retrieve the information.
- * - Generate the information.
- * - Attempt to set the information
- *
- *
- * Its also worth mentioning that not all stores support key tests.
- * For stores that don't support key tests this functionality is mimicked by using the equivalent get method.
- * Just one more reason you should not use these methods unless you have a very good reason to do so.
- *
- * @param string|int $key
- * @return bool True if the cache has the requested key, false otherwise.
- */
- public function has($key);
-
- /**
- * Test if a cache has at least one of the given keys.
- *
- * It is strongly recommended to avoid the use of this function if not absolutely required.
- * In a high load environment the cache may well change between the test and any subsequent action (get, set, delete etc).
- *
- * Its also worth mentioning that not all stores support key tests.
- * For stores that don't support key tests this functionality is mimicked by using the equivalent get method.
- * Just one more reason you should not use these methods unless you have a very good reason to do so.
- *
- * @param array $keys
- * @return bool True if the cache has at least one of the given keys
- */
- public function has_any(array $keys);
-
- /**
- * Test is a cache has all of the given keys.
- *
- * It is strongly recommended to avoid the use of this function if not absolutely required.
- * In a high load environment the cache may well change between the test and any subsequent action (get, set, delete etc).
- *
- * Its also worth mentioning that not all stores support key tests.
- * For stores that don't support key tests this functionality is mimicked by using the equivalent get method.
- * Just one more reason you should not use these methods unless you have a very good reason to do so.
- *
- * @param array $keys
- * @return bool True if the cache has all of the given keys, false otherwise.
- */
- public function has_all(array $keys);
-}
-
-/**
- * Cache store feature: keys are searchable.
- *
- * Cache stores can choose to implement this interface.
- * In order for a store to be usable as a session cache it must implement this interface.
- *
- * @since Moodle 2.4.4
- */
-interface cache_is_searchable {
- /**
- * Finds all of the keys being used by the cache store.
- *
- * @return array.
- */
- public function find_all();
-
- /**
- * Finds all of the keys whose keys start with the given prefix.
- *
- * @param string $prefix
- */
- public function find_by_prefix($prefix);
-}
-
-/**
- * Cache store feature: configurable.
- *
- * This feature should be implemented by all cache stores that are configurable when adding an instance.
- * It requires the implementation of methods required to convert form data into the a configuration array for the
- * store instance, and then the reverse converting configuration data into an array that can be used to set the
- * data for the edit form.
- *
- * Can be implemented by classes already implementing cache_store.
- */
-interface cache_is_configurable {
-
- /**
- * Given the data from the add instance form this function creates a configuration array.
- *
- * @param stdClass $data
- * @return array
- */
- public static function config_get_configuration_array($data);
-
- /**
- * Allows the cache store to set its data against the edit form before it is shown to the user.
- *
- * @param moodleform $editform
- * @param array $config
- */
- public static function config_set_edit_form_data(moodleform $editform, array $config);
-}
-
-/**
- * Cache Data Source.
- *
- * The cache data source interface can be implemented by any class within Moodle.
- * If implemented then the class can be reference in a cache definition and will be used to load information that cannot be
- * retrieved from the cache. As part of its retrieval that information will also be loaded into the cache.
- *
- * This allows developers to created a complete cache solution that can be used through code ensuring consistent cache
- * interaction and loading. Allowing them in turn to centralise code and help keeps things more easily maintainable.
- *
- * Can be implemented by any class.
- *
- * @package core
- * @category cache
- * @copyright 2012 Sam Hemelryk
- * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
- */
-interface cache_data_source {
-
- /**
- * Returns an instance of the data source class that the cache can use for loading data using the other methods
- * specified by this interface.
- *
- * @param cache_definition $definition
- * @return object
- */
- public static function get_instance_for_cache(cache_definition $definition);
-
- /**
- * Loads the data for the key provided ready formatted for caching.
- *
- * @param string|int $key The key to load.
- * @return mixed What ever data should be returned, or false if it can't be loaded.
- */
- public function load_for_cache($key);
-
- /**
- * Loads several keys for the cache.
- *
- * @param array $keys An array of keys each of which will be string|int.
- * @return array An array of matching data items.
- */
- public function load_many_for_cache(array $keys);
-}
-
-/**
- * Versionable cache data source.
- *
- * This interface extends the main cache data source interface to add an extra required method if
- * the data source is to be used for a versioned cache.
- *
- * @package core_cache
- */
-interface cache_data_source_versionable extends cache_data_source {
- /**
- * Loads the data for the key provided ready formatted for caching.
- *
- * If there is no data for that key, or if the data for the required key has an older version
- * than the specified $requiredversion, then this returns null.
- *
- * If there is data then $actualversion should be set to the actual version number retrieved
- * (may be the same as $requiredversion or newer).
- *
- * @param string|int $key The key to load.
- * @param int $requiredversion Minimum required version
- * @param mixed $actualversion Should be set to the actual version number retrieved
- * @return mixed What ever data should be returned, or false if it can't be loaded.
- */
- public function load_for_cache_versioned($key, int $requiredversion, &$actualversion);
-}
-
-/**
- * Cacheable object.
- *
- * This interface can be implemented by any class that is going to be passed into a cache and allows it to take control of the
- * structure and the information about to be cached, as well as how to deal with it when it is retrieved from a cache.
- * Think of it like serialisation and the __sleep and __wakeup methods.
- * This is used because cache stores are responsible for how they interact with data and what they do when storing it. This
- * interface ensures there is always a guaranteed action.
- */
-interface cacheable_object {
-
- /**
- * Prepares the object for caching. Works like the __sleep method.
- *
- * @return mixed The data to cache, can be anything except a class that implements the cacheable_object... that would
- * be dumb.
- */
- public function prepare_to_cache();
-
- /**
- * Takes the data provided by prepare_to_cache and reinitialises an instance of the associated from it.
- *
- * @param mixed $data
- * @return object The instance for the given data.
- */
- public static function wake_from_cache($data);
-}
-
-/**
- * Cache lock interface
- *
- * This interface needs to be inherited by all cache lock plugins.
- */
-interface cache_lock_interface {
- /**
- * Constructs an instance of the cache lock given its name and its configuration data
- *
- * @param string $name The unique name of the lock instance
- * @param array $configuration
- */
- public function __construct($name, array $configuration = array());
-
- /**
- * Acquires a lock on a given key.
- *
- * @param string $key The key to acquire a lock for.
- * @param string $ownerid An unique identifier for the owner of this lock. It is entirely optional for the cache lock plugin
- * to use this. Each implementation can decide for themselves.
- * @param bool $block If set to true the application will wait until a lock can be acquired
- * @return bool True if the lock can be acquired false otherwise.
- */
- public function lock($key, $ownerid, $block = false);
-
- /**
- * Releases the lock held on a certain key.
- *
- * @param string $key The key to release the lock for.
- * @param string $ownerid An unique identifier for the owner of this lock. It is entirely optional for the cache lock plugin
- * to use this. Each implementation can decide for themselves.
- * @param bool $forceunlock If set to true the lock will be removed if it exists regardless of whether or not we own it.
- */
- public function unlock($key, $ownerid, $forceunlock = false);
-
- /**
- * Checks the state of the given key.
- *
- * Returns true if the key is locked and belongs to the ownerid.
- * Returns false if the key is locked but does not belong to the ownerid.
- * Returns null if there is no lock
- *
- * @param string $key The key we are checking for.
- * @param string $ownerid The identifier so we can check if we have the lock or if it is someone else.
- * @return bool True if this code has the lock, false if there is a lock but this code doesn't have it, null if there
- * is no lock.
- */
- public function check_state($key, $ownerid);
-
- /**
- * Cleans up any left over locks.
- *
- * This function MUST clean up any locks that have been acquired and not released during processing.
- * Although the situation of acquiring a lock and not releasing it should be insanely rare we need to deal with it.
- * Things such as unfortunate timeouts etc could cause this situation.
- */
- public function __destruct();
-}
diff --git a/cache/classes/key_aware_cache_interface.php b/cache/classes/key_aware_cache_interface.php
new file mode 100644
index 00000000000..4390ae20c6e
--- /dev/null
+++ b/cache/classes/key_aware_cache_interface.php
@@ -0,0 +1,92 @@
+.
+
+namespace core_cache;
+
+/**
+ * Cache store feature: key awareness.
+ *
+ * This is a feature that cache stores and cache loaders can both choose to implement.
+ * If a cache store implements this then it will be made responsible for tests for items within the cache.
+ * If the cache store being used doesn't implement this then it will be the responsibility of the cache loader to use the
+ * equivalent get methods to mimick the functionality of these tests.
+ *
+ * Cache stores should only override these methods if they natively support such features or if they have a better performing
+ * means of performing these tests than the handling that would otherwise take place in the cache_loader.
+ *
+ * Can be implemented by classes already implementing cache_store.
+ *
+ * @package core_cache
+ * @copyright Sam Hemelryk
+ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+interface key_aware_cache_interface {
+ /**
+ * Test is a cache has a key.
+ *
+ * The use of the has methods is strongly discouraged. In a high load environment the cache may well change between the
+ * test and any subsequent action (get, set, delete etc).
+ * Instead it is recommended to write your code in such a way they it performs the following steps:
+ *
+ * - Attempt to retrieve the information.
+ * - Generate the information.
+ * - Attempt to set the information
+ *
+ *
+ * Its also worth mentioning that not all stores support key tests.
+ * For stores that don't support key tests this functionality is mimicked by using the equivalent get method.
+ * Just one more reason you should not use these methods unless you have a very good reason to do so.
+ *
+ * @param string|int $key
+ * @return bool True if the cache has the requested key, false otherwise.
+ */
+ public function has($key);
+
+ /**
+ * Test if a cache has at least one of the given keys.
+ *
+ * It is strongly recommended to avoid the use of this function if not absolutely required.
+ * In a high load environment the cache may well change between the test and any subsequent action (get, set, delete etc).
+ *
+ * Its also worth mentioning that not all stores support key tests.
+ * For stores that don't support key tests this functionality is mimicked by using the equivalent get method.
+ * Just one more reason you should not use these methods unless you have a very good reason to do so.
+ *
+ * @param array $keys
+ * @return bool True if the cache has at least one of the given keys
+ */
+ public function has_any(array $keys);
+
+ /**
+ * Test is a cache has all of the given keys.
+ *
+ * It is strongly recommended to avoid the use of this function if not absolutely required.
+ * In a high load environment the cache may well change between the test and any subsequent action (get, set, delete etc).
+ *
+ * Its also worth mentioning that not all stores support key tests.
+ * For stores that don't support key tests this functionality is mimicked by using the equivalent get method.
+ * Just one more reason you should not use these methods unless you have a very good reason to do so.
+ *
+ * @param array $keys
+ * @return bool True if the cache has all of the given keys, false otherwise.
+ */
+ public function has_all(array $keys);
+}
+
+// Alias this class to the old name.
+// This file will be autoloaded by the legacyclasses autoload system.
+// In future all uses of this class will be corrected and the legacy references will be removed.
+class_alias(key_aware_cache_interface::class, \cache_is_key_aware::class);
diff --git a/cache/classes/loader_interface.php b/cache/classes/loader_interface.php
new file mode 100644
index 00000000000..880ac4341a2
--- /dev/null
+++ b/cache/classes/loader_interface.php
@@ -0,0 +1,226 @@
+.
+
+namespace core_cache;
+
+/**
+ * Cache Loader.
+ *
+ * This cache loader interface provides the required structure for classes that wish to be interacted with as a
+ * means of accessing and interacting with a cache.
+ *
+ * Can be implemented by any class wishing to be a cache loader.
+ * @package core_cache
+ * @copyright Sam Hemelryk
+ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+interface loader_interface {
+ /**
+ * Retrieves the value for the given key from the cache.
+ *
+ * @param string|int $key The key for the data being requested.
+ * @param int $strictness One of IGNORE_MISSING or MUST_EXIST.
+ * @return mixed The data retrieved from the cache, or false if the key did not exist within the cache.
+ * If MUST_EXIST was used then an exception will be thrown if the key does not exist within the cache.
+ */
+ public function get($key, $strictness = IGNORE_MISSING);
+
+ /**
+ * Retrieves the value and actual version for the given key, with at least the required version.
+ *
+ * If there is no value for the key, or there is a value but it doesn't have the required
+ * version, then this function will return false (or throw an exception if you set strictness
+ * to MUST_EXIST).
+ *
+ * This function can be used to make it easier to support localisable caches (where the cache
+ * could be stored on a local server as well as a shared cache). Specifying the version means
+ * that it will automatically retrieve the correct version if available, either from the local
+ * server or [if that has an older version] from the shared server.
+ *
+ * If the cached version is newer than specified version, it will be returned regardless. For
+ * example, if you request version 4, but the locally cached version is 5, it will be returned.
+ * If you request version 6, and the locally cached version is 5, then the system will look in
+ * higher-level caches (if any); if there still isn't a version 6 or greater, it will return
+ * null.
+ *
+ * You must use this function if you use set_versioned.
+ *
+ * @param string|int $key The key for the data being requested.
+ * @param int $requiredversion Minimum required version of the data
+ * @param int $strictness One of IGNORE_MISSING or MUST_EXIST.
+ * @param mixed $actualversion If specified, will be set to the actual version number retrieved
+ * @return mixed Data from the cache, or false if the key did not exist or was too old
+ */
+ public function get_versioned($key, int $requiredversion, int $strictness = IGNORE_MISSING, &$actualversion = null);
+
+ /**
+ * Retrieves an array of values for an array of keys.
+ *
+ * Using this function comes with potential performance implications.
+ * Not all cache stores will support get_many/set_many operations and in order to replicate this functionality will call
+ * the equivalent singular method for each item provided.
+ * This should not deter you from using this function as there is a performance benefit in situations where the cache
+ * store does support it, but you should be aware of this fact.
+ *
+ * @param array $keys The keys of the data being requested.
+ * @param int $strictness One of IGNORE_MISSING or MUST_EXIST.
+ * @return array An array of key value pairs for the items that could be retrieved from the cache.
+ * If MUST_EXIST was used and not all keys existed within the cache then an exception will be thrown.
+ * Otherwise any key that did not exist will have a data value of false within the results.
+ */
+ public function get_many(array $keys, $strictness = IGNORE_MISSING);
+
+ /**
+ * Sends a key => value pair to the cache.
+ *
+ *
+ * // This code will add four entries to the cache, one for each url.
+ * $cache->set('main', 'http://moodle.org');
+ * $cache->set('docs', 'http://docs.moodle.org');
+ * $cache->set('tracker', 'http://tracker.moodle.org');
+ * $cache->set('qa', 'http://qa.moodle.net');
+ *
+ *
+ * @param string|int $key The key for the data being requested.
+ * @param mixed $data The data to set against the key.
+ * @return bool True on success, false otherwise.
+ */
+ public function set($key, $data);
+
+ /**
+ * Sets the value for the given key with the given version.
+ *
+ * The cache does not store multiple versions - any existing version will be overwritten with
+ * this one. This function should only be used if there is a known 'current version' (e.g.
+ * stored in a database table). It only ensures that the cache does not return outdated data.
+ *
+ * This function can be used to help implement localisable caches (where the cache could be
+ * stored on a local server as well as a shared cache). The version will be recorded alongside
+ * the item and get_versioned will always return the correct version.
+ *
+ * The version number must be an integer that always increases. This could be based on the
+ * current time, or a stored value that increases by 1 each time it changes, etc.
+ *
+ * If you use this function you must use get_versioned to retrieve the data.
+ *
+ * @param string|int $key The key for the data being set.
+ * @param int $version Integer for the version of the data
+ * @param mixed $data The data to set against the key.
+ * @return bool True on success, false otherwise.
+ */
+ public function set_versioned($key, int $version, $data): bool;
+
+ /**
+ * Sends several key => value pairs to the cache.
+ *
+ * Using this function comes with potential performance implications.
+ * Not all cache stores will support get_many/set_many operations and in order to replicate this functionality will call
+ * the equivalent singular method for each item provided.
+ * This should not deter you from using this function as there is a performance benefit in situations where the cache store
+ * does support it, but you should be aware of this fact.
+ *
+ *
+ * // This code will add four entries to the cache, one for each url.
+ * $cache->set_many(array(
+ * 'main' => 'http://moodle.org',
+ * 'docs' => 'http://docs.moodle.org',
+ * 'tracker' => 'http://tracker.moodle.org',
+ * 'qa' => ''http://qa.moodle.net'
+ * ));
+ *
+ *
+ * @param array $keyvaluearray An array of key => value pairs to send to the cache.
+ * @return int The number of items successfully set. It is up to the developer to check this matches the number of items.
+ * ... if they care that is.
+ */
+ public function set_many(array $keyvaluearray);
+
+ /**
+ * Test is a cache has a key.
+ *
+ * The use of the has methods is strongly discouraged. In a high load environment the cache may well change between the
+ * test and any subsequent action (get, set, delete etc).
+ * Instead it is recommended to write your code in such a way they it performs the following steps:
+ *
+ * - Attempt to retrieve the information.
+ * - Generate the information.
+ * - Attempt to set the information
+ *
+ *
+ * Its also worth mentioning that not all stores support key tests.
+ * For stores that don't support key tests this functionality is mimicked by using the equivalent get method.
+ * Just one more reason you should not use these methods unless you have a very good reason to do so.
+ *
+ * @param string|int $key
+ * @return bool True if the cache has the requested key, false otherwise.
+ */
+ public function has($key);
+
+ /**
+ * Test if a cache has at least one of the given keys.
+ *
+ * It is strongly recommended to avoid the use of this function if not absolutely required.
+ * In a high load environment the cache may well change between the test and any subsequent action (get, set, delete etc).
+ *
+ * Its also worth mentioning that not all stores support key tests.
+ * For stores that don't support key tests this functionality is mimicked by using the equivalent get method.
+ * Just one more reason you should not use these methods unless you have a very good reason to do so.
+ *
+ * @param array $keys
+ * @return bool True if the cache has at least one of the given keys
+ */
+ public function has_any(array $keys);
+
+ /**
+ * Test is a cache has all of the given keys.
+ *
+ * It is strongly recommended to avoid the use of this function if not absolutely required.
+ * In a high load environment the cache may well change between the test and any subsequent action (get, set, delete etc).
+ *
+ * Its also worth mentioning that not all stores support key tests.
+ * For stores that don't support key tests this functionality is mimicked by using the equivalent get method.
+ * Just one more reason you should not use these methods unless you have a very good reason to do so.
+ *
+ * @param array $keys
+ * @return bool True if the cache has all of the given keys, false otherwise.
+ */
+ public function has_all(array $keys);
+
+ /**
+ * Delete the given key from the cache.
+ *
+ * @param string|int $key The key to delete.
+ * @param bool $recurse When set to true the key will also be deleted from all stacked cache loaders and their stores.
+ * This happens by default and ensure that all the caches are consistent. It is NOT recommended to change this.
+ * @return bool True of success, false otherwise.
+ */
+ public function delete($key, $recurse = true);
+
+ /**
+ * Delete all of the given keys from the cache.
+ *
+ * @param array $keys The key to delete.
+ * @param bool $recurse When set to true the key will also be deleted from all stacked cache loaders and their stores.
+ * This happens by default and ensure that all the caches are consistent. It is NOT recommended to change this.
+ * @return int The number of items successfully deleted.
+ */
+ public function delete_many(array $keys, $recurse = true);
+}
+
+// Alias this class to the old name.
+// This file will be autoloaded by the legacyclasses autoload system.
+// In future all uses of this class will be corrected and the legacy references will be removed.
+class_alias(loader_interface::class, \cache_loader::class);
diff --git a/cache/classes/loader_with_locking_interface.php b/cache/classes/loader_with_locking_interface.php
new file mode 100644
index 00000000000..e1e1416cd7b
--- /dev/null
+++ b/cache/classes/loader_with_locking_interface.php
@@ -0,0 +1,81 @@
+.
+
+namespace core_cache;
+
+use core\exception\moodle_exception;
+
+/**
+ * Cache Loader supporting locking.
+ *
+ * This interface should be given to classes already implementing core_cache\loader_interface that also wish to support locking.
+ * It outlines the required structure for utilising locking functionality when using a cache.
+ *
+ * Can be implemented by any class already implementing the core_cache\loader_interface interface.
+ * @package core_cache
+ * @copyright Sam Hemelryk
+ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+interface loader_with_locking_interface {
+ /**
+ * Acquires a lock for the given key.
+ *
+ * Please note that this happens automatically if the cache definition requires locking.
+ * it is still made a public method so that adhoc caches can use it if they choose.
+ * However this doesn't guarantee consistent access. It will become the responsibility of the calling code to ensure
+ * locks are acquired, checked, and released.
+ *
+ * Prior to Moodle 4,3 this function used to return false if the lock cannot be obtained. It
+ * now always returns true, and throws an exception if the lock cannot be obtained.
+ *
+ * @param string|int $key
+ * @return bool Always returns true (for backwards compatibility)
+ * @throws moodle_exception If the lock cannot be obtained after a timeout
+ */
+ public function acquire_lock($key);
+
+ /**
+ * Checks if the cache loader owns the lock for the given key.
+ *
+ * Please note that this happens automatically if the cache definition requires locking.
+ * it is still made a public method so that adhoc caches can use it if they choose.
+ * However this doesn't guarantee consistent access. It will become the responsibility of the calling code to ensure
+ * locks are acquired, checked, and released.
+ *
+ * @param string|int $key
+ * @return bool True if this code has the lock, false if there is a lock but this code doesn't have it,
+ * null if there is no lock.
+ */
+ public function check_lock_state($key);
+
+ /**
+ * Releases the lock for the given key.
+ *
+ * Please note that this happens automatically if the cache definition requires locking.
+ * it is still made a public method so that adhoc caches can use it if they choose.
+ * However this doesn't guarantee consistent access. It will become the responsibility of the calling code to ensure
+ * locks are acquired, checked, and released.
+ *
+ * @param string|int $key
+ * @return bool True if the lock has been released, false if there was a problem releasing the lock.
+ */
+ public function release_lock($key);
+}
+
+// Alias this class to the old name.
+// This file will be autoloaded by the legacyclasses autoload system.
+// In future all uses of this class will be corrected and the legacy references will be removed.
+class_alias(loader_with_locking_interface::class, \cache_loader_with_locking::class);
diff --git a/cache/classes/local/administration_display_helper.php b/cache/classes/local/administration_display_helper.php
index 900cb89f437..f14ef80d6bd 100644
--- a/cache/classes/local/administration_display_helper.php
+++ b/cache/classes/local/administration_display_helper.php
@@ -20,7 +20,7 @@
* This file is part of Moodle's cache API, affectionately called MUC.
* It contains the components that are requried in order to use caching.
*
- * @package core
+ * @package core_cache
* @category cache
* @author Peter Burnett
* @copyright 2020 Catalyst IT
@@ -30,8 +30,30 @@
namespace core_cache\local;
-use cache_store, cache_factory, cache_config_writer, cache_helper;
+use core_cache\cache;
+use core_cache\config;
+use core_cache\config_writer;
+use core_cache\configurable_cache_interface;
+use core_cache\exception\cache_exception;
+use core_cache\factory;
+use core_cache\form\cache_lock_form;
+use core_cache\form\cache_mode_mappings_form;
+use core_cache\form\cache_definition_sharing_form;
+use core_cache\form\cache_definition_mappings_form;
+use core_cache\form\cachestore_addinstance_form;
+use core_cache\helper as cache_helper;
+use core_cache\lockable_cache_interface;
+use core_cache\store;
+use core_component;
+use core\context;
+use core\context\system as context_system;
+use core\exception\coding_exception;
+use core\exception\moodle_exception;
use core\output\notification;
+use core\output\single_button;
+use core\url;
+use html_writer;
+use stdClass;
/**
* A cache helper for administration tasks
@@ -42,9 +64,8 @@ use core\output\notification;
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class administration_display_helper extends \core_cache\administration_helper {
-
/**
- * Please do not call constructor directly. Use cache_factory::get_administration_display_helper() instead.
+ * Please do not call constructor directly. Use factory::get_administration_display_helper() instead.
*/
public function __construct() {
// Nothing to do here.
@@ -59,33 +80,33 @@ class administration_display_helper extends \core_cache\administration_helper {
* element is used.
* @return array of actions. Each action is an action_url.
*/
- public function get_definition_actions(\context $context, array $definitionsummary): array {
+ public function get_definition_actions(context $context, array $definitionsummary): array {
global $OUTPUT;
if (has_capability('moodle/site:config', $context)) {
- $actions = array();
+ $actions = [];
// Edit mappings.
$actions[] = $OUTPUT->action_link(
- new \moodle_url('/cache/admin.php', array('action' => 'editdefinitionmapping',
- 'definition' => $definitionsummary['id'])),
+ new url('/cache/admin.php', ['action' => 'editdefinitionmapping',
+ 'definition' => $definitionsummary['id'], ]),
get_string('editmappings', 'cache')
);
// Edit sharing.
if (count($definitionsummary['sharingoptions']) > 1) {
$actions[] = $OUTPUT->action_link(
- new \moodle_url('/cache/admin.php', array('action' => 'editdefinitionsharing',
- 'definition' => $definitionsummary['id'])),
+ new url('/cache/admin.php', ['action' => 'editdefinitionsharing',
+ 'definition' => $definitionsummary['id'], ]),
get_string('editsharing', 'cache')
);
}
// Purge.
$actions[] = $OUTPUT->action_link(
- new \moodle_url('/cache/admin.php', array('action' => 'purgedefinition',
- 'definition' => $definitionsummary['id'], 'sesskey' => sesskey())),
+ new url('/cache/admin.php', ['action' => 'purgedefinition',
+ 'definition' => $definitionsummary['id'], 'sesskey' => sesskey(), ]),
get_string('purge', 'cache')
);
return $actions;
}
- return array();
+ return [];
}
/**
@@ -98,24 +119,24 @@ class administration_display_helper extends \core_cache\administration_helper {
*/
public function get_store_instance_actions(string $name, array $storedetails): array {
global $OUTPUT;
- $actions = array();
- if (has_capability('moodle/site:config', \context_system::instance())) {
- $baseurl = new \moodle_url('/cache/admin.php', array('store' => $name));
+ $actions = [];
+ if (has_capability('moodle/site:config', context_system::instance())) {
+ $baseurl = new url('/cache/admin.php', ['store' => $name]);
if (empty($storedetails['default'])) {
// Edit store.
$actions[] = $OUTPUT->action_link(
- new \moodle_url($baseurl, array('action' => 'editstore', 'plugin' => $storedetails['plugin'])),
+ new url($baseurl, ['action' => 'editstore', 'plugin' => $storedetails['plugin']]),
get_string('editstore', 'cache')
);
// Delete store.
$actions[] = $OUTPUT->action_link(
- new \moodle_url($baseurl, array('action' => 'deletestore')),
+ new url($baseurl, ['action' => 'deletestore']),
get_string('deletestore', 'cache')
);
}
// Purge store.
$actions[] = $OUTPUT->action_link(
- new \moodle_url($baseurl, array('action' => 'purgestore', 'sesskey' => sesskey())),
+ new url($baseurl, ['action' => 'purgestore', 'sesskey' => sesskey()]),
get_string('purge', 'cache')
);
}
@@ -132,11 +153,13 @@ class administration_display_helper extends \core_cache\administration_helper {
*/
public function get_store_plugin_actions(string $name, array $plugindetails): array {
global $OUTPUT;
- $actions = array();
- if (has_capability('moodle/site:config', \context_system::instance())) {
+ $actions = [];
+ if (has_capability('moodle/site:config', context_system::instance())) {
if (!empty($plugindetails['canaddinstance'])) {
- $url = new \moodle_url('/cache/admin.php',
- array('action' => 'addstore', 'plugin' => $name));
+ $url = new url(
+ '/cache/admin.php',
+ ['action' => 'addstore', 'plugin' => $name]
+ );
$actions[] = $OUTPUT->action_link(
$url,
get_string('addinstance', 'cache')
@@ -153,28 +176,28 @@ class administration_display_helper extends \core_cache\administration_helper {
* @return cachestore_addinstance_form
* @throws coding_exception
*/
- public function get_add_store_form(string $plugin): \cachestore_addinstance_form {
+ public function get_add_store_form(string $plugin): cachestore_addinstance_form {
global $CFG; // Needed for includes.
- $plugins = \core_component::get_plugin_list('cachestore');
+ $plugins = core_component::get_plugin_list('cachestore');
if (!array_key_exists($plugin, $plugins)) {
- throw new \coding_exception('Invalid cache plugin used when trying to create an edit form.');
+ throw new coding_exception('Invalid cache plugin used when trying to create an edit form.');
}
$plugindir = $plugins[$plugin];
$class = 'cachestore_addinstance_form';
- if (file_exists($plugindir.'/addinstanceform.php')) {
- require_once($plugindir.'/addinstanceform.php');
- if (class_exists('cachestore_'.$plugin.'_addinstance_form')) {
- $class = 'cachestore_'.$plugin.'_addinstance_form';
- if (!array_key_exists('cachestore_addinstance_form', class_parents($class))) {
- throw new \coding_exception('Cache plugin add instance forms must extend cachestore_addinstance_form');
+ if (file_exists($plugindir . '/addinstanceform.php')) {
+ require_once($plugindir . '/addinstanceform.php');
+ if (class_exists('cachestore_' . $plugin . '_addinstance_form')) {
+ $class = 'cachestore_' . $plugin . '_addinstance_form';
+ if (!array_key_exists(cachestore_addinstance_form::class, class_parents($class))) {
+ throw new coding_exception('Cache plugin add instance forms must extend cachestore_addinstance_form');
}
}
}
$locks = $this->get_possible_locks_for_stores($plugindir, $plugin);
- $url = new \moodle_url('/cache/admin.php', array('action' => 'addstore'));
- return new $class($url, array('plugin' => $plugin, 'store' => null, 'locks' => $locks));
+ $url = new url('/cache/admin.php', ['action' => 'addstore']);
+ return new $class($url, ['plugin' => $plugin, 'store' => null, 'locks' => $locks]);
}
/**
@@ -185,43 +208,45 @@ class administration_display_helper extends \core_cache\administration_helper {
* @return cachestore_addinstance_form
* @throws coding_exception
*/
- public function get_edit_store_form(string $plugin, string $store): \cachestore_addinstance_form {
+ public function get_edit_store_form(string $plugin, string $store): cachestore_addinstance_form {
global $CFG; // Needed for includes.
- $plugins = \core_component::get_plugin_list('cachestore');
+ $plugins = core_component::get_plugin_list('cachestore');
if (!array_key_exists($plugin, $plugins)) {
- throw new \coding_exception('Invalid cache plugin used when trying to create an edit form.');
+ throw new coding_exception('Invalid cache plugin used when trying to create an edit form.');
}
- $factory = \cache_factory::instance();
+ $factory = factory::instance();
$config = $factory->create_config_instance();
$stores = $config->get_all_stores();
if (!array_key_exists($store, $stores)) {
- throw new \coding_exception('Invalid store name given when trying to create an edit form.');
+ throw new coding_exception('Invalid store name given when trying to create an edit form.');
}
$plugindir = $plugins[$plugin];
$class = 'cachestore_addinstance_form';
- if (file_exists($plugindir.'/addinstanceform.php')) {
- require_once($plugindir.'/addinstanceform.php');
- if (class_exists('cachestore_'.$plugin.'_addinstance_form')) {
- $class = 'cachestore_'.$plugin.'_addinstance_form';
- if (!array_key_exists('cachestore_addinstance_form', class_parents($class))) {
- throw new \coding_exception('Cache plugin add instance forms must extend cachestore_addinstance_form');
+ if (file_exists($plugindir . '/addinstanceform.php')) {
+ require_once($plugindir . '/addinstanceform.php');
+ if (class_exists('cachestore_' . $plugin . '_addinstance_form')) {
+ $class = 'cachestore_' . $plugin . '_addinstance_form';
+ if (!array_key_exists(cachestore_addinstance_form::class, class_parents($class))) {
+ throw new coding_exception('Cache plugin add instance forms must extend cachestore_addinstance_form');
}
}
}
$locks = $this->get_possible_locks_for_stores($plugindir, $plugin);
- $url = new \moodle_url('/cache/admin.php', array('action' => 'editstore', 'plugin' => $plugin, 'store' => $store));
- $editform = new $class($url, array('plugin' => $plugin, 'store' => $store, 'locks' => $locks));
+ $url = new url('/cache/admin.php', ['action' => 'editstore', 'plugin' => $plugin, 'store' => $store]);
+ $editform = new $class($url, ['plugin' => $plugin, 'store' => $store, 'locks' => $locks]);
if (isset($stores[$store]['lock'])) {
- $editform->set_data(array('lock' => $stores[$store]['lock']));
+ $editform->set_data(['lock' => $stores[$store]['lock']]);
}
// See if the cachestore is going to want to load data for the form.
// If it has a customised add instance form then it is going to want to.
- $storeclass = 'cachestore_'.$plugin;
+ $storeclass = 'cachestore_' . $plugin;
$storedata = $stores[$store];
- if (array_key_exists('configuration', $storedata) &&
- array_key_exists('cache_is_configurable', class_implements($storeclass))) {
+ if (
+ array_key_exists('configuration', $storedata) &&
+ array_key_exists(configurable_cache_interface::class, class_implements($storeclass))
+ ) {
$storeclass::config_set_edit_form_data($editform, $storedata['configuration']);
}
return $editform;
@@ -237,17 +262,17 @@ class administration_display_helper extends \core_cache\administration_helper {
protected function get_possible_locks_for_stores(string $plugindir, string $plugin) {
global $CFG; // Needed for includes.
$supportsnativelocking = false;
- if (file_exists($plugindir.'/lib.php')) {
- require_once($plugindir.'/lib.php');
- $pluginclass = 'cachestore_'.$plugin;
+ if (file_exists($plugindir . '/lib.php')) {
+ require_once($plugindir . '/lib.php');
+ $pluginclass = 'cachestore_' . $plugin;
if (class_exists($pluginclass)) {
- $supportsnativelocking = array_key_exists('cache_is_lockable', class_implements($pluginclass));
+ $supportsnativelocking = array_key_exists(lockable_cache_interface::class, class_implements($pluginclass));
}
}
if (!$supportsnativelocking) {
- $config = \cache_config::instance();
- $locks = array();
+ $config = config::instance();
+ $locks = [];
foreach ($config->get_locks() as $lock => $conf) {
if (!empty($conf['default'])) {
$name = get_string($lock, 'cache');
@@ -271,21 +296,21 @@ class administration_display_helper extends \core_cache\administration_helper {
* @return array
* @throws coding_exception
*/
- public function get_store_configuration_from_data(\stdClass $data): array {
+ public function get_store_configuration_from_data(stClass $data): array {
global $CFG;
- $file = $CFG->dirroot.'/cache/stores/'.$data->plugin.'/lib.php';
+ $file = $CFG->dirroot . '/cache/stores/' . $data->plugin . '/lib.php';
if (!file_exists($file)) {
- throw new \coding_exception('Invalid cache plugin provided. '.$file);
+ throw new coding_exception('Invalid cache plugin provided. ' . $file);
}
require_once($file);
- $class = 'cachestore_'.$data->plugin;
+ $class = 'cachestore_' . $data->plugin;
if (!class_exists($class)) {
- throw new \coding_exception('Invalid cache plugin provided.');
+ throw new coding_exception('Invalid cache plugin provided.');
}
- if (array_key_exists('cache_is_configurable', class_implements($class))) {
+ if (array_key_exists(configurable_cache_interface::class, class_implements($class))) {
return $class::config_get_configuration_array($data);
}
- return array();
+ return [];
}
/**
@@ -296,8 +321,8 @@ class administration_display_helper extends \core_cache\administration_helper {
* @return array
*/
public function get_addable_lock_options(): array {
- $plugins = \core_component::get_plugin_list_with_class('cachelock', '', 'lib.php');
- $options = array();
+ $plugins = core_component::get_plugin_list_with_class('cachelock', '', 'lib.php');
+ $options = [];
$len = strlen('cachelock_');
foreach ($plugins as $plugin => $class) {
$method = "$class::can_add_instance";
@@ -314,28 +339,30 @@ class administration_display_helper extends \core_cache\administration_helper {
* Gets the form to use when adding a lock instance.
*
* @param string $plugin
- * @param array $lockplugin
+ * @param array|null $lockplugin
* @return cache_lock_form
* @throws coding_exception
*/
- public function get_add_lock_form(string $plugin, ?array $lockplugin = null): \cache_lock_form {
+ public function get_add_lock_form(string $plugin, ?array $lockplugin = null): cache_lock_form {
global $CFG; // Needed for includes.
- $plugins = \core_component::get_plugin_list('cachelock');
+ $plugins = core_component::get_plugin_list('cachelock');
if (!array_key_exists($plugin, $plugins)) {
- throw new \coding_exception('Invalid cache lock plugin requested when trying to create a form.');
+ throw new coding_exception('Invalid cache lock plugin requested when trying to create a form.');
}
$plugindir = $plugins[$plugin];
- $class = 'cache_lock_form';
- if (file_exists($plugindir.'/addinstanceform.php') && in_array('cache_is_configurable', class_implements($class))) {
- require_once($plugindir.'/addinstanceform.php');
- if (class_exists('cachelock_'.$plugin.'_addinstance_form')) {
- $class = 'cachelock_'.$plugin.'_addinstance_form';
- if (!array_key_exists('cache_lock_form', class_parents($class))) {
- throw new \coding_exception('Cache lock plugin add instance forms must extend cache_lock_form');
+ $class = cache_lock_form::class;
+ $hasaddinstanceform = file_exists($plugindir . '/addinstanceform.php');
+ $hasaddinstanceform = $hasaddinstanceform && in_array(configurable_cache_interface::class, class_implements($class));
+ if ($hasaddinstanceform) {
+ require_once($plugindir . '/addinstanceform.php');
+ if (class_exists('cachelock_' . $plugin . '_addinstance_form')) {
+ $class = 'cachelock_' . $plugin . '_addinstance_form';
+ if (!is_a($class, cache_lock_form::class, true)) {
+ throw new coding_exception('Cache lock plugin add instance forms must extend cache_lock_form');
}
}
}
- return new $class(null, array('lock' => $plugin));
+ return new $class(null, ['lock' => $plugin]);
}
/**
@@ -346,21 +373,21 @@ class administration_display_helper extends \core_cache\administration_helper {
* @return array
* @throws coding_exception
*/
- public function get_lock_configuration_from_data(string $plugin, \stdClass $data): array {
+ public function get_lock_configuration_from_data(string $plugin, stdClass $data): array {
global $CFG;
- $file = $CFG->dirroot.'/cache/locks/'.$plugin.'/lib.php';
+ $file = $CFG->dirroot . '/cache/locks/' . $plugin . '/lib.php';
if (!file_exists($file)) {
- throw new \coding_exception('Invalid cache plugin provided. '.$file);
+ throw new coding_exception('Invalid cache plugin provided. ' . $file);
}
require_once($file);
- $class = 'cachelock_'.$plugin;
+ $class = 'cachelock_' . $plugin;
if (!class_exists($class)) {
- throw new \coding_exception('Invalid cache plugin provided.');
+ throw new coding_exception('Invalid cache plugin provided.');
}
- if (array_key_exists('cache_is_configurable', class_implements($class))) {
+ if (array_key_exists(configurable_cache_interface::class, class_implements($class))) {
return $class::config_get_configuration_array($data);
}
- return array();
+ return [];
}
/**
@@ -372,27 +399,27 @@ class administration_display_helper extends \core_cache\administration_helper {
*/
public function perform_cache_actions(string $action, array $forminfo): array {
switch ($action) {
- case 'rescandefinitions' : // Rescan definitions.
+ case 'rescandefinitions': // Rescan definitions.
$this->action_rescan_definition();
break;
- case 'addstore' : // Add the requested store.
+ case 'addstore': // Add the requested store.
$forminfo = $this->action_addstore();
break;
- case 'editstore' : // Edit the requested store.
+ case 'editstore': // Edit the requested store.
$forminfo = $this->action_editstore();
break;
- case 'deletestore' : // Delete a given store.
+ case 'deletestore': // Delete a given store.
$this->action_deletestore($action);
break;
- case 'editdefinitionmapping' : // Edit definition mappings.
+ case 'editdefinitionmapping': // Edit definition mappings.
$forminfo = $this->action_editdefinitionmapping();
break;
- case 'editdefinitionsharing' : // Edit definition sharing.
+ case 'editdefinitionsharing': // Edit definition sharing.
$forminfo = $this->action_editdefinitionsharing();
break;
@@ -431,7 +458,7 @@ class administration_display_helper extends \core_cache\administration_helper {
global $PAGE;
require_sesskey();
- \cache_config_writer::update_definitions();
+ config_writer::update_definitions();
redirect($PAGE->url);
}
@@ -446,7 +473,7 @@ class administration_display_helper extends \core_cache\administration_helper {
$plugin = required_param('plugin', PARAM_PLUGIN);
if (!$storepluginsummaries[$plugin]['canaddinstance']) {
- throw new \moodle_exception('ex_unmetstorerequirements', 'cache');
+ throw new moodle_exception('ex_unmetstorerequirements', 'cache');
}
$mform = $this->get_add_store_form($plugin);
$title = get_string('addstore', 'cache', $storepluginsummaries[$plugin]['name']);
@@ -454,7 +481,7 @@ class administration_display_helper extends \core_cache\administration_helper {
redirect($PAGE->url);
} else if ($data = $mform->get_data()) {
$config = $this->get_store_configuration_from_data($data);
- $writer = \cache_config_writer::instance();
+ $writer = config_writer::instance();
unset($config['lock']);
foreach ($writer->get_locks() as $lock => $lockconfig) {
if ($lock == $data->lock) {
@@ -466,7 +493,7 @@ class administration_display_helper extends \core_cache\administration_helper {
}
$PAGE->navbar->add(get_string('addstore', 'cache', 'cache'), $PAGE->url);
- return array('form' => $mform, 'title' => $title);
+ return ['form' => $mform, 'title' => $title];
}
/**
@@ -486,7 +513,7 @@ class administration_display_helper extends \core_cache\administration_helper {
redirect($PAGE->url);
} else if ($data = $mform->get_data()) {
$config = $this->get_store_configuration_from_data($data);
- $writer = \cache_config_writer::instance();
+ $writer = config_writer::instance();
unset($config['lock']);
foreach ($writer->get_locks() as $lock => $lockconfig) {
@@ -498,7 +525,7 @@ class administration_display_helper extends \core_cache\administration_helper {
redirect($PAGE->url, get_string('editstoresuccess', 'cache', $storepluginsummaries[$plugin]['name']), 5);
}
- return array('form' => $mform, 'title' => $title);
+ return ['form' => $mform, 'title' => $title];
}
/**
@@ -525,9 +552,9 @@ class administration_display_helper extends \core_cache\administration_helper {
if ($notifysuccess) {
if (!$confirm) {
$title = get_string('confirmstoredeletion', 'cache');
- $params = array('store' => $store, 'confirm' => 1, 'action' => $action, 'sesskey' => sesskey());
- $url = new \moodle_url($PAGE->url, $params);
- $button = new \single_button($url, get_string('deletestore', 'cache'));
+ $params = ['store' => $store, 'confirm' => 1, 'action' => $action, 'sesskey' => sesskey()];
+ $url = new url($PAGE->url, $params);
+ $button = new single_button($url, get_string('deletestore', 'cache'));
$PAGE->set_title($title);
$PAGE->set_heading($SITE->fullname);
@@ -539,7 +566,7 @@ class administration_display_helper extends \core_cache\administration_helper {
exit;
} else {
require_sesskey();
- $writer = \cache_config_writer::instance();
+ $writer = config_writer::instance();
$writer->delete_store_instance($store);
redirect($PAGE->url, get_string('deletestoresuccess', 'cache'), 5);
}
@@ -560,15 +587,15 @@ class administration_display_helper extends \core_cache\administration_helper {
$definition = required_param('definition', PARAM_SAFEPATH);
if (!array_key_exists($definition, $definitionsummaries)) {
- throw new \cache_exception('Invalid cache definition requested');
+ throw new cache_exception('Invalid cache definition requested');
}
$title = get_string('editdefinitionmappings', 'cache', $definition);
- $mform = new \cache_definition_mappings_form($PAGE->url, array('definition' => $definition));
+ $mform = new cache_definition_mappings_form($PAGE->url, ['definition' => $definition]);
if ($mform->is_cancelled()) {
redirect($PAGE->url);
} else if ($data = $mform->get_data()) {
- $writer = \cache_config_writer::instance();
- $mappings = array();
+ $writer = config_writer::instance();
+ $mappings = [];
foreach ($data->mappings as $mapping) {
if (!empty($mapping)) {
$mappings[] = $mapping;
@@ -579,7 +606,7 @@ class administration_display_helper extends \core_cache\administration_helper {
}
$PAGE->navbar->add(get_string('updatedefinitionmapping', 'cache'), $PAGE->url);
- return array('form' => $mform, 'title' => $title);
+ return ['form' => $mform, 'title' => $title];
}
/**
@@ -593,24 +620,24 @@ class administration_display_helper extends \core_cache\administration_helper {
$definition = required_param('definition', PARAM_SAFEPATH);
if (!array_key_exists($definition, $definitionsummaries)) {
- throw new \cache_exception('Invalid cache definition requested');
+ throw new cache_exception('Invalid cache definition requested');
}
$title = get_string('editdefinitionsharing', 'cache', $definition);
$sharingoptions = $definitionsummaries[$definition]['sharingoptions'];
- $customdata = array('definition' => $definition, 'sharingoptions' => $sharingoptions);
- $mform = new \cache_definition_sharing_form($PAGE->url, $customdata);
- $mform->set_data(array(
+ $customdata = ['definition' => $definition, 'sharingoptions' => $sharingoptions];
+ $mform = new cache_definition_sharing_form($PAGE->url, $customdata);
+ $mform->set_data([
'sharing' => $definitionsummaries[$definition]['selectedsharingoption'],
- 'userinputsharingkey' => $definitionsummaries[$definition]['userinputsharingkey']
- ));
+ 'userinputsharingkey' => $definitionsummaries[$definition]['userinputsharingkey'],
+ ]);
if ($mform->is_cancelled()) {
redirect($PAGE->url);
} else if ($data = $mform->get_data()) {
$component = $definitionsummaries[$definition]['component'];
$area = $definitionsummaries[$definition]['area'];
// Purge the stores removing stale data before we alter the sharing option.
- \cache_helper::purge_stores_used_by_definition($component, $area);
- $writer = \cache_config_writer::instance();
+ cache_helper::purge_stores_used_by_definition($component, $area);
+ $writer = config_writer::instance();
$sharing = array_sum(array_keys($data->sharing));
$userinputsharingkey = $data->userinputsharingkey;
$writer->set_definition_sharing($definition, $sharing, $userinputsharingkey);
@@ -618,7 +645,7 @@ class administration_display_helper extends \core_cache\administration_helper {
}
$PAGE->navbar->add(get_string('updatedefinitionsharing', 'cache'), $PAGE->url);
- return array('form' => $mform, 'title' => $title);
+ return ['form' => $mform, 'title' => $title];
}
/**
@@ -631,26 +658,26 @@ class administration_display_helper extends \core_cache\administration_helper {
$storeinstancesummaries = $this->get_store_instance_summaries();
$defaultmodestores = $this->get_default_mode_stores();
- $mform = new \cache_mode_mappings_form(null, $storeinstancesummaries);
- $mform->set_data(array(
- 'mode_'.cache_store::MODE_APPLICATION => key($defaultmodestores[cache_store::MODE_APPLICATION]),
- 'mode_'.cache_store::MODE_SESSION => key($defaultmodestores[cache_store::MODE_SESSION]),
- 'mode_'.cache_store::MODE_REQUEST => key($defaultmodestores[cache_store::MODE_REQUEST]),
- ));
+ $mform = new cache_mode_mappings_form(null, $storeinstancesummaries);
+ $mform->set_data([
+ 'mode_' . store::MODE_APPLICATION => key($defaultmodestores[store::MODE_APPLICATION]),
+ 'mode_' . store::MODE_SESSION => key($defaultmodestores[store::MODE_SESSION]),
+ 'mode_' . store::MODE_REQUEST => key($defaultmodestores[store::MODE_REQUEST]),
+ ]);
if ($mform->is_cancelled()) {
redirect($PAGE->url);
} else if ($data = $mform->get_data()) {
- $mappings = array(
- cache_store::MODE_APPLICATION => array($data->{'mode_'.cache_store::MODE_APPLICATION}),
- cache_store::MODE_SESSION => array($data->{'mode_'.cache_store::MODE_SESSION}),
- cache_store::MODE_REQUEST => array($data->{'mode_'.cache_store::MODE_REQUEST}),
- );
- $writer = cache_config_writer::instance();
+ $mappings = [
+ store::MODE_APPLICATION => [$data->{'mode_' . store::MODE_APPLICATION}],
+ store::MODE_SESSION => [$data->{'mode_' . store::MODE_SESSION}],
+ store::MODE_REQUEST => [$data->{'mode_' . store::MODE_REQUEST}],
+ ];
+ $writer = config_writer::instance();
$writer->set_mode_mappings($mappings);
redirect($PAGE->url);
}
- return array('form' => $mform);
+ return ['form' => $mform];
}
/**
@@ -663,8 +690,8 @@ class administration_display_helper extends \core_cache\administration_helper {
require_sesskey();
$id = required_param('definition', PARAM_SAFEPATH);
- list($component, $area) = explode('/', $id, 2);
- $factory = cache_factory::instance();
+ [$component, $area] = explode('/', $id, 2);
+ $factory = factory::instance();
$definition = $factory->create_definition($component, $area);
if ($definition->has_required_identifiers()) {
// We will have to purge the stores used by this definition.
@@ -679,9 +706,11 @@ class administration_display_helper extends \core_cache\administration_helper {
'component' => $component,
'area' => $area,
]);
- $purgeagainlink = \html_writer::link(new \moodle_url('/cache/admin.php', [
- 'action' => 'purgedefinition', 'sesskey' => sesskey(), 'definition' => $id]),
- get_string('purgeagain', 'cache'));
+ $purgeagainlink = html_writer::link(
+ new url('/cache/admin.php', [
+ 'action' => 'purgedefinition', 'sesskey' => sesskey(), 'definition' => $id, ]),
+ get_string('purgeagain', 'cache')
+ );
redirect($PAGE->url, $message . ' ' . $purgeagainlink, 5);
}
@@ -697,9 +726,11 @@ class administration_display_helper extends \core_cache\administration_helper {
$store = required_param('store', PARAM_TEXT);
cache_helper::purge_store($store);
$message = get_string('purgexstoresuccess', 'cache', ['store' => $store]);
- $purgeagainlink = \html_writer::link(new \moodle_url('/cache/admin.php', [
- 'action' => 'purgestore', 'sesskey' => sesskey(), 'store' => $store]),
- get_string('purgeagain', 'cache'));
+ $purgeagainlink = html_writer::link(
+ new url('/cache/admin.php', [
+ 'action' => 'purgestore', 'sesskey' => sesskey(), 'store' => $store, ]),
+ get_string('purgeagain', 'cache')
+ );
redirect($PAGE->url, $message . ' ' . $purgeagainlink, 5);
}
@@ -717,7 +748,7 @@ class administration_display_helper extends \core_cache\administration_helper {
if ($mform->is_cancelled()) {
redirect($PAGE->url);
} else if ($data = $mform->get_data()) {
- $factory = cache_factory::instance();
+ $factory = factory::instance();
$config = $factory->create_config_instance(true);
$name = $data->name;
$data = $this->get_lock_configuration_from_data($lock, $data);
@@ -725,7 +756,7 @@ class administration_display_helper extends \core_cache\administration_helper {
redirect($PAGE->url, get_string('addlocksuccess', 'cache', $name), 5);
}
- return array('form' => $mform);
+ return ['form' => $mform];
}
/**
@@ -750,9 +781,9 @@ class administration_display_helper extends \core_cache\administration_helper {
if ($notifysuccess) {
if (!$confirm) {
$title = get_string('confirmlockdeletion', 'cache');
- $params = array('lock' => $lock, 'confirm' => 1, 'action' => $action, 'sesskey' => sesskey());
- $url = new \moodle_url($PAGE->url, $params);
- $button = new \single_button($url, get_string('deletelock', 'cache'));
+ $params = ['lock' => $lock, 'confirm' => 1, 'action' => $action, 'sesskey' => sesskey()];
+ $url = new url($PAGE->url, $params);
+ $button = new single_button($url, get_string('deletelock', 'cache'));
$PAGE->set_title($title);
$PAGE->set_heading($SITE->fullname);
@@ -764,7 +795,7 @@ class administration_display_helper extends \core_cache\administration_helper {
exit;
} else {
require_sesskey();
- $writer = cache_config_writer::instance();
+ $writer = config_writer::instance();
$writer->delete_lock_instance($lock);
redirect($PAGE->url, get_string('deletelocksuccess', 'cache'), 5);
}
@@ -780,7 +811,7 @@ class administration_display_helper extends \core_cache\administration_helper {
* @return string the HTML for the admin page.
*/
public function generate_admin_page(\core_cache\output\renderer $renderer): string {
- $context = \context_system::instance();
+ $context = context_system::instance();
$html = '';
$storepluginsummaries = $this->get_store_plugin_summaries();
@@ -795,10 +826,10 @@ class administration_display_helper extends \core_cache\administration_helper {
$html .= $renderer->lock_summaries($locks);
$html .= $renderer->additional_lock_actions();
- $applicationstore = join(', ', $defaultmodestores[cache_store::MODE_APPLICATION]);
- $sessionstore = join(', ', $defaultmodestores[cache_store::MODE_SESSION]);
- $requeststore = join(', ', $defaultmodestores[cache_store::MODE_REQUEST]);
- $editurl = new \moodle_url('/cache/admin.php', array('action' => 'editmodemappings'));
+ $applicationstore = join(', ', $defaultmodestores[store::MODE_APPLICATION]);
+ $sessionstore = join(', ', $defaultmodestores[store::MODE_SESSION]);
+ $requeststore = join(', ', $defaultmodestores[store::MODE_REQUEST]);
+ $editurl = new url('/cache/admin.php', ['action' => 'editmodemappings']);
$html .= $renderer->mode_mappings($applicationstore, $sessionstore, $requeststore, $editurl);
return $html;
@@ -829,7 +860,7 @@ class administration_display_helper extends \core_cache\administration_helper {
public function get_usage(int $samplekeys): array {
$results = [];
- $factory = cache_factory::instance();
+ $factory = factory::instance();
// Check the caches we already have an instance of, so we don't make another one...
$got = $factory->get_caches_in_use();
@@ -849,7 +880,7 @@ class administration_display_helper extends \core_cache\administration_helper {
// Where possible (if it doesn't need identifiers), make an instance of the cache, otherwise
// we can't get the store instances for it (and it won't show up in the list).
if (empty($configdetails['requireidentifiers'])) {
- \cache::make($configdetails['component'], $configdetails['area']);
+ cache::make($configdetails['component'], $configdetails['area']);
}
}
$definition = $factory->create_definition($configdetails['component'], $configdetails['area']);
@@ -859,7 +890,7 @@ class administration_display_helper extends \core_cache\administration_helper {
$currentresult = (object)['cacheid' => $definition->get_id(), 'stores' => []];
$results[$currentresult->cacheid] = $currentresult;
- /** @var cache_store $store */
+ /** @var store $store */
foreach ($stores as $store) {
// Skip static cache.
if ($store instanceof \cachestore_static) {
diff --git a/cache/classes/lockable_cache_interface.php b/cache/classes/lockable_cache_interface.php
new file mode 100644
index 00000000000..504af701a8d
--- /dev/null
+++ b/cache/classes/lockable_cache_interface.php
@@ -0,0 +1,65 @@
+.
+
+namespace core_cache;
+
+/**
+ * Cache store feature: locking.
+ *
+ * This is a feature that cache stores can implement if they wish to support locking themselves rather
+ * than having the cache loader handle it for them.
+ *
+ * Can be implemented by classes already implementing store.
+ * @package core_cache
+ * @copyright Sam Hemelryk
+ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+interface lockable_cache_interface {
+ /**
+ * Acquires a lock on the given key for the given identifier.
+ *
+ * @param string $key The key we are locking.
+ * @param string $ownerid The identifier so we can check if we have the lock or if it is someone else.
+ * The use of this property is entirely optional and implementations can act as they like upon it.
+ * @return bool True if the lock could be acquired, false otherwise.
+ */
+ public function acquire_lock($key, $ownerid);
+
+ /**
+ * Test if there is already a lock for the given key and if there is whether it belongs to the calling code.
+ *
+ * @param string $key The key we are locking.
+ * @param string $ownerid The identifier so we can check if we have the lock or if it is someone else.
+ * @return bool True if this code has the lock, false if there is a lock but this code doesn't have it, null if there
+ * is no lock.
+ */
+ public function check_lock_state($key, $ownerid);
+
+ /**
+ * Releases the lock on the given key.
+ *
+ * @param string $key The key we are locking.
+ * @param string $ownerid The identifier so we can check if we have the lock or if it is someone else.
+ * The use of this property is entirely optional and implementations can act as they like upon it.
+ * @return bool True if the lock has been released, false if there was a problem releasing the lock.
+ */
+ public function release_lock($key, $ownerid);
+}
+
+// Alias this class to the old name.
+// This file will be autoloaded by the legacyclasses autoload system.
+// In future all uses of this class will be corrected and the legacy references will be removed.
+class_alias(lockable_cache_interface::class, \cache_is_lockable::class);
diff --git a/cache/classes/output/renderer.php b/cache/classes/output/renderer.php
index 9f634f9a8ac..c0284f4aa2a 100644
--- a/cache/classes/output/renderer.php
+++ b/cache/classes/output/renderer.php
@@ -16,9 +16,9 @@
namespace core_cache\output;
-use cache_factory;
-use cache_store;
use context;
+use core_cache\factory as cache_factory;
+use core_cache\store as cache_store;
use core_collator;
use html_table;
use html_table_cell;
@@ -36,7 +36,6 @@ use single_select;
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class renderer extends \plugin_renderer_base {
-
/**
* Displays store summaries.
*
@@ -48,7 +47,7 @@ class renderer extends \plugin_renderer_base {
*/
public function store_instance_summariers(array $storeinstancesummaries, array $storepluginsummaries) {
$table = new html_table();
- $table->head = array(
+ $table->head = [
get_string('storename', 'cache'),
get_string('plugin', 'cache'),
get_string('storeready', 'cache'),
@@ -57,8 +56,8 @@ class renderer extends \plugin_renderer_base {
get_string('supports', 'cache'),
get_string('locking', 'cache') . ' ' . $this->output->help_icon('locking', 'cache'),
get_string('actions', 'cache'),
- );
- $table->colclasses = array(
+ ];
+ $table->colclasses = [
'storename',
'plugin',
'storeready',
@@ -66,42 +65,42 @@ class renderer extends \plugin_renderer_base {
'modes',
'supports',
'locking',
- 'actions'
- );
- $table->data = array();
+ 'actions',
+ ];
+ $table->data = [];
$defaultstoreactions = get_string('defaultstoreactions', 'cache');
foreach ($storeinstancesummaries as $name => $storesummary) {
$htmlactions = cache_factory::get_administration_display_helper()->get_store_instance_actions($name, $storesummary);
- $modes = array();
+ $modes = [];
foreach ($storesummary['modes'] as $mode => $enabled) {
if ($enabled) {
- $modes[] = get_string('mode_'.$mode, 'cache');
+ $modes[] = get_string('mode_' . $mode, 'cache');
}
}
- $supports = array();
+ $supports = [];
foreach ($storesummary['supports'] as $support => $enabled) {
if ($enabled) {
- $supports[] = get_string('supports_'.$support, 'cache');
+ $supports[] = get_string('supports_' . $support, 'cache');
}
}
$info = '';
if (!empty($storesummary['default'])) {
- $info = $this->output->pix_icon('i/info', $defaultstoreactions, '', array('class' => 'icon'));
+ $info = $this->output->pix_icon('i/info', $defaultstoreactions, '', ['class' => 'icon']);
}
$isready = $storesummary['isready'] && $storesummary['requirementsmet'];
- $readycell = new html_table_cell;
+ $readycell = new html_table_cell();
if ($isready) {
$readycell->text = $this->output->pix_icon('i/valid', '1');
}
$storename = $storesummary['name'];
if (!empty($storesummary['default'])) {
- $storename = get_string('store_'.$storesummary['name'], 'cache');
+ $storename = get_string('store_' . $storesummary['name'], 'cache');
}
if (!$isready && (int)$storesummary['mappings'] > 0) {
$readycell->text = $this->output->help_icon('storerequiresattention', 'cache');
@@ -113,24 +112,24 @@ class renderer extends \plugin_renderer_base {
$lock = get_string($storesummary['lock']['name'], 'cache');
}
- $row = new html_table_row(array(
+ $row = new html_table_row([
$storename,
- get_string('pluginname', 'cachestore_'.$storesummary['plugin']),
+ get_string('pluginname', 'cachestore_' . $storesummary['plugin']),
$readycell,
$storesummary['mappings'],
join(', ', $modes),
join(', ', $supports),
$lock,
- $info.join(', ', $htmlactions)
- ));
- $row->attributes['class'] = 'store-'.$name;
+ $info . join(', ', $htmlactions),
+ ]);
+ $row->attributes['class'] = 'store-' . $name;
if ($storesummary['default']) {
$row->attributes['class'] .= ' default-store';
}
$table->data[] = $row;
}
- $html = html_writer::start_tag('div', array('id' => 'core-cache-store-summaries'));
+ $html = html_writer::start_tag('div', ['id' => 'core-cache-store-summaries']);
$html .= $this->output->heading(get_string('storesummaries', 'cache'), 3);
$html .= html_writer::table($table);
$html .= html_writer::end_tag('div');
@@ -146,55 +145,55 @@ class renderer extends \plugin_renderer_base {
*/
public function store_plugin_summaries(array $storepluginsummaries) {
$table = new html_table();
- $table->head = array(
+ $table->head = [
get_string('plugin', 'cache'),
get_string('storeready', 'cache'),
get_string('stores', 'cache'),
get_string('modes', 'cache'),
get_string('supports', 'cache'),
get_string('actions', 'cache'),
- );
- $table->colclasses = array(
+ ];
+ $table->colclasses = [
'plugin',
'storeready',
'stores',
'modes',
'supports',
- 'actions'
- );
- $table->data = array();
+ 'actions',
+ ];
+ $table->data = [];
foreach ($storepluginsummaries as $name => $plugin) {
$htmlactions = cache_factory::get_administration_display_helper()->get_store_plugin_actions($name, $plugin);
- $modes = array();
+ $modes = [];
foreach ($plugin['modes'] as $mode => $enabled) {
if ($enabled) {
- $modes[] = get_string('mode_'.$mode, 'cache');
+ $modes[] = get_string('mode_' . $mode, 'cache');
}
}
- $supports = array();
+ $supports = [];
foreach ($plugin['supports'] as $support => $enabled) {
if ($enabled) {
- $supports[] = get_string('supports_'.$support, 'cache');
+ $supports[] = get_string('supports_' . $support, 'cache');
}
}
- $row = new html_table_row(array(
+ $row = new html_table_row([
$plugin['name'],
($plugin['requirementsmet']) ? $this->output->pix_icon('i/valid', '1') : '',
$plugin['instances'],
join(', ', $modes),
join(', ', $supports),
- join(', ', $htmlactions)
- ));
+ join(', ', $htmlactions),
+ ]);
- $row->attributes['class'] = 'plugin-'.$name;
+ $row->attributes['class'] = 'plugin-' . $name;
$table->data[] = $row;
}
- $html = html_writer::start_tag('div', array('id' => 'core-cache-plugin-summaries'));
+ $html = html_writer::start_tag('div', ['id' => 'core-cache-plugin-summaries']);
$html .= $this->output->heading(get_string('pluginsummaries', 'cache'), 3);
$html .= html_writer::table($table);
$html .= html_writer::end_tag('div');
@@ -212,7 +211,7 @@ class renderer extends \plugin_renderer_base {
*/
public function definition_summaries(array $definitionsummaries, context $context) {
$table = new html_table();
- $table->head = array(
+ $table->head = [
get_string('definition', 'cache'),
get_string('mode', 'cache'),
get_string('component', 'cache'),
@@ -220,9 +219,9 @@ class renderer extends \plugin_renderer_base {
get_string('mappings', 'cache'),
get_string('sharing', 'cache'),
get_string('canuselocalstore', 'cache'),
- get_string('actions', 'cache')
- );
- $table->colclasses = array(
+ get_string('actions', 'cache'),
+ ];
+ $table->colclasses = [
'definition',
'mode',
'component',
@@ -230,9 +229,9 @@ class renderer extends \plugin_renderer_base {
'mappings',
'sharing',
'canuselocalstore',
- 'actions'
- );
- $table->data = array();
+ 'actions',
+ ];
+ $table->data = [];
core_collator::asort_array_of_arrays_by_key($definitionsummaries, 'name');
@@ -242,7 +241,7 @@ class renderer extends \plugin_renderer_base {
if (!empty($definition['mappings'])) {
$mapping = join(', ', $definition['mappings']);
} else {
- $mapping = ''.$none.'';
+ $mapping = '' . $none . '';
}
$uselocalcachecol = get_string('no');
@@ -252,27 +251,27 @@ class renderer extends \plugin_renderer_base {
}
}
- $row = new html_table_row(array(
+ $row = new html_table_row([
$definition['name'],
- get_string('mode_'.$definition['mode'], 'cache'),
+ get_string('mode_' . $definition['mode'], 'cache'),
$definition['component'],
$definition['area'],
$mapping,
join(', ', $definition['selectedsharingoption']),
$uselocalcachecol,
- join(', ', $htmlactions)
- ));
- $row->attributes['class'] = 'definition-'.$definition['component'].'-'.$definition['area'];
+ join(', ', $htmlactions),
+ ]);
+ $row->attributes['class'] = 'definition-' . $definition['component'] . '-' . $definition['area'];
$table->data[] = $row;
}
- $html = html_writer::start_tag('div', array('id' => 'core-cache-definition-summaries'));
+ $html = html_writer::start_tag('div', ['id' => 'core-cache-definition-summaries']);
$html .= $this->output->heading(get_string('definitionsummaries', 'cache'), 3);
$html .= html_writer::table($table);
- $url = new moodle_url('/cache/admin.php', array('action' => 'rescandefinitions', 'sesskey' => sesskey()));
+ $url = new moodle_url('/cache/admin.php', ['action' => 'rescandefinitions', 'sesskey' => sesskey()]);
$link = html_writer::link($url, get_string('rescandefinitions', 'cache'));
- $html .= html_writer::tag('div', $link, array('id' => 'core-cache-rescan-definitions'));
+ $html .= html_writer::tag('div', $link, ['id' => 'core-cache-rescan-definitions']);
$html .= html_writer::end_tag('div');
return $html;
@@ -289,30 +288,30 @@ class renderer extends \plugin_renderer_base {
*/
public function mode_mappings($applicationstore, $sessionstore, $requeststore, moodle_url $editurl) {
$table = new html_table();
- $table->colclasses = array(
+ $table->colclasses = [
'mode',
'mapping',
- );
- $table->rowclasses = array(
+ ];
+ $table->rowclasses = [
'mode_application',
'mode_session',
- 'mode_request'
- );
- $table->head = array(
+ 'mode_request',
+ ];
+ $table->head = [
get_string('mode', 'cache'),
get_string('mappings', 'cache'),
- );
- $table->data = array(
- array(get_string('mode_'.cache_store::MODE_APPLICATION, 'cache'), $applicationstore),
- array(get_string('mode_'.cache_store::MODE_SESSION, 'cache'), $sessionstore),
- array(get_string('mode_'.cache_store::MODE_REQUEST, 'cache'), $requeststore)
- );
+ ];
+ $table->data = [
+ [get_string('mode_' . cache_store::MODE_APPLICATION, 'cache'), $applicationstore],
+ [get_string('mode_' . cache_store::MODE_SESSION, 'cache'), $sessionstore],
+ [get_string('mode_' . cache_store::MODE_REQUEST, 'cache'), $requeststore],
+ ];
- $html = html_writer::start_tag('div', array('id' => 'core-cache-mode-mappings'));
+ $html = html_writer::start_tag('div', ['id' => 'core-cache-mode-mappings']);
$html .= $this->output->heading(get_string('defaultmappings', 'cache'), 3);
$html .= html_writer::table($table);
$link = html_writer::link($editurl, get_string('editmappings', 'cache'));
- $html .= html_writer::tag('div', $link, array('class' => 'edit-link'));
+ $html .= html_writer::tag('div', $link, ['class' => 'edit-link']);
$html .= html_writer::end_tag('div');
return $html;
}
@@ -327,45 +326,45 @@ class renderer extends \plugin_renderer_base {
*/
public function lock_summaries(array $locks) {
$table = new html_table();
- $table->colclasses = array(
+ $table->colclasses = [
'name',
'type',
'default',
'uses',
- 'actions'
- );
- $table->rowclasses = array(
+ 'actions',
+ ];
+ $table->rowclasses = [
'lock_name',
'lock_type',
'lock_default',
'lock_uses',
'lock_actions',
- );
- $table->head = array(
+ ];
+ $table->head = [
get_string('lockname', 'cache'),
get_string('locktype', 'cache'),
get_string('lockdefault', 'cache'),
get_string('lockuses', 'cache'),
- get_string('actions', 'cache')
- );
- $table->data = array();
+ get_string('actions', 'cache'),
+ ];
+ $table->data = [];
$tick = $this->output->pix_icon('i/valid', '');
foreach ($locks as $lock) {
- $actions = array();
+ $actions = [];
if ($lock['uses'] === 0 && !$lock['default']) {
- $url = new moodle_url('/cache/admin.php', array('lock' => $lock['name'], 'action' => 'deletelock'));
+ $url = new moodle_url('/cache/admin.php', ['lock' => $lock['name'], 'action' => 'deletelock']);
$actions[] = html_writer::link($url, get_string('delete', 'cache'));
}
- $table->data[] = new html_table_row(array(
+ $table->data[] = new html_table_row([
new html_table_cell($lock['name']),
new html_table_cell($lock['type']),
new html_table_cell($lock['default'] ? $tick : ''),
new html_table_cell($lock['uses']),
- new html_table_cell(join(' ', $actions))
- ));
+ new html_table_cell(join(' ', $actions)),
+ ]);
}
- $html = html_writer::start_tag('div', array('id' => 'core-cache-lock-summary'));
+ $html = html_writer::start_tag('div', ['id' => 'core-cache-lock-summary']);
$html .= $this->output->heading(get_string('locksummary', 'cache'), 3);
$html .= html_writer::table($table);
$html .= html_writer::end_tag('div');
@@ -378,12 +377,12 @@ class renderer extends \plugin_renderer_base {
* @return string
*/
public function additional_lock_actions(): string {
- $url = new moodle_url('/cache/admin.php', array('action' => 'newlockinstance'));
+ $url = new moodle_url('/cache/admin.php', ['action' => 'newlockinstance']);
$select = new single_select($url, 'lock', cache_factory::get_administration_display_helper()->get_addable_lock_options());
$select->label = get_string('addnewlockinstance', 'cache');
- $html = html_writer::start_tag('div', array('id' => 'core-cache-lock-additional-actions'));
- $html .= html_writer::tag('div', $this->output->render($select), array('class' => 'new-instance'));
+ $html = html_writer::start_tag('div', ['id' => 'core-cache-lock-additional-actions']);
+ $html .= html_writer::tag('div', $this->output->render($select), ['class' => 'new-instance']);
$html .= html_writer::end_tag('div');
return $html;
}
@@ -400,14 +399,14 @@ class renderer extends \plugin_renderer_base {
* @param array $notifications
* @return string
*/
- public function notifications(array $notifications = array()) {
+ public function notifications(array $notifications = []) {
if (count($notifications) === 0) {
// There are no notifications to render.
return '';
}
$html = html_writer::start_div('notifications');
foreach ($notifications as $notification) {
- list($message, $notifysuccess) = $notification;
+ [$message, $notifysuccess] = $notification;
$html .= $this->notification($message, ($notifysuccess) ? 'notifysuccess' : 'notifyproblem');
}
$html .= html_writer::end_div();
@@ -417,7 +416,7 @@ class renderer extends \plugin_renderer_base {
/**
* Creates the two tables which display on the usage page.
*
- * @param array $usage Usage information (from cache_helper::usage)
+ * @param array $usage Usage information (from \core_cache\helper::usage)
* @return array Array of 2 tables (main and summary table)
* @throws \coding_exception
*/
@@ -432,10 +431,10 @@ class renderer extends \plugin_renderer_base {
get_string('usage_mean', 'cache'),
get_string('usage_sd', 'cache'),
get_string('usage_total', 'cache'),
- get_string('usage_totalmargin', 'cache')];
+ get_string('usage_totalmargin', 'cache'), ];
$table->align = [
'left', 'left', 'left',
- 'right', 'right', 'right', 'right', 'right'
+ 'right', 'right', 'right', 'right', 'right',
];
$table->data = [];
@@ -445,7 +444,7 @@ class renderer extends \plugin_renderer_base {
get_string('storename', 'cache'),
get_string('plugin', 'cache'),
get_string('usage_total', 'cache'),
- get_string('usage_realtotal', 'cache')
+ get_string('usage_realtotal', 'cache'),
];
$summarytable->align = [
'left', 'left',
@@ -542,7 +541,7 @@ class renderer extends \plugin_renderer_base {
$data = [
'maintable' => \html_writer::table($maintable),
'summarytable' => \html_writer::table($summarytable),
- 'samplesform' => $samplesform->render()
+ 'samplesform' => $samplesform->render(),
];
return $this->render_from_template('core_cache/usage', $data);
diff --git a/cache/classes/privacy/provider.php b/cache/classes/privacy/provider.php
index 9816123b5fd..6679ed1d34d 100644
--- a/cache/classes/privacy/provider.php
+++ b/cache/classes/privacy/provider.php
@@ -24,9 +24,7 @@
namespace core_cache\privacy;
-defined('MOODLE_INTERNAL') || die();
-
-use \core_privacy\local\metadata\collection;
+use core_privacy\local\metadata\collection;
/**
* Privacy Subsystem implementation for core_cache.
@@ -36,13 +34,12 @@ use \core_privacy\local\metadata\collection;
*/
class provider implements
// Caches store data.
- \core_privacy\local\metadata\provider,
+ \core_privacy\local\metadata\provider,
// The cache subsystem stores data on behalf of other components.
- \core_privacy\local\request\subsystem\plugin_provider,
- \core_privacy\local\request\shared_userlist_provider
- {
-
+ \core_privacy\local\request\subsystem\plugin_provider,
+ \core_privacy\local\request\shared_userlist_provider
+{
/**
* Returns meta data about this system.
*
diff --git a/cache/classes/request_cache.php b/cache/classes/request_cache.php
new file mode 100644
index 00000000000..87874deebbf
--- /dev/null
+++ b/cache/classes/request_cache.php
@@ -0,0 +1,42 @@
+.
+
+namespace core_cache;
+
+/**
+ * An request cache.
+ *
+ * This class is used for request caches returned by the cache::make methods.
+ *
+ * This cache class should never be interacted with directly. Instead you should always use the cache::make methods.
+ * It is technically possible to call those methods through this class however there is no guarantee that you will get an
+ * instance of this class back again.
+ *
+ * @internal don't use me directly.
+ *
+ * @package core_cache
+ * @category cache
+ * @copyright 2012 Sam Hemelryk
+ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+class request_cache extends cache {
+ // This comment appeases code pre-checker ;) !
+}
+
+// Alias this class to the old name.
+// This file will be autoloaded by the legacyclasses autoload system.
+// In future all uses of this class will be corrected and the legacy references will be removed.
+class_alias(request_cache::class, \cache_request::class);
diff --git a/cache/classes/searchable_cache_interface.php b/cache/classes/searchable_cache_interface.php
new file mode 100644
index 00000000000..9f6171b0ea2
--- /dev/null
+++ b/cache/classes/searchable_cache_interface.php
@@ -0,0 +1,48 @@
+.
+
+namespace core_cache;
+
+/**
+ * Cache store feature: keys are searchable.
+ *
+ * Cache stores can choose to implement this interface.
+ * In order for a store to be usable as a session cache it must implement this interface.
+ *
+ * @package core_cache
+ * @copyright Sam Hemelryk
+ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+interface searchable_cache_interface {
+ /**
+ * Finds all of the keys being used by the cache store.
+ *
+ * @return array.
+ */
+ public function find_all();
+
+ /**
+ * Finds all of the keys whose keys start with the given prefix.
+ *
+ * @param string $prefix
+ */
+ public function find_by_prefix($prefix);
+}
+
+// Alias this class to the old name.
+// This file will be autoloaded by the legacyclasses autoload system.
+// In future all uses of this class will be corrected and the legacy references will be removed.
+class_alias(searchable_cache_interface::class, \cache_is_searchable::class);
diff --git a/cache/classes/session_cache.php b/cache/classes/session_cache.php
new file mode 100644
index 00000000000..f00850533ee
--- /dev/null
+++ b/cache/classes/session_cache.php
@@ -0,0 +1,593 @@
+.
+
+namespace core_cache;
+
+use core\exception\coding_exception;
+
+/**
+ * A session cache.
+ *
+ * This class is used for session caches returned by the cache::make methods.
+ *
+ * It differs from the application loader in a couple of noteable ways:
+ * 1. Sessions are always expected to exist.
+ * Because of this we don't ever use the static acceleration array.
+ * 2. Session data for a loader instance (store + definition) is consolidate into a
+ * single array for storage within the store.
+ * Along with this we embed a lastaccessed time with the data. This way we can
+ * check sessions for a last access time.
+ * 3. Session stores are required to support key searching and must
+ * implement searchable_cache_interface. This ensures stores used for the cache can be
+ * targetted for garbage collection of session data.
+ *
+ * This cache class should never be interacted with directly. Instead you should always use the cache::make methods.
+ * It is technically possible to call those methods through this class however there is no guarantee that you will get an
+ * instance of this class back again.
+ *
+ * @todo we should support locking in the session as well. Should be pretty simple to set up.
+ *
+ * @internal don't use me directly.
+ * @method store|searchable_cache_interface get_store() Returns the cache store which must implement
+ * both searchable_cache_interface.
+ *
+ * @package core_cache
+ * @category cache
+ * @copyright 2012 Sam Hemelryk
+ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+class session_cache extends cache {
+ /**
+ * The user the session has been established for.
+ * @var int
+ */
+ protected static $loadeduserid = null;
+
+ /**
+ * The userid this cache is currently using.
+ * @var int
+ */
+ protected $currentuserid = null;
+
+ /**
+ * The session id we are currently using.
+ * @var array
+ */
+ protected $sessionid = null;
+
+ /**
+ * The session data for the above session id.
+ * @var array
+ */
+ protected $session = null;
+
+ /**
+ * Constant used to prefix keys.
+ */
+ const KEY_PREFIX = 'sess_';
+
+ /**
+ * This is the key used to track last access.
+ */
+ const LASTACCESS = '__lastaccess__';
+
+ /**
+ * Override the cache::construct method.
+ *
+ * This function gets overriden so that we can process any invalidation events if need be.
+ * If the definition doesn't have any invalidation events then this occurs exactly as it would for the cache class.
+ * Otherwise we look at the last invalidation time and then check the invalidation data for events that have occured
+ * between then now.
+ *
+ * You should not call this method from your code, instead you should use the cache::make methods.
+ *
+ * @param definition $definition
+ * @param store $store
+ * @param loader_interface|data_source_interface $loader
+ */
+ public function __construct(definition $definition, store $store, $loader = null) {
+ // First up copy the loadeduserid to the current user id.
+ $this->currentuserid = self::$loadeduserid;
+ $this->set_session_id();
+ parent::__construct($definition, $store, $loader);
+
+ // This will trigger check tracked user. If this gets removed a call to that will need to be added here in its place.
+ $this->set(self::LASTACCESS, cache::now());
+
+ $this->handle_invalidation_events();
+ }
+
+ /**
+ * Sets the session id for the loader.
+ */
+ protected function set_session_id() {
+ $this->sessionid = preg_replace('#[^a-zA-Z0-9_]#', '_', session_id());
+ }
+
+ /**
+ * Returns the prefix used for all keys.
+ * @return string
+ */
+ protected function get_key_prefix() {
+ return 'u' . $this->currentuserid . '_' . $this->sessionid;
+ }
+
+ /**
+ * Parses the key turning it into a string (or array is required) suitable to be passed to the cache store.
+ *
+ * This function is called for every operation that uses keys. For this reason we use this function to also check
+ * that the current user is the same as the user who last used this cache.
+ *
+ * On top of that if prepends the string 'sess_' to the start of all keys. The _ ensures things are easily identifiable.
+ *
+ * @param string|int $key As passed to get|set|delete etc.
+ * @return string|array String unless the store supports multi-identifiers in which case an array if returned.
+ */
+ protected function parse_key($key) {
+ $prefix = $this->get_key_prefix();
+ if ($key === self::LASTACCESS) {
+ return $key . $prefix;
+ }
+ return $prefix . '_' . parent::parse_key($key);
+ }
+
+ /**
+ * Check that this cache instance is tracking the current user.
+ */
+ protected function check_tracked_user() {
+ if (isset($_SESSION['USER']->id) && $_SESSION['USER']->id !== null) {
+ // Get the id of the current user.
+ $new = $_SESSION['USER']->id;
+ } else {
+ // No user set up yet.
+ $new = 0;
+ }
+ if ($new !== self::$loadeduserid) {
+ // The current user doesn't match the tracked userid for this request.
+ if (!is_null(self::$loadeduserid)) {
+ // Purge the data we have for the old user.
+ // This way we don't bloat the session.
+ $this->purge();
+ }
+ self::$loadeduserid = $new;
+ $this->currentuserid = $new;
+ } else if ($new !== $this->currentuserid) {
+ // The current user matches the loaded user but not the user last used by this cache.
+ $this->purge_current_user();
+ $this->currentuserid = $new;
+ }
+ }
+
+ /**
+ * Purges the session cache of all data belonging to the current user.
+ */
+ public function purge_current_user() {
+ $keys = $this->get_store()->find_by_prefix($this->get_key_prefix());
+ $this->get_store()->delete_many($keys);
+ }
+
+ /**
+ * Retrieves the value for the given key from the cache.
+ *
+ * @param string|int $key The key for the data being requested.
+ * It can be any structure although using a scalar string or int is recommended in the interests of performance.
+ * In advanced cases an array may be useful such as in situations requiring the multi-key functionality.
+ * @param int $requiredversion Minimum required version of the data or cache::VERSION_NONE
+ * @param int $strictness One of IGNORE_MISSING | MUST_EXIST
+ * @param mixed &$actualversion If specified, will be set to the actual version number retrieved
+ * @return mixed|false The data from the cache or false if the key did not exist within the cache.
+ * @throws coding_exception
+ */
+ protected function get_implementation($key, int $requiredversion, int $strictness, &$actualversion = null) {
+ // Check the tracked user.
+ $this->check_tracked_user();
+
+ // Use parent code.
+ return parent::get_implementation($key, $requiredversion, $strictness, $actualversion);
+ }
+
+ /**
+ * Sends a key => value pair to the cache.
+ *
+ *
+ * // This code will add four entries to the cache, one for each url.
+ * $cache->set('main', 'http://moodle.org');
+ * $cache->set('docs', 'http://docs.moodle.org');
+ * $cache->set('tracker', 'http://tracker.moodle.org');
+ * $cache->set('qa', 'http://qa.moodle.net');
+ *
+ *
+ * @param string|int $key The key for the data being requested.
+ * It can be any structure although using a scalar string or int is recommended in the interests of performance.
+ * In advanced cases an array may be useful such as in situations requiring the multi-key functionality.
+ * @param mixed $data The data to set against the key.
+ * @return bool True on success, false otherwise.
+ */
+ public function set($key, $data) {
+ $this->check_tracked_user();
+ $loader = $this->get_loader();
+ if ($loader !== false) {
+ // We have a loader available set it there as well.
+ // We have to let the loader do its own parsing of data as it may be unique.
+ $loader->set($key, $data);
+ }
+ if (is_object($data) && $data instanceof cacheable_object_interface) {
+ $data = new cached_object($data);
+ } else if (!$this->get_store()->supports_dereferencing_objects() && !is_scalar($data)) {
+ // If data is an object it will be a reference.
+ // If data is an array if may contain references.
+ // We want to break references so that the cache cannot be modified outside of itself.
+ // Call the function to unreference it (in the best way possible).
+ $data = $this->unref($data);
+ }
+ // We dont' support native TTL here as we consolidate data for sessions.
+ if ($this->has_a_ttl() && !$this->store_supports_native_ttl()) {
+ $data = new ttl_wrapper($data, $this->get_definition()->get_ttl());
+ }
+ $success = $this->get_store()->set($this->parse_key($key), $data);
+ if ($this->perfdebug) {
+ helper::record_cache_set(
+ $this->get_store(),
+ $this->get_definition(),
+ 1,
+ $this->get_store()->get_last_io_bytes()
+ );
+ }
+ return $success;
+ }
+
+ /**
+ * Delete the given key from the cache.
+ *
+ * @param string|int $key The key to delete.
+ * @param bool $recurse When set to true the key will also be deleted from all stacked cache loaders and their stores.
+ * This happens by default and ensure that all the caches are consistent. It is NOT recommended to change this.
+ * @return bool True of success, false otherwise.
+ */
+ public function delete($key, $recurse = true) {
+ $parsedkey = $this->parse_key($key);
+ if ($recurse && $this->get_loader() !== false) {
+ // Delete from the bottom of the stack first.
+ $this->get_loader()->delete($key, $recurse);
+ }
+ return $this->get_store()->delete($parsedkey);
+ }
+
+ /**
+ * Retrieves an array of values for an array of keys.
+ *
+ * Using this function comes with potential performance implications.
+ * Not all cache stores will support get_many/set_many operations and in order to replicate this functionality will call
+ * the equivalent singular method for each item provided.
+ * This should not deter you from using this function as there is a performance benefit in situations where the cache store
+ * does support it, but you should be aware of this fact.
+ *
+ * @param array $keys The keys of the data being requested.
+ * Each key can be any structure although using a scalar string or int is recommended in the interests of performance.
+ * In advanced cases an array may be useful such as in situations requiring the multi-key functionality.
+ * @param int $strictness One of IGNORE_MISSING or MUST_EXIST.
+ * @return array An array of key value pairs for the items that could be retrieved from the cache.
+ * If MUST_EXIST was used and not all keys existed within the cache then an exception will be thrown.
+ * Otherwise any key that did not exist will have a data value of false within the results.
+ * @throws coding_exception
+ */
+ public function get_many(array $keys, $strictness = IGNORE_MISSING) {
+ $this->check_tracked_user();
+ $parsedkeys = [];
+ $keymap = [];
+ foreach ($keys as $key) {
+ $parsedkey = $this->parse_key($key);
+ $parsedkeys[$key] = $parsedkey;
+ $keymap[$parsedkey] = $key;
+ }
+ $result = $this->get_store()->get_many($parsedkeys);
+ if ($this->perfdebug) {
+ $readbytes = $this->get_store()->get_last_io_bytes();
+ }
+ $return = [];
+ $missingkeys = [];
+ $hasmissingkeys = false;
+ foreach ($result as $parsedkey => $value) {
+ $key = $keymap[$parsedkey];
+ if ($value instanceof ttl_wrapper) {
+ /* @var ttl_wrapper $value */
+ if ($value->has_expired()) {
+ $this->delete($keymap[$parsedkey]);
+ $value = false;
+ } else {
+ $value = $value->data;
+ }
+ }
+ if ($value instanceof cached_object) {
+ /* @var cached_object $value */
+ $value = $value->restore_object();
+ } else if (!$this->get_store()->supports_dereferencing_objects() && !is_scalar($value)) {
+ // If data is an object it will be a reference.
+ // If data is an array if may contain references.
+ // We want to break references so that the cache cannot be modified outside of itself.
+ // Call the function to unreference it (in the best way possible).
+ $value = $this->unref($value);
+ }
+ $return[$key] = $value;
+ if ($value === false) {
+ $hasmissingkeys = true;
+ $missingkeys[$parsedkey] = $key;
+ }
+ }
+ if ($hasmissingkeys) {
+ // We've got missing keys - we've got to check any loaders or data sources.
+ $loader = $this->get_loader();
+ $datasource = $this->get_datasource();
+ if ($loader !== false) {
+ foreach ($loader->get_many($missingkeys) as $key => $value) {
+ if ($value !== false) {
+ $return[$key] = $value;
+ unset($missingkeys[$parsedkeys[$key]]);
+ }
+ }
+ }
+ $hasmissingkeys = count($missingkeys) > 0;
+ if ($datasource !== false && $hasmissingkeys) {
+ // We're still missing keys but we've got a datasource.
+ foreach ($datasource->load_many_for_cache($missingkeys) as $key => $value) {
+ if ($value !== false) {
+ $return[$key] = $value;
+ unset($missingkeys[$parsedkeys[$key]]);
+ }
+ }
+ $hasmissingkeys = count($missingkeys) > 0;
+ }
+ }
+ if ($hasmissingkeys && $strictness === MUST_EXIST) {
+ throw new coding_exception('Requested key did not exist in any cache stores and could not be loaded.');
+ }
+ if ($this->perfdebug) {
+ $hits = 0;
+ $misses = 0;
+ foreach ($return as $value) {
+ if ($value === false) {
+ $misses++;
+ } else {
+ $hits++;
+ }
+ }
+ helper::record_cache_hit($this->get_store(), $this->get_definition(), $hits, $readbytes);
+ helper::record_cache_miss($this->get_store(), $this->get_definition(), $misses);
+ }
+ return $return;
+ }
+
+ /**
+ * Delete all of the given keys from the cache.
+ *
+ * @param array $keys The key to delete.
+ * @param bool $recurse When set to true the key will also be deleted from all stacked cache loaders and their stores.
+ * This happens by default and ensure that all the caches are consistent. It is NOT recommended to change this.
+ * @return int The number of items successfully deleted.
+ */
+ public function delete_many(array $keys, $recurse = true) {
+ $parsedkeys = array_map([$this, 'parse_key'], $keys);
+ if ($recurse && $this->get_loader() !== false) {
+ // Delete from the bottom of the stack first.
+ $this->get_loader()->delete_many($keys, $recurse);
+ }
+ return $this->get_store()->delete_many($parsedkeys);
+ }
+
+ /**
+ * Sends several key => value pairs to the cache.
+ *
+ * Using this function comes with potential performance implications.
+ * Not all cache stores will support get_many/set_many operations and in order to replicate this functionality will call
+ * the equivalent singular method for each item provided.
+ * This should not deter you from using this function as there is a performance benefit in situations where the cache store
+ * does support it, but you should be aware of this fact.
+ *
+ *
+ * // This code will add four entries to the cache, one for each url.
+ * $cache->set_many(array(
+ * 'main' => 'http://moodle.org',
+ * 'docs' => 'http://docs.moodle.org',
+ * 'tracker' => 'http://tracker.moodle.org',
+ * 'qa' => ''http://qa.moodle.net'
+ * ));
+ *
+ *
+ * @param array $keyvaluearray An array of key => value pairs to send to the cache.
+ * @return int The number of items successfully set. It is up to the developer to check this matches the number of items.
+ * ... if they care that is.
+ */
+ public function set_many(array $keyvaluearray) {
+ $this->check_tracked_user();
+ $loader = $this->get_loader();
+ if ($loader !== false) {
+ // We have a loader available set it there as well.
+ // We have to let the loader do its own parsing of data as it may be unique.
+ $loader->set_many($keyvaluearray);
+ }
+ $data = [];
+ $definitionid = $this->get_definition()->get_ttl();
+ $simulatettl = $this->has_a_ttl() && !$this->store_supports_native_ttl();
+ foreach ($keyvaluearray as $key => $value) {
+ if (is_object($value) && $value instanceof cacheable_object_interface) {
+ $value = new cached_object($value);
+ } else if (!$this->get_store()->supports_dereferencing_objects() && !is_scalar($value)) {
+ // If data is an object it will be a reference.
+ // If data is an array if may contain references.
+ // We want to break references so that the cache cannot be modified outside of itself.
+ // Call the function to unreference it (in the best way possible).
+ $value = $this->unref($value);
+ }
+ if ($simulatettl) {
+ $value = new ttl_wrapper($value, $definitionid);
+ }
+ $data[$key] = [
+ 'key' => $this->parse_key($key),
+ 'value' => $value,
+ ];
+ }
+ $successfullyset = $this->get_store()->set_many($data);
+ if ($this->perfdebug && $successfullyset) {
+ helper::record_cache_set(
+ $this->get_store(),
+ $this->get_definition(),
+ $successfullyset,
+ $this->get_store()->get_last_io_bytes()
+ );
+ }
+ return $successfullyset;
+ }
+
+ /**
+ * Purges the cache store, and loader if there is one.
+ *
+ * @return bool True on success, false otherwise
+ */
+ public function purge() {
+ $this->get_store()->purge();
+ if ($this->get_loader()) {
+ $this->get_loader()->purge();
+ }
+ return true;
+ }
+
+ /**
+ * Test is a cache has a key.
+ *
+ * The use of the has methods is strongly discouraged. In a high load environment the cache may well change between the
+ * test and any subsequent action (get, set, delete etc).
+ * Instead it is recommended to write your code in such a way they it performs the following steps:
+ *
+ * - Attempt to retrieve the information.
+ * - Generate the information.
+ * - Attempt to set the information
+ *
+ *
+ * Its also worth mentioning that not all stores support key tests.
+ * For stores that don't support key tests this functionality is mimicked by using the equivalent get method.
+ * Just one more reason you should not use these methods unless you have a very good reason to do so.
+ *
+ * @param string|int $key
+ * @param bool $tryloadifpossible If set to true, the cache doesn't contain the key, and there is another cache loader or
+ * data source then the code will try load the key value from the next item in the chain.
+ * @return bool True if the cache has the requested key, false otherwise.
+ */
+ public function has($key, $tryloadifpossible = false) {
+ $this->check_tracked_user();
+ $parsedkey = $this->parse_key($key);
+ $store = $this->get_store();
+ if ($this->has_a_ttl() && !$this->store_supports_native_ttl()) {
+ // The data has a TTL and the store doesn't support it natively.
+ // We must fetch the data and expect a ttl wrapper.
+ $data = $store->get($parsedkey);
+ $has = ($data instanceof ttl_wrapper && !$data->has_expired());
+ } else if (!$this->store_supports_key_awareness()) {
+ // The store doesn't support key awareness, get the data and check it manually... puke.
+ // Either no TTL is set of the store supports its handling natively.
+ $data = $store->get($parsedkey);
+ $has = ($data !== false);
+ } else {
+ // The store supports key awareness, this is easy!
+ // Either no TTL is set of the store supports its handling natively.
+ /* @var store|key_aware_cache_interface $store */
+ $has = $store->has($parsedkey);
+ }
+ if (!$has && $tryloadifpossible) {
+ $result = null;
+ if ($this->get_loader() !== false) {
+ $result = $this->get_loader()->get($parsedkey);
+ } else if ($this->get_datasource() !== null) {
+ $result = $this->get_datasource()->load_for_cache($key);
+ }
+ $has = ($result !== null);
+ if ($has) {
+ $this->set($key, $result);
+ }
+ }
+ return $has;
+ }
+
+ /**
+ * Test is a cache has all of the given keys.
+ *
+ * It is strongly recommended to avoid the use of this function if not absolutely required.
+ * In a high load environment the cache may well change between the test and any subsequent action (get, set, delete etc).
+ *
+ * Its also worth mentioning that not all stores support key tests.
+ * For stores that don't support key tests this functionality is mimicked by using the equivalent get method.
+ * Just one more reason you should not use these methods unless you have a very good reason to do so.
+ *
+ * @param array $keys
+ * @return bool True if the cache has all of the given keys, false otherwise.
+ */
+ public function has_all(array $keys) {
+ $this->check_tracked_user();
+ if (($this->has_a_ttl() && !$this->store_supports_native_ttl()) || !$this->store_supports_key_awareness()) {
+ foreach ($keys as $key) {
+ if (!$this->has($key)) {
+ return false;
+ }
+ }
+ return true;
+ }
+ // The cache must be key aware and if support native ttl if it a ttl is set.
+ /* @var store|key_aware_cache_interface $store */
+ $store = $this->get_store();
+ return $store->has_all(array_map([$this, 'parse_key'], $keys));
+ }
+
+ /**
+ * Test if a cache has at least one of the given keys.
+ *
+ * It is strongly recommended to avoid the use of this function if not absolutely required.
+ * In a high load environment the cache may well change between the test and any subsequent action (get, set, delete etc).
+ *
+ * Its also worth mentioning that not all stores support key tests.
+ * For stores that don't support key tests this functionality is mimicked by using the equivalent get method.
+ * Just one more reason you should not use these methods unless you have a very good reason to do so.
+ *
+ * @param array $keys
+ * @return bool True if the cache has at least one of the given keys
+ */
+ public function has_any(array $keys) {
+ if (($this->has_a_ttl() && !$this->store_supports_native_ttl()) || !$this->store_supports_key_awareness()) {
+ foreach ($keys as $key) {
+ if ($this->has($key)) {
+ return true;
+ }
+ }
+ return false;
+ }
+ /* @var store|key_aware_cache_interface $store */
+ $store = $this->get_store();
+ return $store->has_any(array_map([$this, 'parse_key'], $keys));
+ }
+
+ /**
+ * The session loader never uses static acceleration.
+ * Instead it stores things in the static $session variable. Shared between all session loaders.
+ *
+ * @return bool
+ */
+ protected function use_static_acceleration() {
+ return false;
+ }
+}
+
+// Alias this class to the old name.
+// This file will be autoloaded by the legacyclasses autoload system.
+// In future all uses of this class will be corrected and the legacy references will be removed.
+class_alias(session_cache::class, \cache_session::class);
diff --git a/cache/classes/store.php b/cache/classes/store.php
index 0190b1da82a..65098eca361 100644
--- a/cache/classes/store.php
+++ b/cache/classes/store.php
@@ -14,79 +14,10 @@
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see .
-/**
- * Cache store - base class
- *
- * This file is part of Moodle's cache API, affectionately called MUC.
- * It contains the components that are required in order to use caching.
- *
- * @package core
- * @category cache
- * @copyright 2012 Sam Hemelryk
- * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
- */
+namespace core_cache;
-defined('MOODLE_INTERNAL') || die();
-
-/**
- * Cache store interface.
- *
- * This interface defines the static methods that must be implemented by every cache store plugin.
- * To ensure plugins implement this class the abstract cache_store class implements this interface.
- *
- * @package core
- * @category cache
- * @copyright 2012 Sam Hemelryk
- * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
- */
-interface cache_store_interface {
- /**
- * Static method to check if the store requirements are met.
- *
- * @return bool True if the stores software/hardware requirements have been met and it can be used. False otherwise.
- */
- public static function are_requirements_met();
-
- /**
- * Static method to check if a store is usable with the given mode.
- *
- * @param int $mode One of cache_store::MODE_*
- */
- public static function is_supported_mode($mode);
-
- /**
- * Returns the supported features as a binary flag.
- *
- * @param array $configuration The configuration of a store to consider specifically.
- * @return int The supported features.
- */
- public static function get_supported_features(array $configuration = array());
-
- /**
- * Returns the supported modes as a binary flag.
- *
- * @param array $configuration The configuration of a store to consider specifically.
- * @return int The supported modes.
- */
- public static function get_supported_modes(array $configuration = array());
-
- /**
- * Generates an instance of the cache store that can be used for testing.
- *
- * Returns an instance of the cache store, or false if one cannot be created.
- *
- * @param cache_definition $definition
- * @return cache_store|false
- */
- public static function initialise_test_instance(cache_definition $definition);
-
- /**
- * Generates the appropriate configuration required for unit testing.
- *
- * @return array Array of unit test configuration data to be used by initialise().
- */
- public static function unit_test_configuration();
-}
+use core\exception\coding_exception;
+use stdClass;
/**
* Abstract cache store class.
@@ -95,13 +26,12 @@ interface cache_store_interface {
* It lays down the foundation for what is required of a cache store plugin.
*
* @since Moodle 2.4
- * @package core
+ * @package core_cache
* @category cache
* @copyright 2012 Sam Hemelryk
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
-abstract class cache_store implements cache_store_interface {
-
+abstract class store implements store_interface {
// Constants for features a cache store can support
/**
@@ -171,7 +101,7 @@ abstract class cache_store implements cache_store_interface {
* @param string $name The name of the cache store
* @param array $configuration The configuration for this store instance.
*/
- abstract public function __construct($name, array $configuration = array());
+ abstract public function __construct($name, array $configuration = []);
/**
* Returns the name of this store instance.
@@ -189,9 +119,9 @@ abstract class cache_store implements cache_store_interface {
* If there are setup tasks that may fail they should be done within the __construct method
* and should they fail is_ready should return false.
*
- * @param cache_definition $definition
+ * @param definition $definition
*/
- abstract public function initialise(cache_definition $definition);
+ abstract public function initialise(definition $definition);
/**
* Returns true if this cache store instance has been initialised.
@@ -204,7 +134,7 @@ abstract class cache_store implements cache_store_interface {
* @return bool
*/
public function is_ready() {
- return forward_static_call(array($this, 'are_requirements_met'));
+ return forward_static_call([$this, 'are_requirements_met']);
}
/**
@@ -270,11 +200,11 @@ abstract class cache_store implements cache_store_interface {
/**
* @deprecated since 2.5
- * @see \cache_store::instance_deleted()
+ * @see store::instance_deleted()
*/
public function cleanup() {
- throw new coding_exception('cache_store::cleanup() can not be used anymore.' .
- ' Please use cache_store::instance_deleted() instead.');
+ throw new coding_exception('store::cleanup() can not be used anymore.' .
+ ' Please use store::instance_deleted() instead.');
}
/**
@@ -344,7 +274,7 @@ abstract class cache_store implements cache_store_interface {
* @return bool
*/
public function is_searchable() {
- return in_array('cache_is_searchable', class_implements($this));
+ return ($this instanceof searchable_cache_interface);
}
/**
@@ -366,9 +296,9 @@ abstract class cache_store implements cache_store_interface {
* you can override this method to handle any situations you want before cloning.
*
* @param array $details An array containing the details of the store from the cache config.
- * @return cache_store
+ * @return store
*/
- public function create_clone(array $details = array()) {
+ public function create_clone(array $details = []) {
// By default we just run clone.
// Any stores that have an issue with this will need to override the create_clone method.
return clone($this);
@@ -383,7 +313,7 @@ abstract class cache_store implements cache_store_interface {
* @return string[] An array of warning strings from the store instance.
*/
public function get_warnings() {
- return array();
+ return [];
}
/**
@@ -446,7 +376,7 @@ abstract class cache_store implements cache_store_interface {
'items' => 0,
'mean' => 0,
'sd' => 0,
- 'margin' => 0
+ 'margin' => 0,
];
// If this cache isn't searchable, we don't know the answer.
@@ -534,3 +464,8 @@ abstract class cache_store implements cache_store_interface {
return self::IO_BYTES_NOT_SUPPORTED;
}
}
+
+// Alias this class to the old name.
+// This file will be autoloaded by the legacyclasses autoload system.
+// In future all uses of this class will be corrected and the legacy references will be removed.
+class_alias(store::class, \cache_store::class);
diff --git a/cache/classes/store_interface.php b/cache/classes/store_interface.php
new file mode 100644
index 00000000000..2095c23bdcd
--- /dev/null
+++ b/cache/classes/store_interface.php
@@ -0,0 +1,82 @@
+.
+
+namespace core_cache;
+
+/**
+ * Cache store interface.
+ *
+ * This interface defines the static methods that must be implemented by every cache store plugin.
+ * To ensure plugins implement this class the abstract store class implements this interface.
+ *
+ * @package core_cache
+ * @category cache
+ * @copyright 2012 Sam Hemelryk
+ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+interface store_interface {
+ /**
+ * Static method to check if the store requirements are met.
+ *
+ * @return bool True if the stores software/hardware requirements have been met and it can be used. False otherwise.
+ */
+ public static function are_requirements_met();
+
+ /**
+ * Static method to check if a store is usable with the given mode.
+ *
+ * @param int $mode One of store::MODE_*
+ */
+ public static function is_supported_mode($mode);
+
+ /**
+ * Returns the supported features as a binary flag.
+ *
+ * @param array $configuration The configuration of a store to consider specifically.
+ * @return int The supported features.
+ */
+ public static function get_supported_features(array $configuration = []);
+
+ /**
+ * Returns the supported modes as a binary flag.
+ *
+ * @param array $configuration The configuration of a store to consider specifically.
+ * @return int The supported modes.
+ */
+ public static function get_supported_modes(array $configuration = []);
+
+ /**
+ * Generates an instance of the cache store that can be used for testing.
+ *
+ * Returns an instance of the cache store, or false if one cannot be created.
+ *
+ * @param definition $definition
+ * @return store_interface|false
+ */
+ public static function initialise_test_instance(definition $definition);
+
+ /**
+ * Generates the appropriate configuration required for unit testing.
+ *
+ * @return array Array of unit test configuration data to be used by initialise().
+ */
+ public static function unit_test_configuration();
+}
+
+// Alias this class to the old name.
+// This file will be autoloaded by the legacyclasses autoload system.
+// In future all uses of this class will be corrected and the legacy references will be removed.
+class_alias(store_interface::class, \cache_store_interface::class);
diff --git a/cache/classes/ttl_wrapper.php b/cache/classes/ttl_wrapper.php
new file mode 100644
index 00000000000..2a98e9df8e8
--- /dev/null
+++ b/cache/classes/ttl_wrapper.php
@@ -0,0 +1,65 @@
+.
+
+namespace core_cache;
+
+/**
+ * A wrapper class used to handle ttl when the cache store doesn't natively support it.
+ *
+ * This class is exactly why you should use event driving invalidation of cache data rather than relying on ttl.
+ *
+ * @package core_cache
+ * @category cache
+ * @copyright 2012 Sam Hemelryk
+ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+class ttl_wrapper {
+ /**
+ * The data being stored.
+ * @var mixed
+ */
+ public $data;
+
+ /**
+ * When the cache data expires as a timestamp.
+ * @var int
+ */
+ public $expires;
+
+ /**
+ * Constructs a ttl cache wrapper.
+ *
+ * @param mixed $data
+ * @param int $ttl The time to live in seconds.
+ */
+ public function __construct($data, $ttl) {
+ $this->data = $data;
+ $this->expires = cache::now() + (int)$ttl;
+ }
+
+ /**
+ * Returns true if the data has expired.
+ * @return int
+ */
+ public function has_expired() {
+ return ($this->expires < cache::now());
+ }
+}
+
+// Alias this class to the old name.
+// This file will be autoloaded by the legacyclasses autoload system.
+// In future all uses of this class will be corrected and the legacy references will be removed.
+class_alias(ttl_wrapper::class, \cache_ttl_wrapper::class);
diff --git a/cache/classes/version_wrapper.php b/cache/classes/version_wrapper.php
index 875ee6156b0..36b8f5d1e6e 100644
--- a/cache/classes/version_wrapper.php
+++ b/cache/classes/version_wrapper.php
@@ -24,7 +24,6 @@ namespace core_cache;
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class version_wrapper {
-
/**
* The data being stored.
* @var mixed
diff --git a/cache/classes/versionable_data_source_interface.php b/cache/classes/versionable_data_source_interface.php
new file mode 100644
index 00000000000..837071507cf
--- /dev/null
+++ b/cache/classes/versionable_data_source_interface.php
@@ -0,0 +1,50 @@
+.
+
+namespace core_cache;
+
+/**
+ * Versionable cache data source.
+ *
+ * This interface extends the main cache data source interface to add an extra required method if
+ * the data source is to be used for a versioned cache.
+ *
+ * @package core_cache
+ * @copyright Sam Hemelryk
+ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+interface versionable_data_source_interface extends data_source_interface {
+ /**
+ * Loads the data for the key provided ready formatted for caching.
+ *
+ * If there is no data for that key, or if the data for the required key has an older version
+ * than the specified $requiredversion, then this returns null.
+ *
+ * If there is data then $actualversion should be set to the actual version number retrieved
+ * (may be the same as $requiredversion or newer).
+ *
+ * @param string|int $key The key to load.
+ * @param int $requiredversion Minimum required version
+ * @param mixed $actualversion Should be set to the actual version number retrieved
+ * @return mixed What ever data should be returned, or false if it can't be loaded.
+ */
+ public function load_for_cache_versioned($key, int $requiredversion, &$actualversion);
+}
+
+// Alias this class to the old name.
+// This file will be autoloaded by the legacyclasses autoload system.
+// In future all uses of this class will be corrected and the legacy references will be removed.
+class_alias(versionable_data_source_interface::class, \cache_data_source_versionable::class);
diff --git a/cache/disabledlib.php b/cache/disabledlib.php
deleted file mode 100644
index 3538d1ed648..00000000000
--- a/cache/disabledlib.php
+++ /dev/null
@@ -1,608 +0,0 @@
-.
-
-/**
- * This file contains classes that are used by the Cache API only when it is disabled.
- *
- * These classes are derivatives of other significant classes used by the Cache API customised specifically
- * to only do what is absolutely necessary when initialising and using the Cache API when its been disabled.
- *
- * @package core
- * @category cache
- * @copyright 2012 Sam Hemelryk
- * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
- */
-
-defined('MOODLE_INTERNAL') || die();
-
-/**
- * Required as it is needed for cache_config_disabled which extends cache_config_writer.
- */
-require_once($CFG->dirroot.'/cache/locallib.php');
-
-/**
- * The cache loader class used when the Cache has been disabled.
- *
- * @copyright 2012 Sam Hemelryk
- * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
- */
-class cache_disabled extends cache implements cache_loader_with_locking {
-
- /**
- * Constructs the cache.
- *
- * @param cache_definition $definition
- * @param cache_store $store
- * @param null $loader Unused.
- */
- public function __construct(cache_definition $definition, cache_store $store, $loader = null) {
- if ($loader instanceof cache_data_source) {
- // Set the data source to allow data sources to work when caching is entirely disabled.
- $this->set_data_source($loader);
- }
-
- // No other features are handled.
- }
-
- /**
- * Gets a key from the cache.
- *
- * @param int|string $key
- * @param int $requiredversion Minimum required version of the data or cache::VERSION_NONE
- * @param int $strictness Unused.
- * @param mixed &$actualversion If specified, will be set to the actual version number retrieved
- * @return bool
- */
- protected function get_implementation($key, int $requiredversion, int $strictness, &$actualversion = null) {
- $datasource = $this->get_datasource();
- if ($datasource !== false) {
- if ($requiredversion === cache::VERSION_NONE) {
- return $datasource->load_for_cache($key);
- } else {
- if (!$datasource instanceof cache_data_source_versionable) {
- throw new \coding_exception('Data source is not versionable');
- }
- $result = $datasource->load_for_cache_versioned($key, $requiredversion, $actualversion);
- if ($result && $actualversion < $requiredversion) {
- throw new \coding_exception('Data source returned outdated version');
- }
- return $result;
- }
- }
- return false;
- }
-
- /**
- * Gets many keys at once from the cache.
- *
- * @param array $keys
- * @param int $strictness Unused.
- * @return array
- */
- public function get_many(array $keys, $strictness = IGNORE_MISSING) {
- if ($this->get_datasource() !== false) {
- return $this->get_datasource()->load_many_for_cache($keys);
- }
-
- return array_combine($keys, array_fill(0, count($keys), false));
- }
-
- /**
- * Sets a key value pair in the cache.
- *
- * @param int|string $key Unused.
- * @param int $version Unused.
- * @param mixed $data Unused.
- * @param bool $setparents Unused.
- * @return bool
- */
- protected function set_implementation($key, int $version, $data, bool $setparents = true): bool {
- return false;
- }
-
- /**
- * Sets many key value pairs in the cache at once.
- *
- * @param array $keyvaluearray Unused.
- * @return int
- */
- public function set_many(array $keyvaluearray) {
- return 0;
- }
-
- /**
- * Deletes an item from the cache.
- *
- * @param int|string $key Unused.
- * @param bool $recurse Unused.
- * @return bool
- */
- public function delete($key, $recurse = true) {
- return false;
- }
-
- /**
- * Deletes many items at once from the cache.
- *
- * @param array $keys Unused.
- * @param bool $recurse Unused.
- * @return int
- */
- public function delete_many(array $keys, $recurse = true) {
- return 0;
- }
-
- /**
- * Checks if the cache has the requested key.
- *
- * @param int|string $key Unused.
- * @param bool $tryloadifpossible Unused.
- * @return bool
- */
- public function has($key, $tryloadifpossible = false) {
- $result = $this->get($key);
-
- return $result !== false;
- }
-
- /**
- * Checks if the cache has all of the requested keys.
- * @param array $keys Unused.
- * @return bool
- */
- public function has_all(array $keys) {
- if (!$this->get_datasource()) {
- return false;
- }
-
- foreach ($keys as $key) {
- if (!$this->has($key)) {
- return false;
- }
- }
- return true;
- }
-
- /**
- * Checks if the cache has any of the requested keys.
- *
- * @param array $keys Unused.
- * @return bool
- */
- public function has_any(array $keys) {
- foreach ($keys as $key) {
- if ($this->has($key)) {
- return true;
- }
- }
-
- return false;
- }
-
- /**
- * Purges all items from the cache.
- *
- * @return bool
- */
- public function purge() {
- return true;
- }
-
- /**
- * Pretend that we got a lock to avoid errors.
- *
- * @param int|string $key
- * @return bool
- */
- public function acquire_lock($key): bool {
- return true;
- }
-
- /**
- * Pretend that we released a lock to avoid errors.
- *
- * @param int|string $key
- * @return bool
- */
- public function release_lock($key): bool {
- return true;
- }
-
- /**
- * Pretend that we have a lock to avoid errors.
- *
- * @param int|string $key
- * @return bool
- */
- public function check_lock_state($key): bool {
- return true;
- }
-}
-
-/**
- * The cache factory class used when the Cache has been disabled.
- *
- * @copyright 2012 Sam Hemelryk
- * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
- */
-class cache_factory_disabled extends cache_factory {
- /** @var array Array of temporary caches in use. */
- protected static $tempcaches = [];
-
- /**
- * Returns an instance of the cache_factor method.
- *
- * @param bool $forcereload Unused.
- * @return cache_factory
- * @throws coding_exception
- */
- public static function instance($forcereload = false) {
- throw new coding_exception('You must not call to this cache factory within your code.');
- }
-
- /**
- * Creates a definition instance or returns the existing one if it has already been created.
- *
- * @param string $component
- * @param string $area
- * @param string $unused Used to be datasourceaggregate but that was removed and this is now unused.
- * @return cache_definition
- */
- public function create_definition($component, $area, $unused = null) {
- $definition = parent::create_definition($component, $area);
- if ($definition->has_data_source()) {
- return $definition;
- }
-
- return cache_definition::load_adhoc(cache_store::MODE_REQUEST, $component, $area);
- }
-
- /**
- * Common public method to create a cache instance given a definition.
- *
- * @param cache_definition $definition
- * @return cache_application|cache_session|cache_store
- * @throws coding_exception
- */
- public function create_cache(cache_definition $definition) {
- $loader = null;
- if ($definition->has_data_source()) {
- $loader = $definition->get_data_source();
- }
- return new cache_disabled($definition, $this->create_dummy_store($definition), $loader);
- }
-
- /**
- * Creates a cache object given the parameters for a definition.
- *
- * @param string $component
- * @param string $area
- * @param array $identifiers
- * @param string $unused Used to be datasourceaggregate but that was removed and this is now unused.
- * @return cache_application|cache_session|cache_request
- */
- public function create_cache_from_definition($component, $area, array $identifiers = array(), $unused = null) {
- // Temporary in-memory caches are sometimes allowed when caching is disabled.
- if (\core_cache\allow_temporary_caches::is_allowed() && !$identifiers) {
- $key = $component . '/' . $area;
- if (array_key_exists($key, self::$tempcaches)) {
- $cache = self::$tempcaches[$key];
- } else {
- $definition = $this->create_definition($component, $area);
- // The cachestore_static class returns true to all three 'SUPPORTS_' checks so it
- // can be used with all definitions.
- $store = new cachestore_static('TEMP:' . $component . '/' . $area);
- $store->initialise($definition);
- // We need to use a cache loader wrapper rather than directly returning the store,
- // or it wouldn't have support for versioning. The cache_application class is used
- // (rather than cache_request which might make more sense logically) because it
- // includes support for locking, which might be necessary for some caches.
- $cache = new cache_application($definition, $store);
- self::$tempcaches[$key] = $cache;
- }
- return $cache;
- }
-
- // Regular cache definitions are cached inside create_definition(). This is not the case for disabledlib.php
- // definitions as they use load_adhoc(). They are built as a new object on each call.
- // We do not need to clone the definition because we know it's new.
- $definition = $this->create_definition($component, $area);
- $definition->set_identifiers($identifiers);
- $cache = $this->create_cache($definition);
- return $cache;
- }
-
- /**
- * Removes all temporary caches.
- *
- * Don't call this directly - used by {@see \core_cache\allow_temporary_caches}.
- */
- public static function clear_temporary_caches(): void {
- self::$tempcaches = [];
- }
-
- /**
- * Creates an ad-hoc cache from the given param.
- *
- * @param int $mode
- * @param string $component
- * @param string $area
- * @param array $identifiers
- * @param array $options An array of options, available options are:
- * - simplekeys : Set to true if the keys you will use are a-zA-Z0-9_
- * - simpledata : Set to true if the type of the data you are going to store is scalar, or an array of scalar vars
- * - staticacceleration : If set to true the cache will hold onto all data passing through it.
- * - staticaccelerationsize : Sets the max size of the static acceleration array.
- * @return cache_application|cache_session|cache_request
- */
- public function create_cache_from_params($mode, $component, $area, array $identifiers = array(), array $options = array()) {
- // Regular cache definitions are cached inside create_definition(). This is not the case for disabledlib.php
- // definitions as they use load_adhoc(). They are built as a new object on each call.
- // We do not need to clone the definition because we know it's new.
- $definition = cache_definition::load_adhoc($mode, $component, $area, $options);
- $definition->set_identifiers($identifiers);
- $cache = $this->create_cache($definition);
- return $cache;
- }
-
- /**
- * Creates a store instance given its name and configuration.
- *
- * @param string $name Unused.
- * @param array $details Unused.
- * @param cache_definition $definition
- * @return boolean|cache_store
- */
- public function create_store_from_config($name, array $details, cache_definition $definition) {
- return $this->create_dummy_store($definition);
- }
-
- /**
- * Creates a cache config instance with the ability to write if required.
- *
- * @param bool $writer Unused.
- * @return cache_config_disabled|cache_config_writer
- */
- public function create_config_instance($writer = false) {
- // We are always going to use the cache_config_disabled class for all regular request.
- // However if the code has requested the writer then likely something is changing and
- // we're going to need to interact with the config.php file.
- // In this case we will still use the cache_config_writer.
- $class = 'cache_config_disabled';
- if ($writer) {
- // If the writer was requested then something is changing.
- $class = 'cache_config_writer';
- }
- if (!array_key_exists($class, $this->configs)) {
- self::set_state(self::STATE_INITIALISING);
- if ($class === 'cache_config_disabled') {
- $configuration = $class::create_default_configuration();
- $this->configs[$class] = new $class;
- } else {
- $configuration = false;
- // If we need a writer, we should get the classname from the generic factory.
- // This is so alternative classes can be used if a different writer is required.
- $this->configs[$class] = parent::get_disabled_writer();
- }
- $this->configs[$class]->load($configuration);
- }
- self::set_state(self::STATE_READY);
-
- // Return the instance.
- return $this->configs[$class];
- }
-
- /**
- * Returns true if the cache API has been disabled.
- *
- * @return bool
- */
- public function is_disabled() {
- return true;
- }
-}
-
-/**
- * The cache config class used when the Cache has been disabled.
- *
- * @copyright 2012 Sam Hemelryk
- * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
- */
-class cache_config_disabled extends cache_config_writer {
-
- /**
- * Returns an instance of the configuration writer.
- *
- * @return cache_config_disabled
- */
- public static function instance() {
- $factory = cache_factory::instance();
- return $factory->create_config_instance(true);
- }
-
- /**
- * Saves the current configuration.
- */
- protected function config_save() {
- // Nothing to do here.
- }
-
- /**
- * Generates a configuration array suitable to be written to the config file.
- *
- * @return array
- */
- protected function generate_configuration_array() {
- $configuration = array();
- $configuration['stores'] = $this->configstores;
- $configuration['modemappings'] = $this->configmodemappings;
- $configuration['definitions'] = $this->configdefinitions;
- $configuration['definitionmappings'] = $this->configdefinitionmappings;
- $configuration['locks'] = $this->configlocks;
- return $configuration;
- }
-
- /**
- * Adds a plugin instance.
- *
- * @param string $name Unused.
- * @param string $plugin Unused.
- * @param array $configuration Unused.
- * @return bool
- * @throws cache_exception
- */
- public function add_store_instance($name, $plugin, array $configuration = array()) {
- return false;
- }
-
- /**
- * Sets the mode mappings.
- *
- * @param array $modemappings Unused.
- * @return bool
- * @throws cache_exception
- */
- public function set_mode_mappings(array $modemappings) {
- return false;
- }
-
- /**
- * Edits a give plugin instance.
- *
- * @param string $name Unused.
- * @param string $plugin Unused.
- * @param array $configuration Unused.
- * @return bool
- * @throws cache_exception
- */
- public function edit_store_instance($name, $plugin, $configuration) {
- return false;
- }
-
- /**
- * Deletes a store instance.
- *
- * @param string $name Unused.
- * @return bool
- * @throws cache_exception
- */
- public function delete_store_instance($name) {
- return false;
- }
-
- /**
- * Creates the default configuration and saves it.
- *
- * @param bool $forcesave Ignored because we are disabled!
- * @return array
- */
- public static function create_default_configuration($forcesave = false) {
- global $CFG;
-
- // HACK ALERT.
- // We probably need to come up with a better way to create the default stores, or at least ensure 100% that the
- // default store plugins are protected from deletion.
- require_once($CFG->dirroot.'/cache/stores/file/lib.php');
- require_once($CFG->dirroot.'/cache/stores/session/lib.php');
- require_once($CFG->dirroot.'/cache/stores/static/lib.php');
-
- $writer = new self;
- $writer->configstores = array(
- 'default_application' => array(
- 'name' => 'default_application',
- 'plugin' => 'file',
- 'configuration' => array(),
- 'features' => cachestore_file::get_supported_features(),
- 'modes' => cache_store::MODE_APPLICATION,
- 'default' => true,
- ),
- 'default_session' => array(
- 'name' => 'default_session',
- 'plugin' => 'session',
- 'configuration' => array(),
- 'features' => cachestore_session::get_supported_features(),
- 'modes' => cache_store::MODE_SESSION,
- 'default' => true,
- ),
- 'default_request' => array(
- 'name' => 'default_request',
- 'plugin' => 'static',
- 'configuration' => array(),
- 'features' => cachestore_static::get_supported_features(),
- 'modes' => cache_store::MODE_REQUEST,
- 'default' => true,
- )
- );
- $writer->configdefinitions = array();
- $writer->configmodemappings = array(
- array(
- 'mode' => cache_store::MODE_APPLICATION,
- 'store' => 'default_application',
- 'sort' => -1
- ),
- array(
- 'mode' => cache_store::MODE_SESSION,
- 'store' => 'default_session',
- 'sort' => -1
- ),
- array(
- 'mode' => cache_store::MODE_REQUEST,
- 'store' => 'default_request',
- 'sort' => -1
- )
- );
- $writer->configlocks = array(
- 'default_file_lock' => array(
- 'name' => 'cachelock_file_default',
- 'type' => 'cachelock_file',
- 'dir' => 'filelocks',
- 'default' => true
- )
- );
-
- return $writer->generate_configuration_array();
- }
-
- /**
- * Updates the definition in the configuration from those found in the cache files.
- *
- * @param bool $coreonly Unused.
- */
- public static function update_definitions($coreonly = false) {
- // Nothing to do here.
- }
-
- /**
- * Locates all of the definition files.
- *
- * @param bool $coreonly Unused.
- * @return array
- */
- protected static function locate_definitions($coreonly = false) {
- return array();
- }
-
- /**
- * Sets the mappings for a given definition.
- *
- * @param string $definition Unused.
- * @param array $mappings Unused.
- * @throws coding_exception
- */
- public function set_definition_mappings($definition, $mappings) {
- // Nothing to do here.
- }
-}
diff --git a/cache/forms.php b/cache/forms.php
index 6ec0778bb42..f9cb1179e2e 100644
--- a/cache/forms.php
+++ b/cache/forms.php
@@ -14,372 +14,5 @@
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see .
-/**
- * Forms used for the administration and managemement of the cache setup.
- *
- * This file is part of Moodle's cache API, affectionately called MUC.
- *
- * @package core
- * @category cache
- * @copyright 2012 Sam Hemelryk
- * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
- */
-
-defined('MOODLE_INTERNAL') || die();
-
-require_once($CFG->dirroot.'/lib/formslib.php');
-
-/**
- * Add store instance form.
- *
- * @package core
- * @category cache
- * @copyright 2012 Sam Hemelryk
- * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
- */
-class cachestore_addinstance_form extends moodleform {
-
- /**
- * The definition of the add instance form
- */
- final protected function definition() {
- $form = $this->_form;
- $store = $this->_customdata['store'];
- $plugin = $this->_customdata['plugin'];
- $locks = $this->_customdata['locks'];
-
- $form->addElement('hidden', 'plugin', $plugin);
- $form->setType('plugin', PARAM_PLUGIN);
- $form->addElement('hidden', 'editing', !empty($this->_customdata['store']));
- $form->setType('editing', PARAM_BOOL);
-
- if (!$store) {
- $form->addElement('text', 'name', get_string('storename', 'cache'));
- $form->addHelpButton('name', 'storename', 'cache');
- $form->addRule('name', get_string('required'), 'required');
- $form->setType('name', PARAM_NOTAGS);
- } else {
- $form->addElement('hidden', 'name', $store);
- $form->addElement('static', 'name-value', get_string('storename', 'cache'), $store);
- $form->setType('name', PARAM_NOTAGS);
- }
-
- if (is_array($locks)) {
- $form->addElement('select', 'lock', get_string('locking', 'cache'), $locks);
- $form->addHelpButton('lock', 'locking', 'cache');
- $form->setType('lock', PARAM_ALPHANUMEXT);
- } else {
- $form->addElement('hidden', 'lock', '');
- $form->setType('lock', PARAM_ALPHANUMEXT);
- $form->addElement('static', 'lock-value', get_string('locking', 'cache'),
- ''.get_string('nativelocking', 'cache').'');
- }
-
- if (method_exists($this, 'configuration_definition')) {
- $form->addElement('header', 'storeconfiguration', get_string('storeconfiguration', 'cache'));
- $this->configuration_definition();
- }
-
- $this->add_action_buttons();
- }
-
- /**
- * Validates the add instance form data
- *
- * @param array $data
- * @param array $files
- * @return array
- */
- public function validation($data, $files) {
- $errors = parent::validation($data, $files);
-
- if (!array_key_exists('name', $errors)) {
- if (!preg_match('#^[a-zA-Z0-9\-_ ]+$#', $data['name'])) {
- $errors['name'] = get_string('storenameinvalid', 'cache');
- } else if (empty($this->_customdata['store'])) {
- $stores = core_cache\administration_helper::get_store_instance_summaries();
- if (array_key_exists($data['name'], $stores)) {
- $errors['name'] = get_string('storenamealreadyused', 'cache');
- }
- }
- }
-
- if (method_exists($this, 'configuration_validation')) {
- $newerrors = $this->configuration_validation($data, $files, $errors);
- // We need to selectiviliy merge here
- foreach ($newerrors as $element => $error) {
- if (!array_key_exists($element, $errors)) {
- $errors[$element] = $error;
- }
- }
- }
-
- return $errors;
- }
-}
-
-/**
- * Form to set definition mappings
- *
- * @package core
- * @category cache
- * @copyright 2012 Sam Hemelryk
- * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
- */
-class cache_definition_mappings_form extends moodleform {
-
- /**
- * The definition of the form
- */
- final protected function definition() {
- global $OUTPUT;
-
- $definition = $this->_customdata['definition'];
- $form = $this->_form;
-
- list($component, $area) = explode('/', $definition, 2);
- list($currentstores, $storeoptions, $defaults) =
- core_cache\administration_helper::get_definition_store_options($component, $area);
-
- $storedata = core_cache\administration_helper::get_definition_summaries();
- if ($storedata[$definition]['mode'] != cache_store::MODE_REQUEST) {
- if (isset($storedata[$definition]['canuselocalstore']) && $storedata[$definition]['canuselocalstore']) {
- $form->addElement('html', $OUTPUT->notification(get_string('localstorenotification', 'cache'), 'notifymessage'));
- } else {
- $form->addElement('html', $OUTPUT->notification(get_string('sharedstorenotification', 'cache'), 'notifymessage'));
- }
- }
- $form->addElement('hidden', 'definition', $definition);
- $form->setType('definition', PARAM_SAFEPATH);
- $form->addElement('hidden', 'action', 'editdefinitionmapping');
- $form->setType('action', PARAM_ALPHA);
-
- $requiredoptions = max(3, count($currentstores)+1);
- $requiredoptions = min($requiredoptions, count($storeoptions));
-
- $options = array('' => get_string('none'));
- foreach ($storeoptions as $option => $def) {
- $options[$option] = $option;
- if ($def['default']) {
- $options[$option] .= ' '.get_string('mappingdefault', 'cache');
- }
- }
-
- for ($i = 0; $i < $requiredoptions; $i++) {
- $title = '...';
- if ($i === 0) {
- $title = get_string('mappingprimary', 'cache');
- } else if ($i === $requiredoptions-1) {
- $title = get_string('mappingfinal', 'cache');
- }
- $form->addElement('select', 'mappings['.$i.']', $title, $options);
- }
- $i = 0;
- foreach ($currentstores as $store => $def) {
- $form->setDefault('mappings['.$i.']', $store);
- $i++;
- }
-
- if (!empty($defaults)) {
- $form->addElement('static', 'defaults', get_string('defaultmappings', 'cache'),
- html_writer::tag('strong', join(', ', $defaults)));
- $form->addHelpButton('defaults', 'defaultmappings', 'cache');
- }
-
- $this->add_action_buttons();
- }
-}
-
-/**
- * Form to set definition sharing option
- *
- * @package core
- * @category cache
- * @copyright 2013 Sam Hemelryk
- * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
- */
-class cache_definition_sharing_form extends moodleform {
- /**
- * The definition of the form
- */
- final protected function definition() {
- $definition = $this->_customdata['definition'];
- $sharingoptions = $this->_customdata['sharingoptions'];
- $form = $this->_form;
-
- $form->addElement('hidden', 'definition', $definition);
- $form->setType('definition', PARAM_SAFEPATH);
- $form->addElement('hidden', 'action', 'editdefinitionsharing');
- $form->setType('action', PARAM_ALPHA);
-
- // We use a group here for validation.
- $count = 0;
- $group = array();
- foreach ($sharingoptions as $value => $text) {
- $count++;
- $group[] = $form->createElement('checkbox', $value, null, $text);
- }
- $form->addGroup($group, 'sharing', get_string('sharing', 'cache'), '
');
- $form->setType('sharing', PARAM_INT);
-
- $form->addElement('text', 'userinputsharingkey', get_string('userinputsharingkey', 'cache'));
- $form->addHelpButton('userinputsharingkey', 'userinputsharingkey', 'cache');
- $form->disabledIf('userinputsharingkey', 'sharing['.cache_definition::SHARING_INPUT.']', 'notchecked');
- $form->setType('userinputsharingkey', PARAM_ALPHANUMEXT);
-
- $values = array_keys($sharingoptions);
- if (in_array(cache_definition::SHARING_ALL, $values)) {
- // If you share with all thenthe other options don't really make sense.
- foreach ($values as $value) {
- $form->disabledIf('sharing['.$value.']', 'sharing['.cache_definition::SHARING_ALL.']', 'checked');
- }
- $form->disabledIf('userinputsharingkey', 'sharing['.cache_definition::SHARING_ALL.']', 'checked');
- }
-
- $this->add_action_buttons();
- }
-
- /**
- * Sets the data for this form.
- *
- * @param array $data
- */
- public function set_data($data) {
- if (!isset($data['sharing'])) {
- // Set the default value here. mforms doesn't handle defaults very nicely.
- $data['sharing'] = core_cache\administration_helper::get_definition_sharing_options(cache_definition::SHARING_DEFAULT);
- }
- parent::set_data($data);
- }
-
- /**
- * Validates this form
- *
- * @param array $data
- * @param array $files
- * @return array
- */
- public function validation($data, $files) {
- $errors = parent::validation($data, $files);
- if (count($errors) === 0 && !isset($data['sharing'])) {
- // They must select at least one sharing option.
- $errors['sharing'] = get_string('sharingrequired', 'cache');
- }
- return $errors;
- }
-}
-
-/**
- * Form to set the mappings for a mode.
- *
- * @package core
- * @category cache
- * @copyright 2012 Sam Hemelryk
- * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
- */
-class cache_mode_mappings_form extends moodleform {
- /**
- * The definition of the form
- */
- protected function definition() {
- $form = $this->_form;
- $stores = $this->_customdata;
-
- $options = array(
- cache_store::MODE_APPLICATION => array(),
- cache_store::MODE_SESSION => array(),
- cache_store::MODE_REQUEST => array()
- );
- foreach ($stores as $storename => $store) {
- foreach ($store['modes'] as $mode => $enabled) {
- if ($enabled && ($mode !== cache_store::MODE_SESSION || $store['supports']['searchable'])) {
- if (empty($store['default'])) {
- $options[$mode][$storename] = $store['name'];
- } else {
- $options[$mode][$storename] = get_string('store_'.$store['name'], 'cache');
- }
- }
- }
- }
-
- $form->addElement('hidden', 'action', 'editmodemappings');
- $form->setType('action', PARAM_ALPHA);
- foreach ($options as $mode => $optionset) {
- $form->addElement('select', 'mode_'.$mode, get_string('mode_'.$mode, 'cache'), $optionset);
- }
-
- $this->add_action_buttons();
- }
-}
-
-/**
- * Form to add a cache lock instance.
- *
- * All cache lock plugins that wish to have custom configuration should override
- * this form, and more explicitly the plugin_definition and plugin_validation methods.
- *
- * @package core
- * @category cache
- * @copyright 2013 Sam Hemelryk
- * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
- */
-class cache_lock_form extends moodleform {
-
- /**
- * Defines this form.
- */
- final public function definition() {
- $plugin = $this->_customdata['lock'];
-
- $this->_form->addElement('hidden', 'action', 'newlockinstance');
- $this->_form->setType('action', PARAM_ALPHANUMEXT);
- $this->_form->addElement('hidden', 'lock', $plugin);
- $this->_form->setType('lock', PARAM_COMPONENT);
- $this->_form->addElement('text', 'name', get_string('lockname', 'cache'));
- $this->_form->setType('name', PARAM_ALPHANUMEXT);
- $this->_form->addRule('name', get_string('required'), 'required');
- $this->_form->addElement('static', 'namedesc', '', get_string('locknamedesc', 'cache'));
-
- $this->plugin_definition();
-
- $this->add_action_buttons();
- }
-
- /**
- * Validates this form.
- *
- * @param array $data
- * @param array $files
- * @return array
- */
- final public function validation($data, $files) {
- $errors = parent::validation($data, $files);
- if (!isset($errors['name'])) {
- $config = cache_config::instance();
- if (in_array($data['name'], array_keys($config->get_locks()))) {
- $errors['name'] = get_string('locknamenotunique', 'cache');
- }
- }
- $errors = $this->plugin_validation($data, $files, $errors);
- return $errors;
- }
-
- /**
- * Plugin specific definition.
- */
- public function plugin_definition() {
- // No custom validation going on here.
- }
-
- /**
- * Plugin specific validation.
- *
- * @param array $data
- * @param array $files
- * @param array $errors
- * @return array
- */
- public function plugin_validation($data, $files, array $errors) {
- return $errors;
- }
-}
\ No newline at end of file
+// This file is intentionally empty.
+// It will be changed to emit debugging in MDL-82836 for Moodle 5.0.
diff --git a/cache/lib.php b/cache/lib.php
deleted file mode 100644
index c11b67a6193..00000000000
--- a/cache/lib.php
+++ /dev/null
@@ -1,228 +0,0 @@
-.
-
-/**
- * The core cache API.
- *
- * Pretty much just includes the mandatory classes and contains the misc classes that arn't worth separating into individual files.
- *
- * This file is part of Moodle's cache API, affectionately called MUC.
- * It contains the components that are requried in order to use caching.
- *
- * @package core
- * @category cache
- * @copyright 2012 Sam Hemelryk
- * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
- */
-
-defined('MOODLE_INTERNAL') || die();
-
-// Include the required classes.
-require_once($CFG->dirroot.'/cache/classes/interfaces.php');
-require_once($CFG->dirroot.'/cache/classes/config.php');
-require_once($CFG->dirroot.'/cache/classes/helper.php');
-require_once($CFG->dirroot.'/cache/classes/factory.php');
-require_once($CFG->dirroot.'/cache/classes/loaders.php');
-require_once($CFG->dirroot.'/cache/classes/store.php');
-require_once($CFG->dirroot.'/cache/classes/definition.php');
-
-/**
- * A cached object wrapper.
- *
- * This class gets used when the data is an object that has implemented the cacheable_object interface.
- *
- * @package core
- * @category cache
- * @copyright 2012 Sam Hemelryk
- * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
- */
-class cache_cached_object {
-
- /**
- * The class of the cacheable object
- * @var string
- */
- protected $class;
-
- /**
- * The data returned by the cacheable_object prepare_to_cache method.
- * @var mixed
- */
- protected $data;
-
- /**
- * Constructs a cached object wrapper.
- * @param cacheable_object $obj
- */
- public function __construct(cacheable_object $obj) {
- $this->class = get_class($obj);
- $this->data = $obj->prepare_to_cache();
- }
-
- /**
- * Restores the data as an instance of the cacheable_object class.
- * @return object
- */
- public function restore_object() {
- $class = $this->class;
- return $class::wake_from_cache($this->data);
- }
-}
-
-/**
- * A wrapper class used to handle ttl when the cache store doesn't natively support it.
- *
- * This class is exactly why you should use event driving invalidation of cache data rather than relying on ttl.
- *
- * @package core
- * @category cache
- * @copyright 2012 Sam Hemelryk
- * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
- */
-class cache_ttl_wrapper {
-
- /**
- * The data being stored.
- * @var mixed
- */
- public $data;
-
- /**
- * When the cache data expires as a timestamp.
- * @var int
- */
- public $expires;
-
- /**
- * Constructs a ttl cache wrapper.
- *
- * @param mixed $data
- * @param int $ttl The time to live in seconds.
- */
- public function __construct($data, $ttl) {
- $this->data = $data;
- $this->expires = cache::now() + (int)$ttl;
- }
-
- /**
- * Returns true if the data has expired.
- * @return int
- */
- public function has_expired() {
- return ($this->expires < cache::now());
- }
-}
-
-/**
- * A cache exception class. Just allows people to catch cache exceptions.
- *
- * @package core
- * @category cache
- * @copyright 2012 Sam Hemelryk
- * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
- */
-class cache_exception extends moodle_exception {
- /**
- * Constructs a new exception
- *
- * @param string $errorcode
- * @param string $module
- * @param string $link
- * @param mixed $a
- * @param mixed $debuginfo
- */
- public function __construct($errorcode, $module = 'cache', $link = '', $a = null, $debuginfo = null) {
- // This may appear like a useless override but you will notice that we have set a MUCH more useful default for $module.
- parent::__construct($errorcode, $module, $link, $a, $debuginfo);
- }
-}
-
-/**
- * An array of cacheable objects.
- *
- * This class allows a developer to create an array of cacheable objects and store that.
- * The cache API doesn't check items within an array to see whether they are cacheable. Such a check would be very costly to both
- * arrays using cacheable object and those that don't.
- * Instead the developer must explicitly use a cacheable_object_array instance.
- *
- * The following is one example of how this class can be used.
- *
- * $data = array();
- * $data[] = new cacheable_object('one');
- * $data[] = new cacheable_object('two');
- * $data[] = new cacheable_object('three');
- * $cache->set(new cacheable_object_array($data));
- *
- * Another example would be
- *
- * $data = new cacheable_object_array();
- * $data[] = new cacheable_object('one');
- * $data[] = new cacheable_object('two');
- * $data[] = new cacheable_object('three');
- * $cache->set($data);
- *
- *
- * @copyright 2012 Sam Hemelryk
- * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
- */
-class cacheable_object_array extends ArrayObject implements cacheable_object {
-
- /**
- * Constructs a new array object instance.
- * @param array $items
- */
- final public function __construct(array $items = array()) {
- parent::__construct($items, ArrayObject::STD_PROP_LIST);
- }
-
- /**
- * Returns the data to cache for this object.
- *
- * @return array An array of cache_cached_object instances.
- * @throws coding_exception
- */
- final public function prepare_to_cache() {
- $result = array();
- foreach ($this as $key => $value) {
- if ($value instanceof cacheable_object) {
- $value = new cache_cached_object($value);
- } else {
- throw new coding_exception('Only cacheable_object instances can be added to a cacheable_array');
- }
- $result[$key] = $value;
- }
- return $result;
- }
-
- /**
- * Returns the cacheable_object_array that was originally sent to the cache.
- *
- * @param array $data
- * @return cacheable_object_array
- * @throws coding_exception
- */
- final public static function wake_from_cache($data) {
- if (!is_array($data)) {
- throw new coding_exception('Invalid data type when reviving cacheable_array data');
- }
- $result = array();
- foreach ($data as $key => $value) {
- $result[$key] = $value->restore_object();
- }
- $class = __CLASS__;
- return new $class($result);
- }
-}
diff --git a/cache/stores/apcu/addinstanceform.php b/cache/stores/apcu/addinstanceform.php
index f9fc73e7e66..aa8081b8ccc 100644
--- a/cache/stores/apcu/addinstanceform.php
+++ b/cache/stores/apcu/addinstanceform.php
@@ -13,17 +13,7 @@
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see .
-/**
- * The library file for the apcu cache store.
- *
- * This file is part of the apcu cache store, it contains the API for interacting with an instance of the store.
- *
- * @package cachestore_apcu
- * @copyright 2014 Sam Hemelryk
- * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
- */
-defined('MOODLE_INTERNAL') || die();
-require_once($CFG->dirroot.'/cache/forms.php');
+
/**
* Form for adding a apcu instance.
*
diff --git a/cache/stores/apcu/lib.php b/cache/stores/apcu/lib.php
index 077a5d7a3ff..91bbc5e84e6 100644
--- a/cache/stores/apcu/lib.php
+++ b/cache/stores/apcu/lib.php
@@ -14,24 +14,19 @@
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see .
+use core_cache\configurable_cache_interface;
+use core_cache\definition;
+use core_cache\key_aware_cache_interface;
+use core_cache\store;
+
/**
- * APCu cache store main library.
+ * The APCu cache store class.
*
* @package cachestore_apcu
* @copyright 2012 Sam Hemelryk
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
-
-defined('MOODLE_INTERNAL') || die();
-
-/**
- * The APCu cache store class.
- *
- * @copyright 2012 Sam Hemelryk
- * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
- */
-class cachestore_apcu extends cache_store implements cache_is_key_aware, cache_is_configurable {
-
+class cachestore_apcu extends store implements configurable_cache_interface, key_aware_cache_interface {
/**
* The required version of APCu for this extension.
*/
@@ -45,7 +40,7 @@ class cachestore_apcu extends cache_store implements cache_is_key_aware, cache_i
/**
* The definition used when this instance was initialised.
- * @var cache_definition
+ * @var definition
*/
protected $definition = null;
@@ -81,7 +76,7 @@ class cachestore_apcu extends cache_store implements cache_is_key_aware, cache_i
/**
* Static method to check if a store is usable with the given mode.
*
- * @param int $mode One of cache_store::MODE_*
+ * @param int $mode One of store::MODE_*
* @return bool True if the mode is supported.
*/
public static function is_supported_mode($mode) {
@@ -138,10 +133,10 @@ class cachestore_apcu extends cache_store implements cache_is_key_aware, cache_i
*
* This function should prepare any given connections etc.
*
- * @param cache_definition $definition
+ * @param definition $definition
* @return bool
*/
- public function initialise(cache_definition $definition) {
+ public function initialise(definition $definition) {
$this->definition = $definition;
$this->cacheprefix = $this->storeprefix.$definition->generate_definition_hash().'__';
return true;
@@ -303,10 +298,10 @@ class cachestore_apcu extends cache_store implements cache_is_key_aware, cache_i
*
* Returns an instance of the cache store, or false if one cannot be created.
*
- * @param cache_definition $definition
- * @return cache_store
+ * @param definition $definition
+ * @return store
*/
- public static function initialise_test_instance(cache_definition $definition) {
+ public static function initialise_test_instance(definition $definition) {
$testperformance = get_config('cachestore_apcu', 'testperformance');
if (empty($testperformance)) {
return false;
diff --git a/cache/stores/apcu/tests/store_test.php b/cache/stores/apcu/tests/store_test.php
index f4fee05346c..b2cbd730b36 100644
--- a/cache/stores/apcu/tests/store_test.php
+++ b/cache/stores/apcu/tests/store_test.php
@@ -16,8 +16,8 @@
namespace cachestore_apcu;
-use cache_store;
-use cache_definition;
+use core_cache\store;
+use core_cache\definition;
use cachestore_apcu;
defined('MOODLE_INTERNAL') || die();
@@ -54,7 +54,7 @@ class store_test extends \cachestore_tests {
* Test that the Moodle APCu store doesn't cross paths with other code using APCu as well.
*/
public function test_cross_application_interaction(): void {
- $definition = cache_definition::load_adhoc(cache_store::MODE_APPLICATION, 'cachestore_apcu', 'phpunit_test');
+ $definition = definition::load_adhoc(store::MODE_APPLICATION, 'cachestore_apcu', 'phpunit_test');
$instance = new cachestore_apcu('Test', cachestore_apcu::unit_test_configuration());
$instance->initialise($definition);
@@ -73,11 +73,11 @@ class store_test extends \cachestore_tests {
}
public function test_different_caches_have_different_prefixes(): void {
- $definition = cache_definition::load_adhoc(cache_store::MODE_APPLICATION, 'cachestore_apcu', 'phpunit_test');
+ $definition = definition::load_adhoc(store::MODE_APPLICATION, 'cachestore_apcu', 'phpunit_test');
$instance = new cachestore_apcu('Test', cachestore_apcu::unit_test_configuration());
$instance->initialise($definition);
- $definition2 = cache_definition::load_adhoc(cache_store::MODE_APPLICATION, 'cachestore_apcu', 'phpunit_test2');
+ $definition2 = definition::load_adhoc(store::MODE_APPLICATION, 'cachestore_apcu', 'phpunit_test2');
$instance2 = new cachestore_apcu('Test', cachestore_apcu::unit_test_configuration());
$instance2->initialise($definition2);
diff --git a/cache/stores/file/addinstanceform.php b/cache/stores/file/addinstanceform.php
index 4240d7f5952..5a2ac837f77 100644
--- a/cache/stores/file/addinstanceform.php
+++ b/cache/stores/file/addinstanceform.php
@@ -14,20 +14,6 @@
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see .
-/**
- * The library file for the file cache store.
- *
- * This file is part of the file cache store, it contains the API for interacting with an instance of the store.
- * This is used as a default cache store within the Cache API. It should never be deleted.
- *
- * @package cachestore_file
- * @category cache
- * @copyright 2012 Sam Hemelryk
- * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
- */
-
-require_once($CFG->dirroot.'/cache/forms.php');
-
/**
* Form for adding a file instance.
*
@@ -68,4 +54,4 @@ class cachestore_file_addinstance_form extends cachestore_addinstance_form {
$form->setType('lockwait', PARAM_INT);
$form->addHelpButton('lockwait', 'lockwait', 'cachestore_file');
}
-}
\ No newline at end of file
+}
diff --git a/cache/stores/file/lib.php b/cache/stores/file/lib.php
index d1c1057e359..cf02e0ce2c2 100644
--- a/cache/stores/file/lib.php
+++ b/cache/stores/file/lib.php
@@ -14,17 +14,12 @@
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see .
-/**
- * The library file for the file cache store.
- *
- * This file is part of the file cache store, it contains the API for interacting with an instance of the store.
- * This is used as a default cache store within the Cache API. It should never be deleted.
- *
- * @package cachestore_file
- * @category cache
- * @copyright 2012 Sam Hemelryk
- * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
- */
+use core_cache\configurable_cache_interface;
+use core_cache\definition;
+use core_cache\key_aware_cache_interface;
+use core_cache\lockable_cache_interface;
+use core_cache\searchable_cache_interface;
+use core_cache\store;
/**
* The file store class.
@@ -34,12 +29,16 @@
* autocreate: true, false
* prescan: true, false
*
+ * @package cachestore_file
* @copyright 2012 Sam Hemelryk
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
-class cachestore_file extends cache_store implements cache_is_key_aware, cache_is_configurable, cache_is_searchable,
- cache_is_lockable {
-
+class cachestore_file extends store implements
+ key_aware_cache_interface,
+ configurable_cache_interface,
+ searchable_cache_interface,
+ lockable_cache_interface
+{
/**
* The name of the store.
* @var string
@@ -105,7 +104,7 @@ class cachestore_file extends cache_store implements cache_is_key_aware, cache_i
/**
* The cache definition this instance has been initialised with.
- * @var cache_definition
+ * @var definition
*/
protected $definition;
@@ -150,7 +149,7 @@ class cachestore_file extends cache_store implements cache_is_key_aware, cache_i
* Constructs the store instance.
*
* Noting that this function is not an initialisation. It is used to prepare the store for use.
- * The store will be initialised when required and will be provided with a cache_definition at that time.
+ * The store will be initialised when required and will be provided with a definition at that time.
*
* @param string $name
* @param array $configuration
@@ -302,11 +301,11 @@ class cachestore_file extends cache_store implements cache_is_key_aware, cache_i
/**
* Returns true if the given mode is supported by this store.
*
- * @param int $mode One of cache_store::MODE_*
+ * @param int $mode One of store::MODE_*
* @return bool
*/
public static function is_supported_mode($mode) {
- return ($mode === self::MODE_APPLICATION || $mode === self::MODE_SESSION);
+ return ($mode === static::MODE_APPLICATION || $mode === static::MODE_SESSION);
}
/**
@@ -314,9 +313,9 @@ class cachestore_file extends cache_store implements cache_is_key_aware, cache_i
*
* Once this has been done the cache is all set to be used.
*
- * @param cache_definition $definition
+ * @param definition $definition
*/
- public function initialise(cache_definition $definition) {
+ public function initialise(definition $definition) {
global $CFG;
$this->definition = $definition;
@@ -802,10 +801,10 @@ class cachestore_file extends cache_store implements cache_is_key_aware, cache_i
*
* Returns an instance of the cache store, or false if one cannot be created.
*
- * @param cache_definition $definition
+ * @param definition $definition
* @return cachestore_file
*/
- public static function initialise_test_instance(cache_definition $definition) {
+ public static function initialise_test_instance(definition $definition) {
$name = 'File test';
$path = make_cache_directory('cachestore_file_test');
$cache = new cachestore_file($name, array('path' => $path));
@@ -1009,7 +1008,6 @@ class cachestore_file extends cache_store implements cache_is_key_aware, cache_i
* @param string $key Lock identifier
* @param string $ownerid Cache identifier
* @return bool
- * @throws cache_exception
*/
public function acquire_lock($key, $ownerid): bool {
$lock = $this->lockfactory->get_lock($key, $this->lockwait);
diff --git a/cache/stores/file/tests/asyncpurge_test.php b/cache/stores/file/tests/asyncpurge_test.php
index 66bde847190..8aa14be86fa 100644
--- a/cache/stores/file/tests/asyncpurge_test.php
+++ b/cache/stores/file/tests/asyncpurge_test.php
@@ -16,8 +16,8 @@
namespace cachestore_file;
-use cache_definition;
-use cache_store;
+use core_cache\definition;
+use core_cache\store;
use cachestore_file;
/**
@@ -43,7 +43,7 @@ class asyncpurge_test extends \advanced_testcase {
$this->resetAfterTest(true);
// Cache definition.
- $definition = cache_definition::load_adhoc(cache_store::MODE_APPLICATION, 'cachestore_file', 'phpunit_test');
+ $definition = definition::load_adhoc(store::MODE_APPLICATION, 'cachestore_file', 'phpunit_test');
// Extra config, set async purge = true.
$extraconfig = ['asyncpurge' => true, 'filecacherev' => time()];
diff --git a/cache/stores/file/tests/store_test.php b/cache/stores/file/tests/store_test.php
index 9153b091225..9e3d1d47490 100644
--- a/cache/stores/file/tests/store_test.php
+++ b/cache/stores/file/tests/store_test.php
@@ -16,8 +16,8 @@
namespace cachestore_file;
-use cache_definition;
-use cache_store;
+use core_cache\definition;
+use core_cache\store;
use cachestore_file;
defined('MOODLE_INTERNAL') || die();
@@ -54,7 +54,7 @@ class store_test extends \cachestore_tests {
public function test_cache_get_with_prescan_and_purge(): void {
global $CFG;
- $definition = cache_definition::load_adhoc(cache_store::MODE_REQUEST, 'cachestore_file', 'phpunit_test');
+ $definition = definition::load_adhoc(store::MODE_REQUEST, 'cachestore_file', 'phpunit_test');
$name = 'File test';
$path = make_cache_directory('cachestore_file_test');
@@ -78,7 +78,7 @@ class store_test extends \cachestore_tests {
* Tests the get_last_read byte count.
*/
public function test_get_last_io_bytes(): void {
- $definition = cache_definition::load_adhoc(cache_store::MODE_REQUEST, 'cachestore_file', 'phpunit_test');
+ $definition = definition::load_adhoc(store::MODE_REQUEST, 'cachestore_file', 'phpunit_test');
$store = new \cachestore_file('Test');
$store->initialise($definition);
diff --git a/cache/stores/redis/addinstanceform.php b/cache/stores/redis/addinstanceform.php
index 770100c3765..6fa64c68a5f 100644
--- a/cache/stores/redis/addinstanceform.php
+++ b/cache/stores/redis/addinstanceform.php
@@ -14,18 +14,6 @@
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see .
-/**
- * Redis Cache Store - Add instance form
- *
- * @package cachestore_redis
- * @copyright 2013 Adam Durana
- * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
- */
-
-defined('MOODLE_INTERNAL') || die();
-
-require_once($CFG->dirroot . '/cache/forms.php');
-
/**
* Form for adding instance of Redis Cache Store.
*
diff --git a/cache/stores/redis/lib.php b/cache/stores/redis/lib.php
index 7e3145324da..0c96afe220d 100644
--- a/cache/stores/redis/lib.php
+++ b/cache/stores/redis/lib.php
@@ -14,15 +14,12 @@
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see .
-/**
- * Redis Cache Store - Main library
- *
- * @package cachestore_redis
- * @copyright 2013 Adam Durana
- * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
- */
-
-defined('MOODLE_INTERNAL') || die();
+use core_cache\configurable_cache_interface;
+use core_cache\definition;
+use core_cache\key_aware_cache_interface;
+use core_cache\lockable_cache_interface;
+use core_cache\searchable_cache_interface;
+use core_cache\store;
/**
* Redis Cache Store
@@ -33,11 +30,16 @@ defined('MOODLE_INTERNAL') || die();
* not to use TTL if at all possible and the benefits of having many stores in Redis using the
* hash configuration, the hash implementation has been used.
*
+ * @package cachestore_redis
* @copyright 2013 Adam Durana
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
-class cachestore_redis extends cache_store implements cache_is_key_aware, cache_is_lockable,
- cache_is_configurable, cache_is_searchable {
+class cachestore_redis extends store implements
+ key_aware_cache_interface,
+ configurable_cache_interface,
+ searchable_cache_interface,
+ lockable_cache_interface
+{
/**
* Compressor: none.
*/
@@ -87,7 +89,7 @@ class cachestore_redis extends cache_store implements cache_is_key_aware, cache_
/**
* Cache definition for this store.
*
- * @var cache_definition
+ * @var definition
*/
protected $definition = null;
@@ -331,10 +333,10 @@ class cachestore_redis extends cache_store implements cache_is_key_aware, cache_
/**
* Initialize the store.
*
- * @param cache_definition $definition
+ * @param definition $definition
* @return bool
*/
- public function initialise(cache_definition $definition) {
+ public function initialise(definition $definition) {
$this->definition = $definition;
$this->hash = $definition->generate_definition_hash();
return true;
@@ -553,7 +555,7 @@ class cachestore_redis extends cache_store implements cache_is_key_aware, cache_
/**
* Determines if the store has a given key.
*
- * @see cache_is_key_aware
+ * @see key_aware_cache_interface
* @param string $key The key to check for.
* @return bool True if the key exists, false if it does not.
*/
@@ -564,7 +566,7 @@ class cachestore_redis extends cache_store implements cache_is_key_aware, cache_
/**
* Determines if the store has any of the keys in a list.
*
- * @see cache_is_key_aware
+ * @see key_aware_cache_interface
* @param array $keys The keys to check for.
* @return bool True if any of the keys are found, false none of the keys are found.
*/
@@ -580,7 +582,7 @@ class cachestore_redis extends cache_store implements cache_is_key_aware, cache_
/**
* Determines if the store has all of the keys in a list.
*
- * @see cache_is_key_aware
+ * @see key_aware_cache_interface
* @param array $keys The keys to check for.
* @return bool True if all of the keys are found, false otherwise.
*/
@@ -596,7 +598,7 @@ class cachestore_redis extends cache_store implements cache_is_key_aware, cache_
/**
* Tries to acquire a lock with a given name.
*
- * @see cache_is_lockable
+ * @see lockable_cache_interface
* @param string $key Name of the lock to acquire.
* @param string $ownerid Information to identify owner of lock if acquired.
* @return bool True if the lock was acquired, false if it was not.
@@ -639,7 +641,7 @@ class cachestore_redis extends cache_store implements cache_is_key_aware, cache_
/**
* Checks a lock with a given name and owner information.
*
- * @see cache_is_lockable
+ * @see lockable_cache_interface
* @param string $key Name of the lock to check.
* @param string $ownerid Owner information to check existing lock against.
* @return mixed True if the lock exists and the owner information matches, null if the lock does not
@@ -685,7 +687,7 @@ class cachestore_redis extends cache_store implements cache_is_key_aware, cache_
/**
* Releases a given lock if the owner information matches.
*
- * @see cache_is_lockable
+ * @see lockable_cache_interface
* @param string $key Name of the lock to release.
* @param string $ownerid Owner information to use.
* @return bool True if the lock is released, false if it is not.
@@ -804,7 +806,8 @@ class cachestore_redis extends cache_store implements cache_is_key_aware, cache_
/**
* Creates a configuration array from given 'add instance' form data.
*
- * @see cache_is_configurable
+ * @see configurable_cache_interface
+ *
* @param stdClass $data
* @return array
*/
@@ -824,7 +827,7 @@ class cachestore_redis extends cache_store implements cache_is_key_aware, cache_
/**
* Sets form data from a configuration array.
*
- * @see cache_is_configurable
+ * @see configurable_cache_interface
* @param moodleform $editform
* @param array $config
*/
@@ -855,10 +858,10 @@ class cachestore_redis extends cache_store implements cache_is_key_aware, cache_
/**
* Creates an instance of the store for testing.
*
- * @param cache_definition $definition
+ * @param definition $definition
* @return mixed An instance of the store, or false if an instance cannot be created.
*/
- public static function initialise_test_instance(cache_definition $definition) {
+ public static function initialise_test_instance(definition $definition) {
if (!self::are_requirements_met()) {
return false;
}
diff --git a/cache/stores/redis/tests/cachestore_cluster_redis_test.php b/cache/stores/redis/tests/cachestore_cluster_redis_test.php
index 05013afb794..76915ea1131 100644
--- a/cache/stores/redis/tests/cachestore_cluster_redis_test.php
+++ b/cache/stores/redis/tests/cachestore_cluster_redis_test.php
@@ -16,8 +16,9 @@
namespace cachestore_redis;
-use cache_definition;
-use cache_store;
+use core_cache\definition;
+use core_cache\helper;
+use core_cache\store;
use cachestore_redis;
defined('MOODLE_INTERNAL') || die();
@@ -53,8 +54,8 @@ class cachestore_cluster_redis_test extends \advanced_testcase {
public function create_store(?string $seed = null): cachestore_redis {
global $DB;
- $definition = cache_definition::load_adhoc(
- mode: cache_store::MODE_APPLICATION,
+ $definition = definition::load_adhoc(
+ mode: store::MODE_APPLICATION,
component: 'cachestore_redis',
area: 'phpunit_test',
);
@@ -91,7 +92,7 @@ class cachestore_cluster_redis_test extends \advanced_testcase {
parent::setUp();
if (!cachestore_redis::are_requirements_met()) {
$this->markTestSkipped('Could not test cachestore_redis with cluster, missing requirements.');
- } else if (!\cache_helper::is_cluster_available()) {
+ } else if (!helper::is_cluster_available()) {
$this->markTestSkipped('Could not test cachestore_redis with cluster, class RedisCluster is not available.');
} else if (!defined('TEST_CACHESTORE_REDIS_SERVERSCLUSTER')) {
$this->markTestSkipped('Could not test cachestore_redis with cluster, missing configuration. ' .
diff --git a/cache/stores/redis/tests/cachestore_redis_test.php b/cache/stores/redis/tests/cachestore_redis_test.php
index af3fac0a938..514accad0bd 100644
--- a/cache/stores/redis/tests/cachestore_redis_test.php
+++ b/cache/stores/redis/tests/cachestore_redis_test.php
@@ -16,9 +16,9 @@
namespace cachestore_redis;
-use cache_definition;
-use cache_store;
use cachestore_redis;
+use core_cache\definition;
+use core_cache\store;
defined('MOODLE_INTERNAL') || die();
@@ -73,7 +73,7 @@ class cachestore_redis_test extends \cachestore_tests {
* @return cachestore_redis
*/
protected function create_cachestore_redis(): cachestore_redis {
- $definition = cache_definition::load_adhoc(cache_store::MODE_APPLICATION, 'cachestore_redis', 'phpunit_test');
+ $definition = definition::load_adhoc(store::MODE_APPLICATION, 'cachestore_redis', 'phpunit_test');
$store = new cachestore_redis('Test', cachestore_redis::unit_test_configuration());
$store->initialise($definition);
$this->store = $store;
diff --git a/cache/stores/redis/tests/compressor_test.php b/cache/stores/redis/tests/compressor_test.php
index 6df84410465..6c2574bc150 100644
--- a/cache/stores/redis/tests/compressor_test.php
+++ b/cache/stores/redis/tests/compressor_test.php
@@ -16,9 +16,9 @@
namespace cachestore_redis;
-use cache_definition;
-use cache_store;
use cachestore_redis;
+use core_cache\definition;
+use core_cache\store;
require_once(__DIR__.'/../../../tests/fixtures/stores.php');
require_once(__DIR__.'/../lib.php');
@@ -57,8 +57,8 @@ class compressor_test extends \advanced_testcase {
* @return cachestore_redis
*/
public function create_store($compressor, $serializer) {
- /** @var cache_definition $definition */
- $definition = cache_definition::load_adhoc(cache_store::MODE_APPLICATION, 'cachestore_redis', 'phpunit_test');
+ /** @var definition $definition */
+ $definition = definition::load_adhoc(store::MODE_APPLICATION, 'cachestore_redis', 'phpunit_test');
$config = cachestore_redis::unit_test_configuration();
$config['compressor'] = $compressor;
$config['serializer'] = $serializer;
diff --git a/cache/stores/redis/tests/store_test.php b/cache/stores/redis/tests/store_test.php
index 8dcbe42df60..6da90ee9210 100644
--- a/cache/stores/redis/tests/store_test.php
+++ b/cache/stores/redis/tests/store_test.php
@@ -16,8 +16,8 @@
namespace cachestore_redis;
-use cache_store;
-use cache_definition;
+use core_cache\definition;
+use core_cache\store;
use cachestore_redis;
defined('MOODLE_INTERNAL') || die();
@@ -76,8 +76,8 @@ class store_test extends \cachestore_tests {
*/
protected function create_cachestore_redis(array $extraconfig = [], bool $ttl = false): cachestore_redis {
if ($ttl) {
- /** @var cache_definition $definition */
- $definition = cache_definition::load('core/wibble', [
+ /** @var definition $definition */
+ $definition = definition::load('core/wibble', [
'mode' => 1,
'simplekeys' => true,
'simpledata' => true,
@@ -89,8 +89,8 @@ class store_test extends \cachestore_tests {
'sharingoptions' => 15,
]);
} else {
- /** @var cache_definition $definition */
- $definition = cache_definition::load_adhoc(cache_store::MODE_APPLICATION, 'cachestore_redis', 'phpunit_test');
+ /** @var definition $definition */
+ $definition = definition::load_adhoc(store::MODE_APPLICATION, 'cachestore_redis', 'phpunit_test');
}
$configuration = array_merge(cachestore_redis::unit_test_configuration(), $extraconfig);
$store = new cachestore_redis('Test', $configuration);
@@ -200,9 +200,9 @@ class store_test extends \cachestore_tests {
$store = $this->create_cachestore_redis();
$store->set('foo', [1, 2, 3, 4]);
- $this->assertEquals(\cache_store::IO_BYTES_NOT_SUPPORTED, $store->get_last_io_bytes());
+ $this->assertEquals(store::IO_BYTES_NOT_SUPPORTED, $store->get_last_io_bytes());
$store->get('foo');
- $this->assertEquals(\cache_store::IO_BYTES_NOT_SUPPORTED, $store->get_last_io_bytes());
+ $this->assertEquals(store::IO_BYTES_NOT_SUPPORTED, $store->get_last_io_bytes());
}
/**
diff --git a/cache/stores/redis/tests/ttl_test.php b/cache/stores/redis/tests/ttl_test.php
index a02d58d6cbe..6ee2197a607 100644
--- a/cache/stores/redis/tests/ttl_test.php
+++ b/cache/stores/redis/tests/ttl_test.php
@@ -16,6 +16,8 @@
namespace cachestore_redis;
+use core_cache\definition;
+
/**
* TTL support test for Redis cache.
*
@@ -41,7 +43,7 @@ final class ttl_test extends \advanced_testcase {
}
// Set up a Redis store with a fake definition that has TTL set to 10 seconds.
- $definition = \cache_definition::load('core/wibble', [
+ $definition = definition::load('core/wibble', [
'mode' => 1,
'simplekeys' => true,
'simpledata' => true,
diff --git a/cache/stores/session/lib.php b/cache/stores/session/lib.php
index f1284f1bdd0..257ca701f20 100644
--- a/cache/stores/session/lib.php
+++ b/cache/stores/session/lib.php
@@ -26,6 +26,11 @@
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
+use core_cache\definition;
+use core_cache\key_aware_cache_interface;
+use core_cache\searchable_cache_interface;
+use core_cache\store;
+
defined('MOODLE_INTERNAL') || die();
/**
@@ -34,7 +39,7 @@ defined('MOODLE_INTERNAL') || die();
* @copyright 2012 Sam Hemelryk
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
-abstract class session_data_store extends cache_store {
+abstract class session_data_store extends store {
/**
* Used for the actual storage.
@@ -90,8 +95,7 @@ abstract class session_data_store extends cache_store {
* @copyright 2012 Sam Hemelryk
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
-class cachestore_session extends session_data_store implements cache_is_key_aware, cache_is_searchable {
-
+class cachestore_session extends session_data_store implements key_aware_cache_interface, searchable_cache_interface {
/**
* The name of the store
* @var store
@@ -132,7 +136,7 @@ class cachestore_session extends session_data_store implements cache_is_key_awar
* Constructs the store instance.
*
* Noting that this function is not an initialisation. It is used to prepare the store for use.
- * The store will be initialised when required and will be provided with a cache_definition at that time.
+ * The store will be initialised when required and will be provided with a definition at that time.
*
* @param string $name
* @param array $configuration
@@ -186,11 +190,11 @@ class cachestore_session extends session_data_store implements cache_is_key_awar
/**
* Returns true if the given mode is supported by this store.
*
- * @param int $mode One of cache_store::MODE_*
+ * @param int $mode One of store::MODE_*
* @return bool
*/
public static function is_supported_mode($mode) {
- return ($mode === self::MODE_SESSION);
+ return ($mode === store::MODE_SESSION);
}
/**
@@ -198,9 +202,9 @@ class cachestore_session extends session_data_store implements cache_is_key_awar
*
* Once this has been done the cache is all set to be used.
*
- * @param cache_definition $definition
+ * @param definition $definition
*/
- public function initialise(cache_definition $definition) {
+ public function initialise(definition $definition) {
$this->storeid = $definition->generate_definition_hash();
$this->store = &self::register_store_id($this->name.'-'.$definition->get_id());
$this->ttl = $definition->get_ttl();
@@ -506,10 +510,10 @@ class cachestore_session extends session_data_store implements cache_is_key_awar
/**
* Generates an instance of the cache store that can be used for testing.
*
- * @param cache_definition $definition
+ * @param definition $definition
* @return cachestore_session
*/
- public static function initialise_test_instance(cache_definition $definition) {
+ public static function initialise_test_instance(definition $definition) {
// Do something here perhaps.
$cache = new cachestore_session('Session test');
$cache->initialise($definition);
diff --git a/cache/stores/static/lib.php b/cache/stores/static/lib.php
index 72a0c80f3d1..dc37077d41b 100644
--- a/cache/stores/static/lib.php
+++ b/cache/stores/static/lib.php
@@ -26,6 +26,9 @@
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
+use core_cache\definition;
+use core_cache\store;
+
defined('MOODLE_INTERNAL') || die();
/**
@@ -34,8 +37,7 @@ defined('MOODLE_INTERNAL') || die();
* @copyright 2012 Sam Hemelryk
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
-abstract class static_data_store extends cache_store {
-
+abstract class static_data_store extends store {
/**
* An array for storage.
* @var array
@@ -134,7 +136,7 @@ class cachestore_static extends static_data_store implements cache_is_key_aware,
* Constructs the store instance.
*
* Noting that this function is not an initialisation. It is used to prepare the store for use.
- * The store will be initialised when required and will be provided with a cache_definition at that time.
+ * The store will be initialised when required and will be provided with a definition at that time.
*
* @param string $name
* @param array $configuration
@@ -190,11 +192,11 @@ class cachestore_static extends static_data_store implements cache_is_key_aware,
/**
* Returns true if the given mode is supported by this store.
*
- * @param int $mode One of cache_store::MODE_*
+ * @param int $mode One of store::MODE_*
* @return bool
*/
public static function is_supported_mode($mode) {
- return ($mode === self::MODE_REQUEST);
+ return ($mode === store::MODE_REQUEST);
}
/**
@@ -202,9 +204,9 @@ class cachestore_static extends static_data_store implements cache_is_key_aware,
*
* Once this has been done the cache is all set to be used.
*
- * @param cache_definition $definition
+ * @param definition $definition
*/
- public function initialise(cache_definition $definition) {
+ public function initialise(definition $definition) {
$keyarray = $definition->generate_multi_key_parts();
$this->storeid = $keyarray['mode'].'/'.$keyarray['component'].'/'.$keyarray['area'].'/'.$keyarray['siteidentifier'];
$this->store = &self::register_store_id($this->storeid);
@@ -525,10 +527,10 @@ class cachestore_static extends static_data_store implements cache_is_key_aware,
/**
* Generates an instance of the cache store that can be used for testing.
*
- * @param cache_definition $definition
+ * @param definition $definition
* @return cachestore_static
*/
- public static function initialise_test_instance(cache_definition $definition) {
+ public static function initialise_test_instance(definition $definition) {
// Do something here perhaps.
$cache = new cachestore_static('Static store');
$cache->initialise($definition);
diff --git a/cache/stores/static/tests/store_test.php b/cache/stores/static/tests/store_test.php
index 329e608596e..95ac8c5d581 100644
--- a/cache/stores/static/tests/store_test.php
+++ b/cache/stores/static/tests/store_test.php
@@ -16,8 +16,8 @@
namespace cachestore_static;
-use cache_definition;
-use cache_store;
+use core_cache\definition;
+use core_cache\store;
use cachestore_static;
defined('MOODLE_INTERNAL') || die();
@@ -50,12 +50,12 @@ class store_test extends \cachestore_tests {
$defid = 'phpunit/testmaxsize';
$config = \cache_config_testing::instance();
$config->phpunit_add_definition($defid, array(
- 'mode' => cache_store::MODE_REQUEST,
+ 'mode' => store::MODE_REQUEST,
'component' => 'phpunit',
'area' => 'testmaxsize',
'maxsize' => 3
));
- $definition = cache_definition::load($defid, $config->get_definition_by_id($defid));
+ $definition = definition::load($defid, $config->get_definition_by_id($defid));
$instance = cachestore_static::initialise_test_instance($definition);
$this->assertTrue($instance->set('key1', 'value1'));
@@ -128,11 +128,11 @@ class store_test extends \cachestore_tests {
$defid = 'phpunit/igbinary';
$config = \cache_config_testing::instance();
$config->phpunit_add_definition($defid, array(
- 'mode' => cache_store::MODE_REQUEST,
+ 'mode' => store::MODE_REQUEST,
'component' => 'phpunit',
'area' => 'testigbinary'
));
- $definition = cache_definition::load($defid, $config->get_definition_by_id($defid));
+ $definition = definition::load($defid, $config->get_definition_by_id($defid));
$instance = cachestore_static::initialise_test_instance($definition);
// Prepare an object.
$obj = new \stdClass();
diff --git a/cache/testperformance.php b/cache/testperformance.php
index 4592e41d2cf..367e4f93a7a 100644
--- a/cache/testperformance.php
+++ b/cache/testperformance.php
@@ -17,15 +17,14 @@
/**
* Store performance test run + output script.
*
- * @package core
+ * @package core_cache
* @category cache
* @copyright 2012 Sam Hemelryk
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
require_once('../config.php');
-require_once($CFG->dirroot.'/lib/adminlib.php');
-require_once($CFG->dirroot.'/cache/locallib.php');
+require_once($CFG->dirroot . '/lib/adminlib.php');
$count = optional_param('count', 100, PARAM_INT);
$count = min($count, 100000);
@@ -34,15 +33,15 @@ $count = max($count, 0);
admin_externalpage_setup('cachetestperformance');
$applicationtable = new html_table();
-$applicationtable->head = array(
+$applicationtable->head = [
get_string('plugin', 'cache'),
get_string('result', 'cache'),
get_string('set', 'cache'),
get_string('gethit', 'cache'),
get_string('getmiss', 'cache'),
get_string('delete', 'cache'),
-);
-$applicationtable->data = array();
+];
+$applicationtable->data = [];
$sessiontable = clone($applicationtable);
$requesttable = clone($applicationtable);
@@ -58,48 +57,47 @@ $strtested = new lang_string('tested', 'cache');
$strnotready = new lang_string('storenotready', 'cache');
foreach (core_component::get_plugin_list_with_file('cachestore', 'lib.php', true) as $plugin => $path) {
-
- $class = 'cachestore_'.$plugin;
- $plugin = get_string('pluginname', 'cachestore_'.$plugin);
+ $class = 'cachestore_' . $plugin;
+ $plugin = get_string('pluginname', 'cachestore_' . $plugin);
if (!class_exists($class) || !method_exists($class, 'initialise_test_instance') || !$class::are_requirements_met()) {
- $applicationtable->data[] = array($plugin, $strinvalidplugin, '-', '-', '-', '-');
- $sessiontable->data[] = array($plugin, $strinvalidplugin, '-', '-', '-', '-');
- $requesttable->data[] = array($plugin, $strinvalidplugin, '-', '-', '-', '-');
+ $applicationtable->data[] = [$plugin, $strinvalidplugin, '-', '-', '-', '-'];
+ $sessiontable->data[] = [$plugin, $strinvalidplugin, '-', '-', '-', '-'];
+ $requesttable->data[] = [$plugin, $strinvalidplugin, '-', '-', '-', '-'];
continue;
}
if (!$class::is_supported_mode(cache_store::MODE_APPLICATION)) {
- $applicationtable->data[] = array($plugin, $strunsupportedmode, '-', '-', '-', '-');
+ $applicationtable->data[] = [$plugin, $strunsupportedmode, '-', '-', '-', '-'];
} else {
$store = $class::initialise_test_instance($application);
if ($store === false) {
- $applicationtable->data[] = array($plugin, $struntestable, '-', '-', '-', '-');
+ $applicationtable->data[] = [$plugin, $struntestable, '-', '-', '-', '-'];
} else if (!$store->is_ready()) {
- $applicationtable->data[] = array($plugin, $strnotready, '-', '-', '-', '-');
+ $applicationtable->data[] = [$plugin, $strnotready, '-', '-', '-', '-'];
} else {
- $result = array($plugin, $strtested, 0, 0, 0);
+ $result = [$plugin, $strtested, 0, 0, 0];
$start = microtime(true);
for ($i = 0; $i < $count; $i++) {
- $store->set('key'.$i, 'test data '.$i);
+ $store->set('key' . $i, 'test data ' . $i);
}
$result[2] = sprintf('%01.4f', microtime(true) - $start);
$start = microtime(true);
for ($i = 0; $i < $count; $i++) {
- $store->get('key'.$i);
+ $store->get('key' . $i);
}
$result[3] = sprintf('%01.4f', microtime(true) - $start);
$start = microtime(true);
for ($i = 0; $i < $count; $i++) {
- $store->get('fake'.$i);
+ $store->get('fake' . $i);
}
$result[4] = sprintf('%01.4f', microtime(true) - $start);
$start = microtime(true);
for ($i = 0; $i < $count; $i++) {
- $store->delete('key'.$i);
+ $store->delete('key' . $i);
}
$result[5] = sprintf('%01.4f', microtime(true) - $start);
$applicationtable->data[] = $result;
@@ -108,36 +106,36 @@ foreach (core_component::get_plugin_list_with_file('cachestore', 'lib.php', true
}
if (!$class::is_supported_mode(cache_store::MODE_SESSION)) {
- $sessiontable->data[] = array($plugin, $strunsupportedmode, '-', '-', '-', '-');
+ $sessiontable->data[] = [$plugin, $strunsupportedmode, '-', '-', '-', '-'];
} else {
$store = $class::initialise_test_instance($session);
if ($store === false) {
- $sessiontable->data[] = array($plugin, $struntestable, '-', '-', '-', '-');
+ $sessiontable->data[] = [$plugin, $struntestable, '-', '-', '-', '-'];
} else if (!$store->is_ready()) {
- $sessiontable->data[] = array($plugin, $strnotready, '-', '-', '-', '-');
+ $sessiontable->data[] = [$plugin, $strnotready, '-', '-', '-', '-'];
} else {
- $result = array($plugin, $strtested, 0, 0, 0);
+ $result = [$plugin, $strtested, 0, 0, 0];
$start = microtime(true);
for ($i = 0; $i < $count; $i++) {
- $store->set('key'.$i, 'test data '.$i);
+ $store->set('key' . $i, 'test data ' . $i);
}
$result[2] = sprintf('%01.4f', microtime(true) - $start);
$start = microtime(true);
for ($i = 0; $i < $count; $i++) {
- $store->get('key'.$i);
+ $store->get('key' . $i);
}
$result[3] = sprintf('%01.4f', microtime(true) - $start);
$start = microtime(true);
for ($i = 0; $i < $count; $i++) {
- $store->get('fake'.$i);
+ $store->get('fake' . $i);
}
$result[4] = sprintf('%01.4f', microtime(true) - $start);
$start = microtime(true);
for ($i = 0; $i < $count; $i++) {
- $store->delete('key'.$i);
+ $store->delete('key' . $i);
}
$result[5] = sprintf('%01.4f', microtime(true) - $start);
$sessiontable->data[] = $result;
@@ -146,52 +144,51 @@ foreach (core_component::get_plugin_list_with_file('cachestore', 'lib.php', true
}
if (!$class::is_supported_mode(cache_store::MODE_REQUEST)) {
- $requesttable->data[] = array($plugin, $strunsupportedmode, '-', '-', '-', '-');
+ $requesttable->data[] = [$plugin, $strunsupportedmode, '-', '-', '-', '-'];
} else {
$store = $class::initialise_test_instance($request);
if ($store === false) {
- $requesttable->data[] = array($plugin, $struntestable, '-', '-', '-', '-');
+ $requesttable->data[] = [$plugin, $struntestable, '-', '-', '-', '-'];
} else if (!$store->is_ready()) {
- $requesttable->data[] = array($plugin, $strnotready, '-', '-', '-', '-');
+ $requesttable->data[] = [$plugin, $strnotready, '-', '-', '-', '-'];
} else {
- $result = array($plugin, $strtested, 0, 0, 0);
+ $result = [$plugin, $strtested, 0, 0, 0];
$start = microtime(true);
for ($i = 0; $i < $count; $i++) {
- $store->set('key'.$i, 'test data '.$i);
+ $store->set('key' . $i, 'test data ' . $i);
}
$result[2] = sprintf('%01.4f', microtime(true) - $start);
$start = microtime(true);
for ($i = 0; $i < $count; $i++) {
- $store->get('key'.$i);
+ $store->get('key' . $i);
}
$result[3] = sprintf('%01.4f', microtime(true) - $start);
$start = microtime(true);
for ($i = 0; $i < $count; $i++) {
- $store->get('fake'.$i);
+ $store->get('fake' . $i);
}
$result[4] = sprintf('%01.4f', microtime(true) - $start);
$start = microtime(true);
for ($i = 0; $i < $count; $i++) {
- $store->delete('key'.$i);
+ $store->delete('key' . $i);
}
$result[5] = sprintf('%01.4f', microtime(true) - $start);
$requesttable->data[] = $result;
$store->instance_deleted();
}
}
-
}
echo $OUTPUT->header();
echo $OUTPUT->heading(get_string('storeperformance', 'cache', $count));
-$possiblecounts = array(1, 10, 100, 500, 1000, 5000, 10000, 50000, 100000);
-$links = array();
+$possiblecounts = [1, 10, 100, 500, 1000, 5000, 10000, 50000, 100000];
+$links = [];
foreach ($possiblecounts as $pcount) {
- $links[] = html_writer::link(new moodle_url($PAGE->url, array('count' => $pcount)), $pcount);
+ $links[] = html_writer::link(new moodle_url($PAGE->url, ['count' => $pcount]), $pcount);
}
echo $OUTPUT->box_start('generalbox performance-test-counts');
echo get_string('requestcount', 'cache', join(', ', $links));
diff --git a/cache/tests/administration_helper_test.php b/cache/tests/administration_helper_test.php
index 49b3dd1a06f..ddaf0e729dd 100644
--- a/cache/tests/administration_helper_test.php
+++ b/cache/tests/administration_helper_test.php
@@ -17,18 +17,6 @@
namespace core_cache;
use cache_config_testing;
-use cache_config_writer;
-use cache_factory;
-use cache_helper;
-use cache_store;
-
-defined('MOODLE_INTERNAL') || die();
-
-// Include the necessary evils.
-global $CFG;
-require_once($CFG->dirroot.'/cache/locallib.php');
-require_once($CFG->dirroot.'/cache/tests/fixtures/lib.php');
-
/**
* PHPunit tests for the cache API and in particular the core_cache\administration_helper
@@ -37,24 +25,34 @@ require_once($CFG->dirroot.'/cache/tests/fixtures/lib.php');
* @category test
* @copyright 2012 Sam Hemelryk
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ * @covers \core_cache\administration_helper
*/
-class administration_helper_test extends \advanced_testcase {
-
+final class administration_helper_test extends \advanced_testcase {
/**
* Set things back to the default before each test.
*/
public function setUp(): void {
parent::setUp();
- cache_factory::reset();
+ factory::reset();
cache_config_testing::create_default_configuration();
}
+ /**
+ * Require all test dependencies not auto-loadable.
+ */
+ public static function setUpBeforeClass(): void {
+ global $CFG;
+
+ parent::setUpBeforeClass();
+ require_once($CFG->dirroot . '/cache/tests/fixtures/lib.php');
+ }
+
/**
* Final task is to reset the cache system
*/
public static function tearDownAfterClass(): void {
parent::tearDownAfterClass();
- cache_factory::reset();
+ factory::reset();
}
/**
@@ -62,20 +60,20 @@ class administration_helper_test extends \advanced_testcase {
*/
public function test_get_summaries(): void {
// First the preparation.
- $config = cache_config_writer::instance();
+ $config = config_writer::instance();
$this->assertTrue($config->add_store_instance('summariesstore', 'file'));
- $config->set_definition_mappings('core/eventinvalidation', array('summariesstore'));
- $this->assertTrue($config->set_mode_mappings(array(
- cache_store::MODE_APPLICATION => array('summariesstore'),
- cache_store::MODE_SESSION => array('default_session'),
- cache_store::MODE_REQUEST => array('default_request'),
- )));
+ $config->set_definition_mappings('core/eventinvalidation', ['summariesstore']);
+ $this->assertTrue($config->set_mode_mappings([
+ store::MODE_APPLICATION => ['summariesstore'],
+ store::MODE_SESSION => ['default_session'],
+ store::MODE_REQUEST => ['default_request'],
+ ]));
$storesummaries = administration_helper::get_store_instance_summaries();
$this->assertIsArray($storesummaries);
$this->assertArrayHasKey('summariesstore', $storesummaries);
$summary = $storesummaries['summariesstore'];
- // Check the keys
+ // Check the keys.
$this->assertArrayHasKey('name', $summary);
$this->assertArrayHasKey('plugin', $summary);
$this->assertArrayHasKey('default', $summary);
@@ -84,7 +82,7 @@ class administration_helper_test extends \advanced_testcase {
$this->assertArrayHasKey('mappings', $summary);
$this->assertArrayHasKey('modes', $summary);
$this->assertArrayHasKey('supports', $summary);
- // Check the important/known values
+ // Check the important/known values.
$this->assertEquals('summariesstore', $summary['name']);
$this->assertEquals('file', $summary['plugin']);
$this->assertEquals(0, $summary['default']);
@@ -92,8 +90,8 @@ class administration_helper_test extends \advanced_testcase {
$this->assertEquals(1, $summary['requirementsmet']);
// Find the number of mappings to sessionstore.
- $mappingcount = count(array_filter($config->get_definitions(), function($element) {
- return $element['mode'] === cache_store::MODE_APPLICATION;
+ $mappingcount = count(array_filter($config->get_definitions(), function ($element) {
+ return $element['mode'] === store::MODE_APPLICATION;
}));
$this->assertEquals($mappingcount, $summary['mappings']);
@@ -101,17 +99,17 @@ class administration_helper_test extends \advanced_testcase {
$this->assertIsArray($definitionsummaries);
$this->assertArrayHasKey('core/eventinvalidation', $definitionsummaries);
$summary = $definitionsummaries['core/eventinvalidation'];
- // Check the keys
+ // Check the keys.
$this->assertArrayHasKey('id', $summary);
$this->assertArrayHasKey('name', $summary);
$this->assertArrayHasKey('mode', $summary);
$this->assertArrayHasKey('component', $summary);
$this->assertArrayHasKey('area', $summary);
$this->assertArrayHasKey('mappings', $summary);
- // Check the important/known values
+ // Check the important/known values.
$this->assertEquals('core/eventinvalidation', $summary['id']);
$this->assertInstanceOf('lang_string', $summary['name']);
- $this->assertEquals(cache_store::MODE_APPLICATION, $summary['mode']);
+ $this->assertEquals(store::MODE_APPLICATION, $summary['mode']);
$this->assertEquals('core', $summary['component']);
$this->assertEquals('eventinvalidation', $summary['area']);
$this->assertIsArray($summary['mappings']);
@@ -121,7 +119,7 @@ class administration_helper_test extends \advanced_testcase {
$this->assertIsArray($pluginsummaries);
$this->assertArrayHasKey('file', $pluginsummaries);
$summary = $pluginsummaries['file'];
- // Check the keys
+ // Check the keys.
$this->assertArrayHasKey('name', $summary);
$this->assertArrayHasKey('requirementsmet', $summary);
$this->assertArrayHasKey('instances', $summary);
@@ -136,12 +134,12 @@ class administration_helper_test extends \advanced_testcase {
$mappings = administration_helper::get_default_mode_stores();
$this->assertIsArray($mappings);
$this->assertCount(3, $mappings);
- $this->assertArrayHasKey(cache_store::MODE_APPLICATION, $mappings);
- $this->assertIsArray($mappings[cache_store::MODE_APPLICATION]);
- $this->assertContains('summariesstore', $mappings[cache_store::MODE_APPLICATION]);
+ $this->assertArrayHasKey(store::MODE_APPLICATION, $mappings);
+ $this->assertIsArray($mappings[store::MODE_APPLICATION]);
+ $this->assertContains('summariesstore', $mappings[store::MODE_APPLICATION]);
$potentials = administration_helper::get_definition_store_options('core', 'eventinvalidation');
- $this->assertIsArray($potentials); // Currently used, suitable, default
+ $this->assertIsArray($potentials); // Currently used, suitable, default.
$this->assertCount(3, $potentials);
$this->assertArrayHasKey('summariesstore', $potentials[0]);
$this->assertArrayHasKey('summariesstore', $potentials[1]);
@@ -152,14 +150,14 @@ class administration_helper_test extends \advanced_testcase {
* Test instantiating an add store form.
*/
public function test_get_add_store_form(): void {
- $form = cache_factory::get_administration_display_helper()->get_add_store_form('file');
+ $form = factory::get_administration_display_helper()->get_add_store_form('file');
$this->assertInstanceOf('moodleform', $form);
try {
- $form = cache_factory::get_administration_display_helper()->get_add_store_form('somethingstupid');
+ $form = factory::get_administration_display_helper()->get_add_store_form('somethingstupid');
$this->fail('You should not be able to create an add form for a store plugin that does not exist.');
} catch (\moodle_exception $e) {
- $this->assertInstanceOf('coding_exception', $e, 'Needs to be: ' .get_class($e)." ::: ".$e->getMessage());
+ $this->assertInstanceOf('coding_exception', $e, 'Needs to be: ' . get_class($e) . " ::: " . $e->getMessage());
}
}
@@ -168,8 +166,8 @@ class administration_helper_test extends \advanced_testcase {
*/
public function test_get_edit_store_form(): void {
// Always instantiate a new core display helper here.
- $administrationhelper = new local\administration_display_helper;
- $config = cache_config_writer::instance();
+ $administrationhelper = new local\administration_display_helper();
+ $config = config_writer::instance();
$this->assertTrue($config->add_store_instance('test_get_edit_store_form', 'file'));
$form = $administrationhelper->get_edit_store_form('file', 'test_get_edit_store_form');
@@ -197,41 +195,41 @@ class administration_helper_test extends \advanced_testcase {
$this->resetAfterTest();
set_debugging(DEBUG_ALL);
- // First with simplekeys
+ // First with simplekeys.
$instance = cache_config_testing::instance(true);
- $instance->phpunit_add_definition('phpunit/hashtest', array(
- 'mode' => cache_store::MODE_APPLICATION,
+ $instance->phpunit_add_definition('phpunit/hashtest', [
+ 'mode' => store::MODE_APPLICATION,
'component' => 'phpunit',
'area' => 'hashtest',
- 'simplekeys' => true
- ));
- $factory = cache_factory::instance();
+ 'simplekeys' => true,
+ ]);
+ $factory = factory::instance();
$definition = $factory->create_definition('phpunit', 'hashtest');
- $result = cache_helper::hash_key('test', $definition);
- $this->assertEquals('test-'.$definition->generate_single_key_prefix(), $result);
+ $result = helper::hash_key('test', $definition);
+ $this->assertEquals('test-' . $definition->generate_single_key_prefix(), $result);
try {
- cache_helper::hash_key('test/test', $definition);
+ helper::hash_key('test/test', $definition);
$this->fail('Invalid key was allowed, you should see this.');
} catch (\coding_exception $e) {
$this->assertEquals('test/test', $e->debuginfo);
}
- // Second without simple keys
- $instance->phpunit_add_definition('phpunit/hashtest2', array(
- 'mode' => cache_store::MODE_APPLICATION,
+ // Second without simple keys.
+ $instance->phpunit_add_definition('phpunit/hashtest2', [
+ 'mode' => store::MODE_APPLICATION,
'component' => 'phpunit',
'area' => 'hashtest2',
- 'simplekeys' => false
- ));
+ 'simplekeys' => false,
+ ]);
$definition = $factory->create_definition('phpunit', 'hashtest2');
- $result = cache_helper::hash_key('test', $definition);
- $this->assertEquals(sha1($definition->generate_single_key_prefix().'-test'), $result);
+ $result = helper::hash_key('test', $definition);
+ $this->assertEquals(sha1($definition->generate_single_key_prefix() . '-test'), $result);
- $result = cache_helper::hash_key('test/test', $definition);
- $this->assertEquals(sha1($definition->generate_single_key_prefix().'-test/test'), $result);
+ $result = helper::hash_key('test/test', $definition);
+ $this->assertEquals(sha1($definition->generate_single_key_prefix() . '-test/test'), $result);
}
/**
@@ -241,17 +239,17 @@ class administration_helper_test extends \advanced_testcase {
// Create a test cache definition and put items in it.
$instance = cache_config_testing::instance(true);
$instance->phpunit_add_definition('phpunit/test', [
- 'mode' => cache_store::MODE_APPLICATION,
+ 'mode' => store::MODE_APPLICATION,
'component' => 'phpunit',
'area' => 'test',
- 'simplekeys' => true
+ 'simplekeys' => true,
]);
$cache = \cache::make('phpunit', 'test');
for ($i = 0; $i < 100; $i++) {
$cache->set('key' . $i, str_repeat('x', $i));
}
- $factory = cache_factory::instance();
+ $factory = factory::instance();
$adminhelper = $factory->get_administration_display_helper();
$usage = $adminhelper->get_usage(10)['phpunit/test'];
diff --git a/cache/tests/allow_temporary_caches_test.php b/cache/tests/allow_temporary_caches_test.php
index cd1879830f6..9272a7c79dd 100644
--- a/cache/tests/allow_temporary_caches_test.php
+++ b/cache/tests/allow_temporary_caches_test.php
@@ -25,8 +25,7 @@ namespace core_cache;
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
* @covers \core_cache\allow_temporary_caches
*/
-class allow_temporary_caches_test extends \advanced_testcase {
-
+final class allow_temporary_caches_test extends \advanced_testcase {
/**
* Tests whether temporary caches are allowed.
*/
@@ -92,8 +91,8 @@ class allow_temporary_caches_test extends \advanced_testcase {
get_fast_modinfo($course);
} finally {
// You have to do this after phpunit_disable or it breaks later tests.
- \cache_factory::reset();
- \cache_factory::instance(true);
+ factory::reset();
+ factory::instance(true);
}
}
}
diff --git a/cache/tests/cache_helper_test.php b/cache/tests/cache_helper_test.php
index fb8dc3b1f7e..135e3bf9494 100644
--- a/cache/tests/cache_helper_test.php
+++ b/cache/tests/cache_helper_test.php
@@ -19,23 +19,22 @@ namespace core_cache;
/**
* PHPunit tests for the cache_helper class.
*
- * @package core
+ * @package core_cache
* @category cache
* @copyright 2023 Andrew Lyons
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
- * @coversDefaultClass \cache_helper
+ * @covers \core_cache\helper
*/
-class cache_helper_test extends \advanced_testcase {
+final class cache_helper_test extends \advanced_testcase {
/**
* Test the result_found method.
*
* @param mixed $value
* @param bool $expected
* @dataProvider result_found_provider
- * @covers ::result_found
*/
public function test_result_found($value, bool $expected): void {
- $this->assertEquals($expected, \cache_helper::result_found($value));
+ $this->assertEquals($expected, helper::result_found($value));
}
/**
@@ -43,7 +42,7 @@ class cache_helper_test extends \advanced_testcase {
*
* @return array
*/
- public function result_found_provider(): array {
+ public static function result_found_provider(): array {
return [
// Only false values are considered as not found.
[false, false],
diff --git a/cache/tests/cache_test.php b/cache/tests/cache_test.php
index c6371b4b5df..86c12a6ae31 100644
--- a/cache/tests/cache_test.php
+++ b/cache/tests/cache_test.php
@@ -16,17 +16,7 @@
namespace core_cache;
-use cache;
-use cache_application;
-use cache_config;
-use cache_config_disabled;
use cache_config_testing;
-use cache_definition;
-use cache_disabled;
-use cache_factory;
-use cache_factory_disabled;
-use cache_helper;
-use cache_loader;
use cache_phpunit_application;
use cache_phpunit_cache;
use cache_phpunit_dummy_object;
@@ -34,10 +24,11 @@ use cache_phpunit_dummy_overrideclass;
use cache_phpunit_factory;
use cache_phpunit_request;
use cache_phpunit_session;
-use cache_request;
-use cache_session;
-use cache_store;
-use cacheable_object_array;
+use cachestore_file;
+use cachestore_session;
+use cachestore_static;
+use core\exception\coding_exception;
+use core\exception\moodle_exception;
/**
* PHPunit tests for the cache API
@@ -45,22 +36,19 @@ use cacheable_object_array;
* This file is part of Moodle's cache API, affectionately called MUC.
* It contains the components that are requried in order to use caching.
*
- * @package core
+ * @package core_cache
* @category cache
* @copyright 2012 Sam Hemelryk
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
- * @coversDefaultClass \cache
- * @covers \cache
+ * @covers \core_cache\cache
*/
-class cache_test extends \advanced_testcase {
-
+final class cache_test extends \advanced_testcase {
/**
* Load required libraries and fixtures.
*/
public static function setUpBeforeClass(): void {
global $CFG;
- require_once($CFG->dirroot . '/cache/locallib.php');
require_once($CFG->dirroot . '/cache/tests/fixtures/lib.php');
require_once($CFG->dirroot . '/cache/tests/fixtures/cache_phpunit_dummy_datasource_versionable.php');
parent::setUpBeforeClass();
@@ -71,7 +59,7 @@ class cache_test extends \advanced_testcase {
*/
public function setUp(): void {
parent::setUp();
- cache_factory::reset();
+ factory::reset();
cache_config_testing::create_default_configuration();
}
@@ -80,39 +68,60 @@ class cache_test extends \advanced_testcase {
*/
public static function tearDownAfterClass(): void {
parent::tearDownAfterClass();
- cache_factory::reset();
+ factory::reset();
+ }
+
+ /**
+ * Check if the $CFG->altcacheconfigpath tests can be run and skip the test if not.
+ *
+ * @throws \PHPUnit\Framework\SkippedTestError if the test is skipped
+ */
+ protected function skip_if_empty_alt_cache_path(): void {
+ if ((defined('TEST_CACHE_USING_ALT_CACHE_CONFIG_PATH') && TEST_CACHE_USING_ALT_CACHE_CONFIG_PATH)) {
+ if (!empty($CFG->altcacheconfigpath)) {
+ // We can't run this test as it requires us to delete the cache configuration script which we just
+ // cant do with a custom path in play.
+ $this->markTestSkipped('Skipped testing cache disable functionality as alt cache path is being used.');
+ }
+ }
}
/**
* Returns the expected application cache store.
+ *
* @return string
*/
- protected function get_expected_application_cache_store() {
+ protected function get_expected_application_store(): string {
global $CFG;
- $expected = 'cachestore_file';
+ $expected = cachestore_file::class;
// Verify if we are using any of the available ways to use a different application store within tests.
- if (defined('TEST_CACHE_USING_APPLICATION_STORE') && preg_match('#[a-zA-Z][a-zA-Z0-9_]*#', TEST_CACHE_USING_APPLICATION_STORE)) {
- // 1st way. Using some of the testing servers.
- $expected = 'cachestore_'.(string)TEST_CACHE_USING_APPLICATION_STORE;
+ if (!defined('TEST_CACHE_USING_APPLICATION_STORE') || empty(TEST_CACHE_USING_ALT_CACHE_CONFIG_PATH)) {
+ return $expected;
+ }
- } else if (defined('TEST_CACHE_USING_ALT_CACHE_CONFIG_PATH') && TEST_CACHE_USING_ALT_CACHE_CONFIG_PATH && !empty($CFG->altcacheconfigpath)) {
+ if (preg_match('#[a-zA-Z][a-zA-Z0-9_]*#', TEST_CACHE_USING_APPLICATION_STORE)) {
+ // 1st way. Using some of the testing servers.
+ $expected = 'cachestore_' . (string) TEST_CACHE_USING_APPLICATION_STORE;
+ } else if (!empty($CFG->altcacheconfigpath)) {
// 2nd way. Using an alternative configuration.
- $defaultstores = cache_helper::get_stores_suitable_for_mode_default();
- $instance = cache_config::instance();
+ $defaultstores = helper::get_stores_suitable_for_mode_default();
+ $instance = config::instance();
// Iterate over defined mode mappings until we get an application one not being the default.
foreach ($instance->get_mode_mappings() as $mapping) {
// If the store is not for application mode, ignore.
- if ($mapping['mode'] !== cache_store::MODE_APPLICATION) {
+ if ($mapping['mode'] !== store::MODE_APPLICATION) {
continue;
}
// If the store matches some default mapping store name, ignore.
- if (array_key_exists($mapping['store'], $defaultstores) && !empty($defaultstores[$mapping['store']]['default'])) {
- continue;
+ if (array_key_exists($mapping['store'], $defaultstores)) {
+ if (!empty($defaultstores[$mapping['store']]['default'])) {
+ continue;
+ }
}
// Arrived here, have found an application mode store not being the default mapped one (file),
// that's the one we are using in the configuration for sure.
- $expected = 'cachestore_'.$mapping['store'];
+ $expected = 'cachestore_' . $mapping['store'];
}
}
@@ -125,20 +134,9 @@ class cache_test extends \advanced_testcase {
public function test_cache_config(): void {
global $CFG;
- if (defined('TEST_CACHE_USING_ALT_CACHE_CONFIG_PATH') && TEST_CACHE_USING_ALT_CACHE_CONFIG_PATH &&
- !empty($CFG->altcacheconfigpath)) {
- // We need to skip this test - it checks the default config structure, but very likely we arn't using the
- // default config structure here so theres no point in running the test.
- $this->markTestSkipped('Skipped testing default cache config structure as alt cache path is being used.');
- }
+ $this->skip_if_empty_alt_cache_path();
- if (defined('TEST_CACHE_USING_APPLICATION_STORE')) {
- // We need to skip this test - it checks the default config structure, but very likely we arn't using the
- // default config structure here because we are testing against an alternative application store.
- $this->markTestSkipped('Skipped testing default cache config structure as alt application store is being used.');
- }
-
- $instance = cache_config::instance();
+ $instance = config::instance();
$this->assertInstanceOf(cache_config_testing::class, $instance);
$this->assertTrue(cache_config_testing::config_file_exists());
@@ -162,11 +160,11 @@ class cache_test extends \advanced_testcase {
$modemappings = $instance->get_mode_mappings();
$this->assertCount(3, $modemappings);
- $modes = array(
- cache_store::MODE_APPLICATION => false,
- cache_store::MODE_SESSION => false,
- cache_store::MODE_REQUEST => false,
- );
+ $modes = [
+ store::MODE_APPLICATION => false,
+ store::MODE_SESSION => false,
+ store::MODE_REQUEST => false,
+ ];
foreach ($modemappings as $mapping) {
// We expect 3 properties.
$this->assertCount(3, $mapping);
@@ -200,13 +198,13 @@ class cache_test extends \advanced_testcase {
*/
public function test_windows_nasty_keys(): void {
$instance = cache_config_testing::instance();
- $instance->phpunit_add_definition('phpunit/windowskeytest', array(
- 'mode' => cache_store::MODE_APPLICATION,
+ $instance->phpunit_add_definition('phpunit/windowskeytest', [
+ 'mode' => store::MODE_APPLICATION,
'component' => 'phpunit',
'area' => 'windowskeytest',
'simplekeys' => true,
- 'simpledata' => true
- ));
+ 'simpledata' => true,
+ ]);
$cache = cache::make('phpunit', 'windowskeytest');
$this->assertTrue($cache->set('contest', 'test data 1'));
$this->assertEquals('test data 1', $cache->get('contest'));
@@ -219,40 +217,40 @@ class cache_test extends \advanced_testcase {
*/
public function test_set_identifiers(): void {
$instance = cache_config_testing::instance();
- $instance->phpunit_add_definition('phpunit/identifier', array(
- 'mode' => cache_store::MODE_APPLICATION,
+ $instance->phpunit_add_definition('phpunit/identifier', [
+ 'mode' => store::MODE_APPLICATION,
'component' => 'phpunit',
'area' => 'identifier',
'simplekeys' => true,
'simpledata' => true,
- 'staticacceleration' => true
- ));
- $cache = cache::make('phpunit', 'identifier', array('area'));
+ 'staticacceleration' => true,
+ ]);
+ $cache = cache::make('phpunit', 'identifier', ['area']);
$this->assertTrue($cache->set('contest', 'test data 1'));
$this->assertEquals('test data 1', $cache->get('contest'));
- $this->expectException('coding_exception');
- $cache->set_identifiers(array());
+ $this->expectException(coding_exception::class);
+ $cache->set_identifiers([]);
}
/**
* Tests the default application cache
*/
public function test_default_application_cache(): void {
- $cache = cache::make_from_params(cache_store::MODE_APPLICATION, 'phpunit', 'applicationtest');
- $this->assertInstanceOf(cache_application::class, $cache);
+ $cache = cache::make_from_params(store::MODE_APPLICATION, 'phpunit', 'applicationtest');
+ $this->assertInstanceOf(application_cache::class, $cache);
$this->run_on_cache($cache);
- $instance = cache_config_testing::instance(true);
- $instance->phpunit_add_definition('phpunit/test_default_application_cache', array(
- 'mode' => cache_store::MODE_APPLICATION,
+ $instance = cache_config_testing::instance();
+ $instance->phpunit_add_definition('phpunit/test_default_application_cache', [
+ 'mode' => store::MODE_APPLICATION,
'component' => 'phpunit',
'area' => 'test_default_application_cache',
'staticacceleration' => true,
- 'staticaccelerationsize' => 1
- ));
+ 'staticaccelerationsize' => 1,
+ ]);
$cache = cache::make('phpunit', 'test_default_application_cache');
- $this->assertInstanceOf(cache_application::class, $cache);
+ $this->assertInstanceOf(application_cache::class, $cache);
$this->run_on_cache($cache);
}
@@ -260,8 +258,8 @@ class cache_test extends \advanced_testcase {
* Tests the default session cache
*/
public function test_default_session_cache(): void {
- $cache = cache::make_from_params(cache_store::MODE_SESSION, 'phpunit', 'applicationtest');
- $this->assertInstanceOf(cache_session::class, $cache);
+ $cache = cache::make_from_params(store::MODE_SESSION, 'phpunit', 'applicationtest');
+ $this->assertInstanceOf(session_cache::class, $cache);
$this->run_on_cache($cache);
}
@@ -269,8 +267,8 @@ class cache_test extends \advanced_testcase {
* Tests the default request cache
*/
public function test_default_request_cache(): void {
- $cache = cache::make_from_params(cache_store::MODE_REQUEST, 'phpunit', 'applicationtest');
- $this->assertInstanceOf(cache_request::class, $cache);
+ $cache = cache::make_from_params(store::MODE_REQUEST, 'phpunit', 'applicationtest');
+ $this->assertInstanceOf(request_cache::class, $cache);
$this->run_on_cache($cache);
}
@@ -278,18 +276,18 @@ class cache_test extends \advanced_testcase {
* Tests using a cache system when there are no stores available (who knows what the admin did to achieve this).
*/
public function test_on_cache_without_store(): void {
- $instance = cache_config_testing::instance(true);
- $instance->phpunit_add_definition('phpunit/nostoretest1', array(
- 'mode' => cache_store::MODE_APPLICATION,
+ $instance = cache_config_testing::instance();
+ $instance->phpunit_add_definition('phpunit/nostoretest1', [
+ 'mode' => store::MODE_APPLICATION,
'component' => 'phpunit',
'area' => 'nostoretest1',
- ));
- $instance->phpunit_add_definition('phpunit/nostoretest2', array(
- 'mode' => cache_store::MODE_APPLICATION,
+ ]);
+ $instance->phpunit_add_definition('phpunit/nostoretest2', [
+ 'mode' => store::MODE_APPLICATION,
'component' => 'phpunit',
'area' => 'nostoretest2',
- 'staticacceleration' => true
- ));
+ 'staticacceleration' => true,
+ ]);
$instance->phpunit_remove_stores();
$cache = cache::make('phpunit', 'nostoretest1');
@@ -304,12 +302,12 @@ class cache_test extends \advanced_testcase {
*
* This function is great because we can use it to ensure all of the loaders perform exactly the same way.
*
- * @param cache_loader $cache
+ * @param loader_interface $cache
*/
- protected function run_on_cache(cache_loader $cache) {
+ protected function run_on_cache(loader_interface $cache) {
$key = 'contestkey';
- $datascalars = array('test data', null);
- $dataarray = array('contest' => 'data', 'part' => 'two');
+ $datascalars = ['test data', null];
+ $dataarray = ['contest' => 'data', 'part' => 'two'];
$dataobject = (object)$dataarray;
foreach ($datascalars as $datascalar) {
@@ -318,11 +316,11 @@ class cache_test extends \advanced_testcase {
// Check all read methods.
$this->assertFalse($cache->get($key));
$this->assertFalse($cache->has($key));
- $result = $cache->get_many(array($key));
+ $result = $cache->get_many([$key]);
$this->assertCount(1, $result);
$this->assertFalse(reset($result));
- $this->assertFalse($cache->has_any(array($key)));
- $this->assertFalse($cache->has_all(array($key)));
+ $this->assertFalse($cache->has_any([$key]));
+ $this->assertFalse($cache->has_all([$key]));
// Set the data.
$this->assertTrue($cache->set($key, $datascalar));
@@ -332,11 +330,11 @@ class cache_test extends \advanced_testcase {
// Recheck the read methods.
$this->assertEquals($datascalar, $cache->get($key));
$this->assertTrue($cache->has($key));
- $result = $cache->get_many(array($key));
+ $result = $cache->get_many([$key]);
$this->assertCount(1, $result);
$this->assertEquals($datascalar, reset($result));
- $this->assertTrue($cache->has_any(array($key)));
- $this->assertTrue($cache->has_all(array($key)));
+ $this->assertTrue($cache->has_any([$key]));
+ $this->assertTrue($cache->has_all([$key]));
// Delete it.
$this->assertTrue($cache->delete($key));
@@ -365,11 +363,10 @@ class cache_test extends \advanced_testcase {
// Test array of objects.
$specobject = new cache_phpunit_dummy_object('red', 'blue', $starttime);
- $data = new cacheable_object_array(array(
+ $data = new cacheable_object_array([
clone($specobject),
clone($specobject),
- clone($specobject))
- );
+ clone($specobject), ]);
$this->assertTrue($cache->set($key, $data));
$result = $cache->get($key);
$this->assertInstanceOf(cacheable_object_array::class, $result);
@@ -383,7 +380,7 @@ class cache_test extends \advanced_testcase {
}
// Test set many.
- $cache->set_many(array('key1' => 'data1', 'key2' => 'data2', 'key3' => null));
+ $cache->set_many(['key1' => 'data1', 'key2' => 'data2', 'key3' => null]);
$this->assertEquals('data1', $cache->get('key1'));
$this->assertEquals('data2', $cache->get('key2'));
$this->assertEquals(null, $cache->get('key3'));
@@ -391,17 +388,17 @@ class cache_test extends \advanced_testcase {
$this->assertTrue($cache->delete('key2'));
$this->assertTrue($cache->delete('key3'));
- $cache->set_many(array(
- 'key1' => array(1, 2, 3),
- 'key2' => array(3, 2, 1),
- ));
+ $cache->set_many([
+ 'key1' => [1, 2, 3],
+ 'key2' => [3, 2, 1],
+ ]);
$this->assertIsArray($cache->get('key1'));
$this->assertIsArray($cache->get('key2'));
$this->assertCount(3, $cache->get('key1'));
$this->assertCount(3, $cache->get('key2'));
- $this->assertIsArray($cache->get_many(array('key1', 'key2')));
- $this->assertCount(2, $cache->get_many(array('key1', 'key2')));
- $this->assertEquals(2, $cache->delete_many(array('key1', 'key2')));
+ $this->assertIsArray($cache->get_many(['key1', 'key2']));
+ $this->assertCount(2, $cache->get_many(['key1', 'key2']));
+ $this->assertEquals(2, $cache->delete_many(['key1', 'key2']));
// Test delete many.
$this->assertTrue($cache->set('key1', 'data1'));
@@ -412,14 +409,14 @@ class cache_test extends \advanced_testcase {
$this->assertEquals('data2', $cache->get('key2'));
$this->assertEquals(null, $cache->get('key3'));
- $this->assertEquals(3, $cache->delete_many(array('key1', 'key2', 'key3')));
+ $this->assertEquals(3, $cache->delete_many(['key1', 'key2', 'key3']));
$this->assertFalse($cache->get('key1'));
$this->assertFalse($cache->get('key2'));
$this->assertFalse($cache->get('key3'));
// Quick reference test.
- $obj = new \stdClass;
+ $obj = new \stdClass();
$obj->key = 'value';
$ref =& $obj;
$this->assertTrue($cache->set('obj', $obj));
@@ -437,11 +434,11 @@ class cache_test extends \advanced_testcase {
$this->assertTrue($cache->delete('obj'));
// Deep reference test.
- $obj1 = new \stdClass;
+ $obj1 = new \stdClass();
$obj1->key = 'value';
- $obj2 = new \stdClass;
+ $obj2 = new \stdClass();
$obj2->key = 'test';
- $obj3 = new \stdClass;
+ $obj3 = new \stdClass();
$obj3->key = 'pork';
$obj1->subobj =& $obj2;
$obj2->subobj =& $obj3;
@@ -460,7 +457,7 @@ class cache_test extends \advanced_testcase {
$this->assertTrue($cache->delete('obj'));
// Death reference test... basically we don't want this to die.
- $obj = new \stdClass;
+ $obj = new \stdClass();
$obj->key = 'value';
$obj->self =& $obj;
$this->assertTrue($cache->set('obj', $obj));
@@ -469,7 +466,7 @@ class cache_test extends \advanced_testcase {
$this->assertEquals('value', $var->key);
// Reference test after retrieve.
- $obj = new \stdClass;
+ $obj = new \stdClass();
$obj->key = 'value';
$this->assertTrue($cache->set('obj', $obj));
@@ -486,26 +483,26 @@ class cache_test extends \advanced_testcase {
$this->assertTrue($cache->delete('obj'));
// Death reference test on get_many... basically we don't want this to die.
- $obj = new \stdClass;
+ $obj = new \stdClass();
$obj->key = 'value';
$obj->self =& $obj;
- $this->assertEquals(1, $cache->set_many(array('obj' => $obj)));
- $var = $cache->get_many(array('obj'));
+ $this->assertEquals(1, $cache->set_many(['obj' => $obj]));
+ $var = $cache->get_many(['obj']);
$this->assertInstanceOf(\stdClass::class, $var['obj']);
$this->assertEquals('value', $var['obj']->key);
// Reference test after retrieve.
- $obj = new \stdClass;
+ $obj = new \stdClass();
$obj->key = 'value';
- $this->assertEquals(1, $cache->set_many(array('obj' => $obj)));
+ $this->assertEquals(1, $cache->set_many(['obj' => $obj]));
- $var1 = $cache->get_many(array('obj'));
+ $var1 = $cache->get_many(['obj']);
$this->assertInstanceOf(\stdClass::class, $var1['obj']);
$this->assertEquals('value', $var1['obj']->key);
$var1['obj']->key = 'eulav';
$this->assertEquals('eulav', $var1['obj']->key);
- $var2 = $cache->get_many(array('obj'));
+ $var2 = $cache->get_many(['obj']);
$this->assertInstanceOf(\stdClass::class, $var2['obj']);
$this->assertEquals('value', $var2['obj']->key);
@@ -519,14 +516,14 @@ class cache_test extends \advanced_testcase {
$this->assertTrue(true);
}
try {
- $cache->get_many(array('exception1', 'exception2'), MUST_EXIST);
+ $cache->get_many(['exception1', 'exception2'], MUST_EXIST);
$this->fail('Exception expected from cache::get_many using MUST_EXIST');
} catch (\Exception $e) {
$this->assertTrue(true);
}
$cache->set('test', 'test');
try {
- $cache->get_many(array('test', 'exception'), MUST_EXIST);
+ $cache->get_many(['test', 'exception'], MUST_EXIST);
$this->fail('Exception expected from cache::get_many using MUST_EXIST');
} catch (\Exception $e) {
$this->assertTrue(true);
@@ -537,17 +534,17 @@ class cache_test extends \advanced_testcase {
* Tests a definition using a data loader
*/
public function test_definition_data_loader(): void {
- $instance = cache_config_testing::instance(true);
- $instance->phpunit_add_definition('phpunit/datasourcetest', array(
- 'mode' => cache_store::MODE_APPLICATION,
+ $instance = cache_config_testing::instance();
+ $instance->phpunit_add_definition('phpunit/datasourcetest', [
+ 'mode' => store::MODE_APPLICATION,
'component' => 'phpunit',
'area' => 'datasourcetest',
'datasource' => 'cache_phpunit_dummy_datasource',
- 'datasourcefile' => 'cache/tests/fixtures/lib.php'
- ));
+ 'datasourcefile' => 'cache/tests/fixtures/lib.php',
+ ]);
$cache = cache::make('phpunit', 'datasourcetest');
- $this->assertInstanceOf(cache_application::class, $cache);
+ $this->assertInstanceOf(application_cache::class, $cache);
// Purge it to be sure.
$this->assertTrue($cache->purge());
@@ -563,7 +560,7 @@ class cache_test extends \advanced_testcase {
// Test multiple values.
$this->assertTrue($cache->purge());
$this->assertTrue($cache->set('b', 'B'));
- $result = $cache->get_many(array('a', 'b', 'c'));
+ $result = $cache->get_many(['a', 'b', 'c']);
$this->assertIsArray($result);
$this->assertCount(3, $result);
$this->assertArrayHasKey('a', $result);
@@ -576,28 +573,25 @@ class cache_test extends \advanced_testcase {
/**
* Tests a definition using a data loader with versioned keys.
- *
- * @covers ::get_versioned
- * @covers ::set_versioned
*/
public function test_definition_data_loader_versioned(): void {
// Create two definitions, one using a non-versionable data source and the other using
// a versionable one.
- $instance = cache_config_testing::instance(true);
- $instance->phpunit_add_definition('phpunit/datasourcetest1', array(
- 'mode' => cache_store::MODE_APPLICATION,
+ $instance = cache_config_testing::instance();
+ $instance->phpunit_add_definition('phpunit/datasourcetest1', [
+ 'mode' => store::MODE_APPLICATION,
'component' => 'phpunit',
'area' => 'datasourcetest1',
'datasource' => 'cache_phpunit_dummy_datasource',
- 'datasourcefile' => 'cache/tests/fixtures/lib.php'
- ));
- $instance->phpunit_add_definition('phpunit/datasourcetest2', array(
- 'mode' => cache_store::MODE_APPLICATION,
+ 'datasourcefile' => 'cache/tests/fixtures/lib.php',
+ ]);
+ $instance->phpunit_add_definition('phpunit/datasourcetest2', [
+ 'mode' => store::MODE_APPLICATION,
'component' => 'phpunit',
'area' => 'datasourcetest2',
- 'datasource' => 'cache_phpunit_dummy_datasource_versionable',
- 'datasourcefile' => 'cache/tests/fixtures/lib.php'
- ));
+ 'datasource' => \cache_phpunit_dummy_datasource_versionable::class,
+ 'datasourcefile' => 'cache/tests/fixtures/lib.php',
+ ]);
// The first data source works for normal 'get'.
$cache1 = cache::make('phpunit', 'datasourcetest1');
@@ -607,7 +601,7 @@ class cache_test extends \advanced_testcase {
try {
$cache1->get_versioned('zombie', 1);
$this->fail();
- } catch (\coding_exception $e) {
+ } catch (coding_exception $e) {
$this->assertStringContainsString('Data source is not versionable', $e->getMessage());
}
@@ -633,17 +627,17 @@ class cache_test extends \advanced_testcase {
* Tests a definition using an overridden loader
*/
public function test_definition_overridden_loader(): void {
- $instance = cache_config_testing::instance(true);
- $instance->phpunit_add_definition('phpunit/overridetest', array(
- 'mode' => cache_store::MODE_APPLICATION,
+ $instance = cache_config_testing::instance();
+ $instance->phpunit_add_definition('phpunit/overridetest', [
+ 'mode' => store::MODE_APPLICATION,
'component' => 'phpunit',
'area' => 'overridetest',
'overrideclass' => 'cache_phpunit_dummy_overrideclass',
- 'overrideclassfile' => 'cache/tests/fixtures/lib.php'
- ));
+ 'overrideclassfile' => 'cache/tests/fixtures/lib.php',
+ ]);
$cache = cache::make('phpunit', 'overridetest');
$this->assertInstanceOf(cache_phpunit_dummy_overrideclass::class, $cache);
- $this->assertInstanceOf(cache_application::class, $cache);
+ $this->assertInstanceOf(application_cache::class, $cache);
// Purge it to be sure.
$this->assertTrue($cache->purge());
// It won't be there yet.
@@ -659,28 +653,28 @@ class cache_test extends \advanced_testcase {
*/
public function test_definition_mappings_only(): void {
/** @var cache_config_testing $instance */
- $instance = cache_config_testing::instance(true);
- $instance->phpunit_add_definition('phpunit/mappingsonly', array(
- 'mode' => cache_store::MODE_APPLICATION,
+ $instance = cache_config_testing::instance();
+ $instance->phpunit_add_definition('phpunit/mappingsonly', [
+ 'mode' => store::MODE_APPLICATION,
'component' => 'phpunit',
'area' => 'mappingsonly',
- 'mappingsonly' => true
- ), false);
- $instance->phpunit_add_definition('phpunit/nonmappingsonly', array(
- 'mode' => cache_store::MODE_APPLICATION,
+ 'mappingsonly' => true,
+ ], false);
+ $instance->phpunit_add_definition('phpunit/nonmappingsonly', [
+ 'mode' => store::MODE_APPLICATION,
'component' => 'phpunit',
'area' => 'nonmappingsonly',
- 'mappingsonly' => false
- ), false);
+ 'mappingsonly' => false,
+ ], false);
$cacheonly = cache::make('phpunit', 'mappingsonly');
- $this->assertInstanceOf(cache_application::class, $cacheonly);
- $this->assertEquals('cachestore_dummy', $cacheonly->phpunit_get_store_class());
+ $this->assertInstanceOf(application_cache::class, $cacheonly);
+ $this->assertInstanceOf(dummy_cachestore::class, $cacheonly->get_store());
- $expected = $this->get_expected_application_cache_store();
+ $expected = $this->get_expected_application_store();
$cachenon = cache::make('phpunit', 'nonmappingsonly');
- $this->assertInstanceOf(cache_application::class, $cachenon);
- $this->assertEquals($expected, $cachenon->phpunit_get_store_class());
+ $this->assertInstanceOf(application_cache::class, $cachenon);
+ $this->assertInstanceOf($expected, $cachenon->get_store());
}
/**
@@ -688,11 +682,11 @@ class cache_test extends \advanced_testcase {
*/
public function test_definition(): void {
$instance = cache_config_testing::instance();
- $instance->phpunit_add_definition('phpunit/test', array(
- 'mode' => cache_store::MODE_APPLICATION,
+ $instance->phpunit_add_definition('phpunit/test', [
+ 'mode' => store::MODE_APPLICATION,
'component' => 'phpunit',
'area' => 'test',
- ));
+ ]);
$cache = cache::make('phpunit', 'test');
$this->assertTrue($cache->set('testkey1', 'test data 1'));
@@ -706,12 +700,12 @@ class cache_test extends \advanced_testcase {
*/
public function test_definition_simplekeys(): void {
$instance = cache_config_testing::instance();
- $instance->phpunit_add_definition('phpunit/simplekeytest', array(
- 'mode' => cache_store::MODE_APPLICATION,
+ $instance->phpunit_add_definition('phpunit/simplekeytest', [
+ 'mode' => store::MODE_APPLICATION,
'component' => 'phpunit',
'area' => 'simplekeytest',
- 'simplekeys' => true
- ));
+ 'simplekeys' => true,
+ ]);
$cache = cache::make('phpunit', 'simplekeytest');
$this->assertTrue($cache->set('testkey1', 'test data 1'));
@@ -731,15 +725,15 @@ class cache_test extends \advanced_testcase {
* Test a negative TTL on an application cache.
*/
public function test_application_ttl_negative(): void {
- $instance = cache_config_testing::instance(true);
- $instance->phpunit_add_definition('phpunit/ttltest', array(
- 'mode' => cache_store::MODE_APPLICATION,
+ $instance = cache_config_testing::instance();
+ $instance->phpunit_add_definition('phpunit/ttltest', [
+ 'mode' => store::MODE_APPLICATION,
'component' => 'phpunit',
'area' => 'ttltest',
- 'ttl' => -86400 // Set to a day in the past to be extra sure.
- ));
+ 'ttl' => -86400, // Set to a day in the past to be extra sure.
+ ]);
$cache = cache::make('phpunit', 'ttltest');
- $this->assertInstanceOf(cache_application::class, $cache);
+ $this->assertInstanceOf(application_cache::class, $cache);
// Purge it to be sure.
$this->assertTrue($cache->purge());
@@ -753,8 +747,8 @@ class cache_test extends \advanced_testcase {
$this->assertFalse($cache->get('Test'));
// Test with multiple keys.
- $this->assertEquals(3, $cache->set_many(array('a' => 'A', 'b' => 'B', 'c' => 'C')));
- $result = $cache->get_many(array('a', 'b', 'c'));
+ $this->assertEquals(3, $cache->set_many(['a' => 'A', 'b' => 'B', 'c' => 'C']));
+ $result = $cache->get_many(['a', 'b', 'c']);
$this->assertIsArray($result);
$this->assertCount(3, $result);
$this->assertArrayHasKey('a', $result);
@@ -765,7 +759,7 @@ class cache_test extends \advanced_testcase {
$this->assertFalse($result['c']);
// Test with multiple keys including missing ones.
- $result = $cache->get_many(array('a', 'c', 'e'));
+ $result = $cache->get_many(['a', 'c', 'e']);
$this->assertIsArray($result);
$this->assertCount(3, $result);
$this->assertArrayHasKey('a', $result);
@@ -780,15 +774,15 @@ class cache_test extends \advanced_testcase {
* Test a positive TTL on an application cache.
*/
public function test_application_ttl_positive(): void {
- $instance = cache_config_testing::instance(true);
- $instance->phpunit_add_definition('phpunit/ttltest', array(
- 'mode' => cache_store::MODE_APPLICATION,
+ $instance = cache_config_testing::instance();
+ $instance->phpunit_add_definition('phpunit/ttltest', [
+ 'mode' => store::MODE_APPLICATION,
'component' => 'phpunit',
'area' => 'ttltest',
- 'ttl' => 86400 // Set to a day in the future to be extra sure.
- ));
+ 'ttl' => 86400, // Set to a day in the future to be extra sure.
+ ]);
$cache = cache::make('phpunit', 'ttltest');
- $this->assertInstanceOf(cache_application::class, $cache);
+ $this->assertInstanceOf(application_cache::class, $cache);
// Purge it to be sure.
$this->assertTrue($cache->purge());
@@ -802,8 +796,8 @@ class cache_test extends \advanced_testcase {
$this->assertEquals('Test', $cache->get('Test'));
// Test with multiple keys.
- $this->assertEquals(3, $cache->set_many(array('a' => 'A', 'b' => 'B', 'c' => 'C')));
- $result = $cache->get_many(array('a', 'b', 'c'));
+ $this->assertEquals(3, $cache->set_many(['a' => 'A', 'b' => 'B', 'c' => 'C']));
+ $result = $cache->get_many(['a', 'b', 'c']);
$this->assertIsArray($result);
$this->assertCount(3, $result);
$this->assertArrayHasKey('a', $result);
@@ -814,7 +808,7 @@ class cache_test extends \advanced_testcase {
$this->assertEquals('C', $result['c']);
// Test with multiple keys including missing ones.
- $result = $cache->get_many(array('a', 'c', 'e'));
+ $result = $cache->get_many(['a', 'c', 'e']);
$this->assertIsArray($result);
$this->assertCount(3, $result);
$this->assertArrayHasKey('a', $result);
@@ -829,15 +823,15 @@ class cache_test extends \advanced_testcase {
* Test a negative TTL on an session cache.
*/
public function test_session_ttl_positive(): void {
- $instance = cache_config_testing::instance(true);
- $instance->phpunit_add_definition('phpunit/ttltest', array(
- 'mode' => cache_store::MODE_SESSION,
+ $instance = cache_config_testing::instance();
+ $instance->phpunit_add_definition('phpunit/ttltest', [
+ 'mode' => store::MODE_SESSION,
'component' => 'phpunit',
'area' => 'ttltest',
- 'ttl' => 86400 // Set to a day in the future to be extra sure.
- ));
+ 'ttl' => 86400, // Set to a day in the future to be extra sure.
+ ]);
$cache = cache::make('phpunit', 'ttltest');
- $this->assertInstanceOf(cache_session::class, $cache);
+ $this->assertInstanceOf(session_cache::class, $cache);
// Purge it to be sure.
$this->assertTrue($cache->purge());
@@ -851,8 +845,8 @@ class cache_test extends \advanced_testcase {
$this->assertEquals('Test', $cache->get('Test'));
// Test with multiple keys.
- $this->assertEquals(3, $cache->set_many(array('a' => 'A', 'b' => 'B', 'c' => 'C')));
- $result = $cache->get_many(array('a', 'b', 'c'));
+ $this->assertEquals(3, $cache->set_many(['a' => 'A', 'b' => 'B', 'c' => 'C']));
+ $result = $cache->get_many(['a', 'b', 'c']);
$this->assertIsArray($result);
$this->assertCount(3, $result);
$this->assertArrayHasKey('a', $result);
@@ -863,7 +857,7 @@ class cache_test extends \advanced_testcase {
$this->assertEquals('C', $result['c']);
// Test with multiple keys including missing ones.
- $result = $cache->get_many(array('a', 'c', 'e'));
+ $result = $cache->get_many(['a', 'c', 'e']);
$this->assertIsArray($result);
$this->assertCount(3, $result);
$this->assertArrayHasKey('a', $result);
@@ -879,11 +873,11 @@ class cache_test extends \advanced_testcase {
*/
public function test_application_manual_locking(): void {
$instance = cache_config_testing::instance();
- $instance->phpunit_add_definition('phpunit/lockingtest', array(
- 'mode' => cache_store::MODE_APPLICATION,
+ $instance->phpunit_add_definition('phpunit/lockingtest', [
+ 'mode' => store::MODE_APPLICATION,
'component' => 'phpunit',
- 'area' => 'lockingtest'
- ));
+ 'area' => 'lockingtest',
+ ]);
// Configure the lock timeout so the test doesn't take too long to run.
$instance->phpunit_edit_store_config('default_application', ['lockwait' => 2]);
$cache1 = cache::make('phpunit', 'lockingtest');
@@ -896,10 +890,12 @@ class cache_test extends \advanced_testcase {
try {
$cache2->acquire_lock('testkey');
$this->fail();
- } catch (\moodle_exception $e) {
+ } catch (moodle_exception $e) {
// Check the right exception message, and debug info mentions the store type.
- $this->assertMatchesRegularExpression('~Unable to acquire a lock.*cachestore_file.*~',
- $e->getMessage());
+ $this->assertMatchesRegularExpression(
+ '~Unable to acquire a lock.*cachestore_file.*~',
+ $e->getMessage()
+ );
}
$this->assertTrue($cache1->check_lock_state('testkey'));
@@ -917,14 +913,14 @@ class cache_test extends \advanced_testcase {
*/
public function test_application_event_invalidation(): void {
$instance = cache_config_testing::instance();
- $instance->phpunit_add_definition('phpunit/eventinvalidationtest', array(
- 'mode' => cache_store::MODE_APPLICATION,
+ $instance->phpunit_add_definition('phpunit/eventinvalidationtest', [
+ 'mode' => store::MODE_APPLICATION,
'component' => 'phpunit',
'area' => 'eventinvalidationtest',
- 'invalidationevents' => array(
- 'crazyevent'
- )
- ));
+ 'invalidationevents' => [
+ 'crazyevent',
+ ],
+ ]);
$cache = cache::make('phpunit', 'eventinvalidationtest');
$this->assertTrue($cache->set('testkey1', 'test data 1'));
@@ -933,7 +929,7 @@ class cache_test extends \advanced_testcase {
$this->assertEquals('test data 2', $cache->get('testkey2'));
// Test invalidating a single entry.
- cache_helper::invalidate_by_event('crazyevent', array('testkey1'));
+ helper::invalidate_by_event('crazyevent', ['testkey1']);
$this->assertFalse($cache->get('testkey1'));
$this->assertEquals('test data 2', $cache->get('testkey2'));
@@ -941,7 +937,7 @@ class cache_test extends \advanced_testcase {
$this->assertTrue($cache->set('testkey1', 'test data 1'));
// Test invalidating both entries.
- cache_helper::invalidate_by_event('crazyevent', array('testkey1', 'testkey2'));
+ helper::invalidate_by_event('crazyevent', ['testkey1', 'testkey2']);
$this->assertFalse($cache->get('testkey1'));
$this->assertFalse($cache->get('testkey2'));
@@ -952,16 +948,16 @@ class cache_test extends \advanced_testcase {
*/
public function test_session_event_invalidation(): void {
$instance = cache_config_testing::instance();
- $instance->phpunit_add_definition('phpunit/test_session_event_invalidation', array(
- 'mode' => cache_store::MODE_SESSION,
+ $instance->phpunit_add_definition('phpunit/test_session_event_invalidation', [
+ 'mode' => store::MODE_SESSION,
'component' => 'phpunit',
'area' => 'test_session_event_invalidation',
- 'invalidationevents' => array(
- 'crazyevent'
- )
- ));
+ 'invalidationevents' => [
+ 'crazyevent',
+ ],
+ ]);
$cache = cache::make('phpunit', 'test_session_event_invalidation');
- $this->assertInstanceOf(cache_session::class, $cache);
+ $this->assertInstanceOf(session_cache::class, $cache);
$this->assertTrue($cache->set('testkey1', 'test data 1'));
$this->assertEquals('test data 1', $cache->get('testkey1'));
@@ -969,7 +965,7 @@ class cache_test extends \advanced_testcase {
$this->assertEquals('test data 2', $cache->get('testkey2'));
// Test invalidating a single entry.
- cache_helper::invalidate_by_event('crazyevent', array('testkey1'));
+ helper::invalidate_by_event('crazyevent', ['testkey1']);
$this->assertFalse($cache->get('testkey1'));
$this->assertEquals('test data 2', $cache->get('testkey2'));
@@ -977,7 +973,7 @@ class cache_test extends \advanced_testcase {
$this->assertTrue($cache->set('testkey1', 'test data 1'));
// Test invalidating both entries.
- cache_helper::invalidate_by_event('crazyevent', array('testkey1', 'testkey2'));
+ helper::invalidate_by_event('crazyevent', ['testkey1', 'testkey2']);
$this->assertFalse($cache->get('testkey1'));
$this->assertFalse($cache->get('testkey2'));
@@ -988,32 +984,32 @@ class cache_test extends \advanced_testcase {
*/
public function test_application_definition_invalidation(): void {
$instance = cache_config_testing::instance();
- $instance->phpunit_add_definition('phpunit/definitioninvalidation', array(
- 'mode' => cache_store::MODE_APPLICATION,
+ $instance->phpunit_add_definition('phpunit/definitioninvalidation', [
+ 'mode' => store::MODE_APPLICATION,
'component' => 'phpunit',
- 'area' => 'definitioninvalidation'
- ));
+ 'area' => 'definitioninvalidation',
+ ]);
$cache = cache::make('phpunit', 'definitioninvalidation');
$this->assertTrue($cache->set('testkey1', 'test data 1'));
$this->assertEquals('test data 1', $cache->get('testkey1'));
$this->assertTrue($cache->set('testkey2', 'test data 2'));
$this->assertEquals('test data 2', $cache->get('testkey2'));
- cache_helper::invalidate_by_definition('phpunit', 'definitioninvalidation', array(), 'testkey1');
+ helper::invalidate_by_definition('phpunit', 'definitioninvalidation', [], 'testkey1');
$this->assertFalse($cache->get('testkey1'));
$this->assertEquals('test data 2', $cache->get('testkey2'));
$this->assertTrue($cache->set('testkey1', 'test data 1'));
- cache_helper::invalidate_by_definition('phpunit', 'definitioninvalidation', array(), array('testkey1'));
+ helper::invalidate_by_definition('phpunit', 'definitioninvalidation', [], ['testkey1']);
$this->assertFalse($cache->get('testkey1'));
$this->assertEquals('test data 2', $cache->get('testkey2'));
$this->assertTrue($cache->set('testkey1', 'test data 1'));
- cache_helper::invalidate_by_definition('phpunit', 'definitioninvalidation', array(), array('testkey1', 'testkey2'));
+ helper::invalidate_by_definition('phpunit', 'definitioninvalidation', [], ['testkey1', 'testkey2']);
$this->assertFalse($cache->get('testkey1'));
$this->assertFalse($cache->get('testkey2'));
@@ -1024,35 +1020,43 @@ class cache_test extends \advanced_testcase {
*/
public function test_session_definition_invalidation(): void {
$instance = cache_config_testing::instance();
- $instance->phpunit_add_definition('phpunit/test_session_definition_invalidation', array(
- 'mode' => cache_store::MODE_SESSION,
+ $instance->phpunit_add_definition('phpunit/test_session_definition_invalidation', [
+ 'mode' => store::MODE_SESSION,
'component' => 'phpunit',
- 'area' => 'test_session_definition_invalidation'
- ));
+ 'area' => 'test_session_definition_invalidation',
+ ]);
$cache = cache::make('phpunit', 'test_session_definition_invalidation');
- $this->assertInstanceOf(cache_session::class, $cache);
+ $this->assertInstanceOf(session_cache::class, $cache);
$this->assertTrue($cache->set('testkey1', 'test data 1'));
$this->assertEquals('test data 1', $cache->get('testkey1'));
$this->assertTrue($cache->set('testkey2', 'test data 2'));
$this->assertEquals('test data 2', $cache->get('testkey2'));
- cache_helper::invalidate_by_definition('phpunit', 'test_session_definition_invalidation', array(), 'testkey1');
+ helper::invalidate_by_definition('phpunit', 'test_session_definition_invalidation', [], 'testkey1');
$this->assertFalse($cache->get('testkey1'));
$this->assertEquals('test data 2', $cache->get('testkey2'));
$this->assertTrue($cache->set('testkey1', 'test data 1'));
- cache_helper::invalidate_by_definition('phpunit', 'test_session_definition_invalidation', array(),
- array('testkey1'));
+ helper::invalidate_by_definition(
+ 'phpunit',
+ 'test_session_definition_invalidation',
+ [],
+ ['testkey1']
+ );
$this->assertFalse($cache->get('testkey1'));
$this->assertEquals('test data 2', $cache->get('testkey2'));
$this->assertTrue($cache->set('testkey1', 'test data 1'));
- cache_helper::invalidate_by_definition('phpunit', 'test_session_definition_invalidation', array(),
- array('testkey1', 'testkey2'));
+ helper::invalidate_by_definition(
+ 'phpunit',
+ 'test_session_definition_invalidation',
+ [],
+ ['testkey1', 'testkey2']
+ );
$this->assertFalse($cache->get('testkey1'));
$this->assertFalse($cache->get('testkey2'));
@@ -1068,28 +1072,29 @@ class cache_test extends \advanced_testcase {
// disconnected/distributed setup (think load balanced server using local cache), instantiate the cache again and finally
// check that it is not picked up.
$instance = cache_config_testing::instance();
- $instance->phpunit_add_definition('phpunit/eventinvalidationtest', array(
- 'mode' => cache_store::MODE_APPLICATION,
+ $instance->phpunit_add_definition('phpunit/eventinvalidationtest', [
+ 'mode' => store::MODE_APPLICATION,
'component' => 'phpunit',
'area' => 'eventinvalidationtest',
'simplekeys' => true,
'simpledata' => true,
- 'invalidationevents' => array(
- 'crazyevent'
- )
- ));
+ 'invalidationevents' => [
+ 'crazyevent',
+ ],
+ ]);
$cache = cache::make('phpunit', 'eventinvalidationtest');
$this->assertTrue($cache->set('testkey1', 'test data 1'));
$this->assertEquals('test data 1', $cache->get('testkey1'));
- cache_helper::invalidate_by_event('crazyevent', array('testkey1'));
+ helper::invalidate_by_event('crazyevent', ['testkey1']);
$this->assertFalse($cache->get('testkey1'));
// OK data added, data invalidated, and invalidation time has been set.
// Now we need to manually add back the data and adjust the invalidation time.
- $hash = md5(cache_store::MODE_APPLICATION.'/phpunit/eventinvalidationtest/'.$CFG->wwwroot.'phpunit');
- $timefile = $CFG->dataroot."/cache/cachestore_file/default_application/phpunit_eventinvalidationtest/las-cache/lastinvalidation-$hash.cache";
+ $hash = md5(store::MODE_APPLICATION . '/phpunit/eventinvalidationtest/' . $CFG->wwwroot . 'phpunit');
+ $timefile = $CFG->dataroot .
+ "/cache/cachestore_file/default_application/phpunit_eventinvalidationtest/las-cache/lastinvalidation-$hash.cache";
// Make sure the file is correct.
$this->assertTrue(file_exists($timefile));
$timecont = serialize(cache::now(true) - 60); // Back 60sec in the past to force it to re-invalidate.
@@ -1097,39 +1102,40 @@ class cache_test extends \advanced_testcase {
file_put_contents($timefile, $timecont);
$this->assertTrue(file_exists($timefile));
- $datafile = $CFG->dataroot."/cache/cachestore_file/default_application/phpunit_eventinvalidationtest/tes-cache/testkey1-$hash.cache";
+ $datafile = $CFG->dataroot .
+ "/cache/cachestore_file/default_application/phpunit_eventinvalidationtest/tes-cache/testkey1-$hash.cache";
$datacont = serialize("test data 1");
make_writable_directory(dirname($datafile));
file_put_contents($datafile, $datacont);
$this->assertTrue(file_exists($datafile));
// Test 1: Rebuild without the event and test its there.
- cache_factory::reset();
+ factory::reset();
$instance = cache_config_testing::instance();
- $instance->phpunit_add_definition('phpunit/eventinvalidationtest', array(
- 'mode' => cache_store::MODE_APPLICATION,
+ $instance->phpunit_add_definition('phpunit/eventinvalidationtest', [
+ 'mode' => store::MODE_APPLICATION,
'component' => 'phpunit',
'area' => 'eventinvalidationtest',
'simplekeys' => true,
'simpledata' => true,
- ));
+ ]);
$cache = cache::make('phpunit', 'eventinvalidationtest');
$this->assertEquals('test data 1', $cache->get('testkey1'));
// Test 2: Rebuild and test the invalidation of the event via the invalidation cache.
- cache_factory::reset();
+ factory::reset();
$instance = cache_config_testing::instance();
- $instance->phpunit_add_definition('phpunit/eventinvalidationtest', array(
- 'mode' => cache_store::MODE_APPLICATION,
+ $instance->phpunit_add_definition('phpunit/eventinvalidationtest', [
+ 'mode' => store::MODE_APPLICATION,
'component' => 'phpunit',
'area' => 'eventinvalidationtest',
'simplekeys' => true,
'simpledata' => true,
- 'invalidationevents' => array(
- 'crazyevent'
- )
- ));
+ 'invalidationevents' => [
+ 'crazyevent',
+ ],
+ ]);
$cache = cache::make('phpunit', 'eventinvalidationtest');
$this->assertFalse($cache->get('testkey1'));
@@ -1147,7 +1153,7 @@ class cache_test extends \advanced_testcase {
// Backdate the event invalidation time by 30 seconds.
$invalidationcache = cache::make('core', 'eventinvalidation');
- $invalidationcache->set('crazyevent', array('testkey2' => cache::now() - 30));
+ $invalidationcache->set('crazyevent', ['testkey2' => cache::now() - 30]);
// Lastinvalidation should already be cache::now().
$this->assertEquals(cache::get_purge_token(), $cache->get('lastinvalidation'));
@@ -1157,31 +1163,30 @@ class cache_test extends \advanced_testcase {
$cache->set('lastinvalidation', $pasttime);
// Make a new cache class. This should not invalidate anything.
- cache_factory::instance()->reset_cache_instances();
+ factory::instance()->reset_cache_instances();
$cache = cache::make('phpunit', 'eventinvalidationtest');
// Lastinvalidation shouldn't change since it was already newer than invalidation event.
$this->assertEquals($pasttime, $cache->get('lastinvalidation'));
// Now set the event invalidation to newer than the lastinvalidation time.
- $invalidationcache->set('crazyevent', array('testkey2' => cache::now() - 5));
+ $invalidationcache->set('crazyevent', ['testkey2' => cache::now() - 5]);
// Make a new cache class. This should should invalidate testkey2.
- cache_factory::instance()->reset_cache_instances();
+ factory::instance()->reset_cache_instances();
$cache = cache::make('phpunit', 'eventinvalidationtest');
// Lastinvalidation timestamp should have updated to cache::now().
$this->assertEquals(cache::get_purge_token(), $cache->get('lastinvalidation'));
// Now simulate a purge_by_event 5 seconds ago.
$invalidationcache = cache::make('core', 'eventinvalidation');
- $invalidationcache->set('crazyevent', array('purged' => cache::now(true) - 5));
+ $invalidationcache->set('crazyevent', ['purged' => cache::now(true) - 5]);
// Set our lastinvalidation timestamp to 15 seconds ago.
$cache->set('lastinvalidation', cache::now(true) - 15);
// Make a new cache class. This should invalidate the cache.
- cache_factory::instance()->reset_cache_instances();
+ factory::instance()->reset_cache_instances();
$cache = cache::make('phpunit', 'eventinvalidationtest');
// Lastinvalidation timestamp should have updated to cache::now().
$this->assertEquals(cache::get_purge_token(), $cache->get('lastinvalidation'));
-
}
/**
@@ -1189,23 +1194,23 @@ class cache_test extends \advanced_testcase {
*/
public function test_application_event_purge(): void {
$instance = cache_config_testing::instance();
- $instance->phpunit_add_definition('phpunit/eventpurgetest', array(
- 'mode' => cache_store::MODE_APPLICATION,
+ $instance->phpunit_add_definition('phpunit/eventpurgetest', [
+ 'mode' => store::MODE_APPLICATION,
'component' => 'phpunit',
'area' => 'eventpurgetest',
- 'invalidationevents' => array(
- 'crazyevent'
- )
- ));
- $instance->phpunit_add_definition('phpunit/eventpurgetestaccelerated', array(
- 'mode' => cache_store::MODE_APPLICATION,
+ 'invalidationevents' => [
+ 'crazyevent',
+ ],
+ ]);
+ $instance->phpunit_add_definition('phpunit/eventpurgetestaccelerated', [
+ 'mode' => store::MODE_APPLICATION,
'component' => 'phpunit',
'area' => 'eventpurgetestaccelerated',
'staticacceleration' => true,
- 'invalidationevents' => array(
- 'crazyevent'
- )
- ));
+ 'invalidationevents' => [
+ 'crazyevent',
+ ],
+ ]);
$cache = cache::make('phpunit', 'eventpurgetest');
$this->assertTrue($cache->set('testkey1', 'test data 1'));
@@ -1214,7 +1219,7 @@ class cache_test extends \advanced_testcase {
$this->assertEquals('test data 2', $cache->get('testkey2'));
// Purge the event.
- cache_helper::purge_by_event('crazyevent');
+ helper::purge_by_event('crazyevent');
// Check things have been removed.
$this->assertFalse($cache->get('testkey1'));
@@ -1228,7 +1233,7 @@ class cache_test extends \advanced_testcase {
$this->assertEquals('test data 2', $cache->get('testkey2'));
// Purge the event.
- cache_helper::purge_by_event('crazyevent');
+ helper::purge_by_event('crazyevent');
// Check things have been removed.
$this->assertFalse($cache->get('testkey1'));
@@ -1240,23 +1245,23 @@ class cache_test extends \advanced_testcase {
*/
public function test_session_event_purge(): void {
$instance = cache_config_testing::instance();
- $instance->phpunit_add_definition('phpunit/eventpurgetest', array(
- 'mode' => cache_store::MODE_SESSION,
+ $instance->phpunit_add_definition('phpunit/eventpurgetest', [
+ 'mode' => store::MODE_SESSION,
'component' => 'phpunit',
'area' => 'eventpurgetest',
- 'invalidationevents' => array(
- 'crazyevent'
- )
- ));
- $instance->phpunit_add_definition('phpunit/eventpurgetestaccelerated', array(
- 'mode' => cache_store::MODE_SESSION,
+ 'invalidationevents' => [
+ 'crazyevent',
+ ],
+ ]);
+ $instance->phpunit_add_definition('phpunit/eventpurgetestaccelerated', [
+ 'mode' => store::MODE_SESSION,
'component' => 'phpunit',
'area' => 'eventpurgetestaccelerated',
'staticacceleration' => true,
- 'invalidationevents' => array(
- 'crazyevent'
- )
- ));
+ 'invalidationevents' => [
+ 'crazyevent',
+ ],
+ ]);
$cache = cache::make('phpunit', 'eventpurgetest');
$this->assertTrue($cache->set('testkey1', 'test data 1'));
@@ -1265,7 +1270,7 @@ class cache_test extends \advanced_testcase {
$this->assertEquals('test data 2', $cache->get('testkey2'));
// Purge the event.
- cache_helper::purge_by_event('crazyevent');
+ helper::purge_by_event('crazyevent');
// Check things have been removed.
$this->assertFalse($cache->get('testkey1'));
@@ -1279,7 +1284,7 @@ class cache_test extends \advanced_testcase {
$this->assertEquals('test data 2', $cache->get('testkey2'));
// Purge the event.
- cache_helper::purge_by_event('crazyevent');
+ helper::purge_by_event('crazyevent');
// Check things have been removed.
$this->assertFalse($cache->get('testkey1'));
@@ -1291,14 +1296,14 @@ class cache_test extends \advanced_testcase {
*/
public function test_application_definition_purge(): void {
$instance = cache_config_testing::instance();
- $instance->phpunit_add_definition('phpunit/definitionpurgetest', array(
- 'mode' => cache_store::MODE_APPLICATION,
+ $instance->phpunit_add_definition('phpunit/definitionpurgetest', [
+ 'mode' => store::MODE_APPLICATION,
'component' => 'phpunit',
'area' => 'definitionpurgetest',
- 'invalidationevents' => array(
- 'crazyevent'
- )
- ));
+ 'invalidationevents' => [
+ 'crazyevent',
+ ],
+ ]);
$cache = cache::make('phpunit', 'definitionpurgetest');
$this->assertTrue($cache->set('testkey1', 'test data 1'));
@@ -1307,7 +1312,7 @@ class cache_test extends \advanced_testcase {
$this->assertEquals('test data 2', $cache->get('testkey2'));
// Purge the event.
- cache_helper::purge_by_definition('phpunit', 'definitionpurgetest');
+ helper::purge_by_definition('phpunit', 'definitionpurgetest');
// Check things have been removed.
$this->assertFalse($cache->get('testkey1'));
@@ -1320,13 +1325,15 @@ class cache_test extends \advanced_testcase {
*/
public function test_alt_cache_path(): void {
global $CFG;
- if ((defined('TEST_CACHE_USING_ALT_CACHE_CONFIG_PATH') && TEST_CACHE_USING_ALT_CACHE_CONFIG_PATH) || !empty($CFG->altcacheconfigpath)) {
- $this->markTestSkipped('Skipped testing alt cache path as it is already being used.');
+
+ if ($this->skip_if_empty_alt_cache_path()) {
+ return;
}
+
$this->resetAfterTest();
- $CFG->altcacheconfigpath = $CFG->dataroot.'/cache/altcacheconfigpath';
+ $CFG->altcacheconfigpath = $CFG->dataroot . '/cache/altcacheconfigpath';
$instance = cache_config_testing::instance();
- $this->assertInstanceOf(cache_config::class, $instance);
+ $this->assertInstanceOf(config::class, $instance);
}
/**
@@ -1334,35 +1341,35 @@ class cache_test extends \advanced_testcase {
*/
public function test_disable_stores(): void {
$instance = cache_config_testing::instance();
- $instance->phpunit_add_definition('phpunit/disabletest1', array(
- 'mode' => cache_store::MODE_APPLICATION,
+ $instance->phpunit_add_definition('phpunit/disabletest1', [
+ 'mode' => store::MODE_APPLICATION,
'component' => 'phpunit',
- 'area' => 'disabletest1'
- ));
- $instance->phpunit_add_definition('phpunit/disabletest2', array(
- 'mode' => cache_store::MODE_SESSION,
+ 'area' => 'disabletest1',
+ ]);
+ $instance->phpunit_add_definition('phpunit/disabletest2', [
+ 'mode' => store::MODE_SESSION,
'component' => 'phpunit',
- 'area' => 'disabletest2'
- ));
- $instance->phpunit_add_definition('phpunit/disabletest3', array(
- 'mode' => cache_store::MODE_REQUEST,
+ 'area' => 'disabletest2',
+ ]);
+ $instance->phpunit_add_definition('phpunit/disabletest3', [
+ 'mode' => store::MODE_REQUEST,
'component' => 'phpunit',
- 'area' => 'disabletest3'
- ));
+ 'area' => 'disabletest3',
+ ]);
- $caches = array(
+ $caches = [
'disabletest1' => cache::make('phpunit', 'disabletest1'),
'disabletest2' => cache::make('phpunit', 'disabletest2'),
- 'disabletest3' => cache::make('phpunit', 'disabletest3')
- );
+ 'disabletest3' => cache::make('phpunit', 'disabletest3'),
+ ];
$this->assertInstanceOf(cache_phpunit_application::class, $caches['disabletest1']);
$this->assertInstanceOf(cache_phpunit_session::class, $caches['disabletest2']);
$this->assertInstanceOf(cache_phpunit_request::class, $caches['disabletest3']);
- $this->assertEquals('cachestore_file', $caches['disabletest1']->phpunit_get_store_class());
- $this->assertEquals('cachestore_session', $caches['disabletest2']->phpunit_get_store_class());
- $this->assertEquals('cachestore_static', $caches['disabletest3']->phpunit_get_store_class());
+ $this->assertInstanceOf(cachestore_file::class, $caches['disabletest1']->get_store());
+ $this->assertInstanceOf(cachestore_session::class, $caches['disabletest2']->get_store());
+ $this->assertInstanceOf(cachestore_static::class, $caches['disabletest3']->get_store());
foreach ($caches as $cache) {
$this->assertFalse($cache->get('test'));
@@ -1370,21 +1377,21 @@ class cache_test extends \advanced_testcase {
$this->assertEquals('test', $cache->get('test'));
}
- cache_factory::disable_stores();
+ factory::disable_stores();
- $caches = array(
+ $caches = [
'disabletest1' => cache::make('phpunit', 'disabletest1'),
'disabletest2' => cache::make('phpunit', 'disabletest2'),
- 'disabletest3' => cache::make('phpunit', 'disabletest3')
- );
+ 'disabletest3' => cache::make('phpunit', 'disabletest3'),
+ ];
$this->assertInstanceOf(cache_phpunit_application::class, $caches['disabletest1']);
$this->assertInstanceOf(cache_phpunit_session::class, $caches['disabletest2']);
$this->assertInstanceOf(cache_phpunit_request::class, $caches['disabletest3']);
- $this->assertEquals('cachestore_dummy', $caches['disabletest1']->phpunit_get_store_class());
- $this->assertEquals('cachestore_dummy', $caches['disabletest2']->phpunit_get_store_class());
- $this->assertEquals('cachestore_dummy', $caches['disabletest3']->phpunit_get_store_class());
+ $this->assertInstanceOf(dummy_cachestore::class, $caches['disabletest1']->get_store());
+ $this->assertInstanceOf(dummy_cachestore::class, $caches['disabletest2']->get_store());
+ $this->assertInstanceOf(dummy_cachestore::class, $caches['disabletest3']->get_store());
foreach ($caches as $cache) {
$this->assertFalse($cache->get('test'));
@@ -1399,37 +1406,33 @@ class cache_test extends \advanced_testcase {
public function test_disable(): void {
global $CFG;
- if ((defined('TEST_CACHE_USING_ALT_CACHE_CONFIG_PATH') && TEST_CACHE_USING_ALT_CACHE_CONFIG_PATH) || !empty($CFG->altcacheconfigpath)) {
- // We can't run this test as it requires us to delete the cache configuration script which we just
- // cant do with a custom path in play.
- $this->markTestSkipped('Skipped testing cache disable functionality as alt cache path is being used.');
- }
+ $this->skip_if_empty_alt_cache_path();
- $configfile = $CFG->dataroot.'/muc/config.php';
+ $configfile = $CFG->dataroot . '/muc/config.php';
// The config file will not exist yet as we've not done anything with the cache.
// reset_all_data removes the file and without a call to create a configuration it doesn't exist
// as yet.
$this->assertFileDoesNotExist($configfile);
- // Disable the cache
+ // Disable the cache.
cache_phpunit_factory::phpunit_disable();
// Check we get the expected disabled factory.
- $factory = cache_factory::instance();
- $this->assertInstanceOf(cache_factory_disabled::class, $factory);
+ $factory = factory::instance();
+ $this->assertInstanceOf(disabled_factory::class, $factory);
// Check we get the expected disabled config.
$config = $factory->create_config_instance();
- $this->assertInstanceOf(cache_config_disabled::class, $config);
+ $this->assertInstanceOf(disabled_config::class, $config);
// Check we get the expected disabled caches.
$cache = cache::make('core', 'string');
- $this->assertInstanceOf(cache_disabled::class, $cache);
+ $this->assertInstanceOf(disabled_cache::class, $cache);
// Test an application cache.
- $cache = cache::make_from_params(cache_store::MODE_APPLICATION, 'phpunit', 'disable');
- $this->assertInstanceOf(cache_disabled::class, $cache);
+ $cache = cache::make_from_params(store::MODE_APPLICATION, 'phpunit', 'disable');
+ $this->assertInstanceOf(disabled_cache::class, $cache);
$this->assertFalse($cache->get('test'));
$this->assertFalse($cache->get_versioned('v', 1));
@@ -1448,8 +1451,8 @@ class cache_test extends \advanced_testcase {
$this->assertTrue($cache->check_lock_state('test'));
// Test a session cache.
- $cache = cache::make_from_params(cache_store::MODE_SESSION, 'phpunit', 'disable');
- $this->assertInstanceOf(cache_disabled::class, $cache);
+ $cache = cache::make_from_params(store::MODE_SESSION, 'phpunit', 'disable');
+ $this->assertInstanceOf(disabled_cache::class, $cache);
$this->assertFalse($cache->get('test'));
$this->assertFalse($cache->get_versioned('v', 1));
@@ -1459,8 +1462,8 @@ class cache_test extends \advanced_testcase {
$this->assertTrue($cache->purge());
// Finally test a request cache.
- $cache = cache::make_from_params(cache_store::MODE_REQUEST, 'phpunit', 'disable');
- $this->assertInstanceOf(cache_disabled::class, $cache);
+ $cache = cache::make_from_params(store::MODE_REQUEST, 'phpunit', 'disable');
+ $this->assertInstanceOf(disabled_cache::class, $cache);
$this->assertFalse($cache->get('test'));
$this->assertFalse($cache->get_versioned('v', 1));
@@ -1469,30 +1472,30 @@ class cache_test extends \advanced_testcase {
$this->assertFalse($cache->delete('test'));
$this->assertTrue($cache->purge());
- cache_factory::reset();
+ factory::reset();
- $factory = cache_factory::instance(true);
+ $factory = factory::instance(true);
$config = $factory->create_config_instance();
- $this->assertEquals('cache_config_testing', get_class($config));
+ $this->assertInstanceOf(cache_config_testing::class, $config);
}
/**
* Test that multiple application loaders work ok.
*/
public function test_multiple_application_loaders(): void {
- $instance = cache_config_testing::instance(true);
+ $instance = cache_config_testing::instance();
$instance->phpunit_add_file_store('phpunittest1');
$instance->phpunit_add_file_store('phpunittest2');
- $instance->phpunit_add_definition('phpunit/multi_loader', array(
- 'mode' => cache_store::MODE_APPLICATION,
+ $instance->phpunit_add_definition('phpunit/multi_loader', [
+ 'mode' => store::MODE_APPLICATION,
'component' => 'phpunit',
- 'area' => 'multi_loader'
- ));
+ 'area' => 'multi_loader',
+ ]);
$instance->phpunit_add_definition_mapping('phpunit/multi_loader', 'phpunittest1', 3);
$instance->phpunit_add_definition_mapping('phpunit/multi_loader', 'phpunittest2', 2);
$cache = cache::make('phpunit', 'multi_loader');
- $this->assertInstanceOf(cache_application::class, $cache);
+ $this->assertInstanceOf(application_cache::class, $cache);
$this->assertFalse($cache->get('test'));
$this->assertTrue($cache->set('test', 'test'));
$this->assertEquals('test', $cache->get('test'));
@@ -1503,8 +1506,8 @@ class cache_test extends \advanced_testcase {
$this->assertFalse($cache->get('test'));
// Test the many commands.
- $this->assertEquals(3, $cache->set_many(array('a' => 'A', 'b' => 'B', 'c' => 'C')));
- $result = $cache->get_many(array('a', 'b', 'c'));
+ $this->assertEquals(3, $cache->set_many(['a' => 'A', 'b' => 'B', 'c' => 'C']));
+ $result = $cache->get_many(['a', 'b', 'c']);
$this->assertIsArray($result);
$this->assertCount(3, $result);
$this->assertArrayHasKey('a', $result);
@@ -1513,9 +1516,9 @@ class cache_test extends \advanced_testcase {
$this->assertEquals('A', $result['a']);
$this->assertEquals('B', $result['b']);
$this->assertEquals('C', $result['c']);
- $this->assertEquals($result, $cache->get_many(array('a', 'b', 'c')));
- $this->assertEquals(2, $cache->delete_many(array('a', 'c')));
- $result = $cache->get_many(array('a', 'b', 'c'));
+ $this->assertEquals($result, $cache->get_many(['a', 'b', 'c']));
+ $this->assertEquals(2, $cache->delete_many(['a', 'c']));
+ $result = $cache->get_many(['a', 'b', 'c']);
$this->assertIsArray($result);
$this->assertCount(3, $result);
$this->assertArrayHasKey('a', $result);
@@ -1532,16 +1535,16 @@ class cache_test extends \advanced_testcase {
// We should still have it on a deeper loader.
$this->assertSame('test', $cache->get('test'));
// Test non-recusive with many functions.
- $this->assertSame(3, $cache->set_many(array(
+ $this->assertSame(3, $cache->set_many([
'one' => 'one',
'two' => 'two',
- 'three' => 'three'
- )));
+ 'three' => 'three',
+ ]));
$this->assertSame('one', $cache->get('one'));
- $this->assertSame(array('two' => 'two', 'three' => 'three'), $cache->get_many(array('two', 'three')));
- $this->assertSame(3, $cache->delete_many(array('one', 'two', 'three'), false));
+ $this->assertSame(['two' => 'two', 'three' => 'three'], $cache->get_many(['two', 'three']));
+ $this->assertSame(3, $cache->delete_many(['one', 'two', 'three'], false));
$this->assertSame('one', $cache->get('one'));
- $this->assertSame(array('two' => 'two', 'three' => 'three'), $cache->get_many(array('two', 'three')));
+ $this->assertSame(['two' => 'two', 'three' => 'three'], $cache->get_many(['two', 'three']));
}
/**
@@ -1549,7 +1552,7 @@ class cache_test extends \advanced_testcase {
*
* @return array
*/
- public function ttl_or_not(): array {
+ public static function ttl_or_not(): array {
return [[false], [true]];
}
@@ -1558,7 +1561,7 @@ class cache_test extends \advanced_testcase {
*
* @return array
*/
- public function ttl_and_static_acceleration_or_not(): array {
+ public static function ttl_and_static_acceleration_or_not(): array {
return [[false, false], [false, true], [true, false], [true, true]];
}
@@ -1567,9 +1570,9 @@ class cache_test extends \advanced_testcase {
*
* @return array
*/
- public function ttl_and_simple_data_or_not(): array {
+ public static function ttl_and_simple_data_or_not(): array {
// Same values as for ttl and static acceleration (two booleans).
- return $this->ttl_and_static_acceleration_or_not();
+ return self::ttl_and_static_acceleration_or_not();
}
/**
@@ -1579,20 +1582,24 @@ class cache_test extends \advanced_testcase {
* @param bool $threelayer If true, uses a 3-layer instead of 2-layer cache
* @param bool $staticacceleration If true, enables static acceleration
* @param bool $simpledata If true, enables simple data
- * @return \cache_application Cache
+ * @return application_cache Cache
*/
- protected function create_versioned_cache(bool $ttl, bool $threelayer = false,
- bool $staticacceleration = false, bool $simpledata = false): \cache_application {
- $instance = cache_config_testing::instance(true);
+ protected function create_versioned_cache(
+ bool $ttl,
+ bool $threelayer = false,
+ bool $staticacceleration = false,
+ bool $simpledata = false
+ ): application_cache {
+ $instance = cache_config_testing::instance();
$instance->phpunit_add_file_store('a', false);
$instance->phpunit_add_file_store('b', false);
if ($threelayer) {
$instance->phpunit_add_file_store('c', false);
}
$defarray = [
- 'mode' => cache_store::MODE_APPLICATION,
+ 'mode' => store::MODE_APPLICATION,
'component' => 'phpunit',
- 'area' => 'multi_loader'
+ 'area' => 'multi_loader',
];
if ($ttl) {
$defarray['ttl'] = '600';
@@ -1621,8 +1628,6 @@ class cache_test extends \advanced_testcase {
* @dataProvider ttl_and_simple_data_or_not
* @param bool $ttl If true, uses a TTL cache.
* @param bool $simpledata If true, turns on simple data flag
- * @covers ::set_versioned
- * @covers ::get_versioned
*/
public function test_versioned_cache_basic(bool $ttl, bool $simpledata): void {
$multicache = $this->create_versioned_cache($ttl, false, false, $simpledata);
@@ -1640,8 +1645,6 @@ class cache_test extends \advanced_testcase {
* @dataProvider ttl_and_static_acceleration_or_not
* @param bool $ttl If true, uses a TTL cache.
* @param bool $staticacceleration If true, enables static acceleration
- * @covers ::set_versioned
- * @covers ::get_versioned
*/
public function test_versioned_cache_objects(bool $ttl, bool $staticacceleration): void {
$multicache = $this->create_versioned_cache($ttl, false, $staticacceleration);
@@ -1667,8 +1670,6 @@ class cache_test extends \advanced_testcase {
*
* @dataProvider ttl_or_not
* @param bool $ttl If true, uses a TTL cache.
- * @covers ::set_versioned
- * @covers ::get_versioned
*/
public function test_versioned_cache_not_exist(bool $ttl): void {
$multicache = $this->create_versioned_cache($ttl);
@@ -1687,8 +1688,6 @@ class cache_test extends \advanced_testcase {
*
* @dataProvider ttl_or_not
* @param bool $ttl If true, uses a TTL cache.
- * @covers ::set_versioned
- * @covers ::get_versioned
*/
public function test_versioned_cache_incompatible_versioning(bool $ttl): void {
$multicache = $this->create_versioned_cache($ttl);
@@ -1698,7 +1697,7 @@ class cache_test extends \advanced_testcase {
try {
$multicache->get('game');
$this->fail();
- } catch (\coding_exception $e) {
+ } catch (coding_exception $e) {
$this->assertStringContainsString('Unexpectedly found versioned cache entry', $e->getMessage());
}
@@ -1707,7 +1706,7 @@ class cache_test extends \advanced_testcase {
try {
$multicache->get_versioned('toy', 1);
$this->fail();
- } catch (\coding_exception $e) {
+ } catch (coding_exception $e) {
$this->assertStringContainsString('Unexpectedly found non-versioned cache entry', $e->getMessage());
}
}
@@ -1718,8 +1717,6 @@ class cache_test extends \advanced_testcase {
*
* @dataProvider ttl_or_not
* @param bool $ttl If true, uses a TTL cache.
- * @covers ::set_versioned
- * @covers ::get_versioned
*/
public function test_versioned_cache_single_copy(bool $ttl): void {
$multicache = $this->create_versioned_cache($ttl);
@@ -1738,8 +1735,6 @@ class cache_test extends \advanced_testcase {
*
* @dataProvider ttl_or_not
* @param bool $ttl If true, uses a TTL cache.
- * @covers ::set_versioned
- * @covers ::get_versioned
*/
public function test_versioned_cache_outdated_local(bool $ttl): void {
$multicache = $this->create_versioned_cache($ttl);
@@ -1748,13 +1743,13 @@ class cache_test extends \advanced_testcase {
$multicache->set_versioned('game', 2, 'Tag');
// Get the two separate cache stores for the multi-level cache.
- $factory = cache_factory::instance();
+ $factory = factory::instance();
$definition = $factory->create_definition('phpunit', 'multi_loader');
[0 => $storea, 1 => $storeb] = $factory->get_store_instances_in_use($definition);
// Simulate what happens if the shared cache is updated with a new version but the
// local one still has an old version.
- $hashgame = cache_helper::hash_key('game', $definition);
+ $hashgame = helper::hash_key('game', $definition);
$data = 'British Bulldog';
if ($ttl) {
$data = new \cache_ttl_wrapper($data, 600);
@@ -1774,7 +1769,7 @@ class cache_test extends \advanced_testcase {
// compare, so check it ignoring the time field.
$this->assertEquals(3, $localvalue->version);
$ttldata = $localvalue->data;
- $this->assertInstanceOf('cache_ttl_wrapper', $ttldata);
+ $this->assertInstanceOf(ttl_wrapper::class, $ttldata);
$this->assertEquals('British Bulldog', $ttldata->data);
} else {
$this->assertEquals(new \core_cache\version_wrapper('British Bulldog', 3), $localvalue);
@@ -1788,8 +1783,6 @@ class cache_test extends \advanced_testcase {
*
* @dataProvider ttl_or_not
* @param bool $ttl If true, uses a TTL cache.
- * @covers ::set_versioned
- * @covers ::get_versioned
*/
public function test_versioned_cache_deleting_outdated(bool $ttl): void {
$multicache = $this->create_versioned_cache($ttl);
@@ -1798,23 +1791,20 @@ class cache_test extends \advanced_testcase {
$multicache->set_versioned('game', 2, 'Tag');
// Get the two separate cache stores for the multi-level cache.
- $factory = cache_factory::instance();
+ $factory = factory::instance();
$definition = $factory->create_definition('phpunit', 'multi_loader');
[0 => $storea, 1 => $storeb] = $factory->get_store_instances_in_use($definition);
// If we request a newer version, then any older version should be deleted in each
// cache level.
$this->assertFalse($multicache->get_versioned('game', 4));
- $hashgame = cache_helper::hash_key('game', $definition);
+ $hashgame = helper::hash_key('game', $definition);
$this->assertFalse($storea->get($hashgame));
$this->assertFalse($storeb->get($hashgame));
}
/**
* Tests a versioned cache when using static cache.
- *
- * @covers ::set_versioned
- * @covers ::get_versioned
*/
public function test_versioned_cache_static(): void {
$staticcache = $this->create_versioned_cache(false, false, true);
@@ -1823,13 +1813,13 @@ class cache_test extends \advanced_testcase {
$staticcache->set_versioned('game', 1, 'Pooh-sticks');
// Get the first cache store (we don't need the second one for this test).
- $factory = cache_factory::instance();
+ $factory = factory::instance();
$definition = $factory->create_definition('phpunit', 'multi_loader');
[0 => $storea] = $factory->get_store_instances_in_use($definition);
// Hack a newer version into cache store without directly calling set (now the static
// has v1, store has v2). This simulates another client updating the cache.
- $hashgame = cache_helper::hash_key('game', $definition);
+ $hashgame = helper::hash_key('game', $definition);
$storea->set($hashgame, new \core_cache\version_wrapper('Tag', 2));
// Get the key from the cache, v1. This will use static acceleration.
@@ -1852,9 +1842,6 @@ class cache_test extends \advanced_testcase {
/**
* Tests basic use of 3-layer versioned caches.
- *
- * @covers ::set_versioned
- * @covers ::get_versioned
*/
public function test_versioned_cache_3_layers_basic(): void {
$multicache = $this->create_versioned_cache(false, true);
@@ -1873,9 +1860,6 @@ class cache_test extends \advanced_testcase {
/**
* Tests use of 3-layer versioned caches where the 3 layers currently have different versions.
- *
- * @covers ::set_versioned
- * @covers ::get_versioned
*/
public function test_versioned_cache_3_layers_different_data(): void {
// Set version 2 using normal method.
@@ -1883,12 +1867,12 @@ class cache_test extends \advanced_testcase {
$multicache->set_versioned('game', 2, 'Tag');
// Get the three separate cache stores for the multi-level cache.
- $factory = cache_factory::instance();
+ $factory = factory::instance();
$definition = $factory->create_definition('phpunit', 'multi_loader');
[0 => $storea, 1 => $storeb, 2 => $storec] = $factory->get_store_instances_in_use($definition);
// Set up two other versions so every level has a different version.
- $hashgame = cache_helper::hash_key('game', $definition);
+ $hashgame = helper::hash_key('game', $definition);
$storeb->set($hashgame, new \core_cache\version_wrapper('British Bulldog', 3));
$storec->set($hashgame, new \core_cache\version_wrapper('Hopscotch', 4));
@@ -1911,20 +1895,20 @@ class cache_test extends \advanced_testcase {
* Test that multiple application loaders work ok.
*/
public function test_multiple_session_loaders(): void {
- /* @var cache_config_testing $instance */
- $instance = cache_config_testing::instance(true);
+ /* @var \cache_config_testing $instance */
+ $instance = cache_config_testing::instance();
$instance->phpunit_add_session_store('phpunittest1');
$instance->phpunit_add_session_store('phpunittest2');
- $instance->phpunit_add_definition('phpunit/multi_loader', array(
- 'mode' => cache_store::MODE_SESSION,
+ $instance->phpunit_add_definition('phpunit/multi_loader', [
+ 'mode' => store::MODE_SESSION,
'component' => 'phpunit',
- 'area' => 'multi_loader'
- ));
+ 'area' => 'multi_loader',
+ ]);
$instance->phpunit_add_definition_mapping('phpunit/multi_loader', 'phpunittest1', 3);
$instance->phpunit_add_definition_mapping('phpunit/multi_loader', 'phpunittest2', 2);
$cache = cache::make('phpunit', 'multi_loader');
- $this->assertInstanceOf(cache_session::class, $cache);
+ $this->assertInstanceOf(session_cache::class, $cache);
$this->assertFalse($cache->get('test'));
$this->assertTrue($cache->set('test', 'test'));
$this->assertEquals('test', $cache->get('test'));
@@ -1935,8 +1919,8 @@ class cache_test extends \advanced_testcase {
$this->assertFalse($cache->get('test'));
// Test the many commands.
- $this->assertEquals(3, $cache->set_many(array('a' => 'A', 'b' => 'B', 'c' => 'C')));
- $result = $cache->get_many(array('a', 'b', 'c'));
+ $this->assertEquals(3, $cache->set_many(['a' => 'A', 'b' => 'B', 'c' => 'C']));
+ $result = $cache->get_many(['a', 'b', 'c']);
$this->assertIsArray($result);
$this->assertCount(3, $result);
$this->assertArrayHasKey('a', $result);
@@ -1945,9 +1929,9 @@ class cache_test extends \advanced_testcase {
$this->assertEquals('A', $result['a']);
$this->assertEquals('B', $result['b']);
$this->assertEquals('C', $result['c']);
- $this->assertEquals($result, $cache->get_many(array('a', 'b', 'c')));
- $this->assertEquals(2, $cache->delete_many(array('a', 'c')));
- $result = $cache->get_many(array('a', 'b', 'c'));
+ $this->assertEquals($result, $cache->get_many(['a', 'b', 'c']));
+ $this->assertEquals(2, $cache->delete_many(['a', 'c']));
+ $result = $cache->get_many(['a', 'b', 'c']);
$this->assertIsArray($result);
$this->assertCount(3, $result);
$this->assertArrayHasKey('a', $result);
@@ -1964,16 +1948,16 @@ class cache_test extends \advanced_testcase {
// We should still have it on a deeper loader.
$this->assertSame('test', $cache->get('test'));
// Test non-recusive with many functions.
- $this->assertSame(3, $cache->set_many(array(
+ $this->assertSame(3, $cache->set_many([
'one' => 'one',
'two' => 'two',
- 'three' => 'three'
- )));
+ 'three' => 'three',
+ ]));
$this->assertSame('one', $cache->get('one'));
- $this->assertSame(array('two' => 'two', 'three' => 'three'), $cache->get_many(array('two', 'three')));
- $this->assertSame(3, $cache->delete_many(array('one', 'two', 'three'), false));
+ $this->assertSame(['two' => 'two', 'three' => 'three'], $cache->get_many(['two', 'three']));
+ $this->assertSame(3, $cache->delete_many(['one', 'two', 'three'], false));
$this->assertSame('one', $cache->get('one'));
- $this->assertSame(array('two' => 'two', 'three' => 'three'), $cache->get_many(array('two', 'three')));
+ $this->assertSame(['two' => 'two', 'three' => 'three'], $cache->get_many(['two', 'three']));
}
/**
@@ -1981,7 +1965,7 @@ class cache_test extends \advanced_testcase {
*/
public function test_session_cache_switch_user(): void {
$this->resetAfterTest(true);
- $cache = cache::make_from_params(cache_store::MODE_SESSION, 'phpunit', 'sessioncache');
+ $cache = cache::make_from_params(store::MODE_SESSION, 'phpunit', 'sessioncache');
$user1 = $this->getDataGenerator()->create_user();
$user2 = $this->getDataGenerator()->create_user();
@@ -2009,13 +1993,13 @@ class cache_test extends \advanced_testcase {
*/
public function test_session_cache_switch_user_application_mapping(): void {
$this->resetAfterTest(true);
- $instance = cache_config_testing::instance(true);
+ $instance = cache_config_testing::instance();
$instance->phpunit_add_file_store('testfilestore');
- $instance->phpunit_add_definition('phpunit/testappsession', array(
- 'mode' => cache_store::MODE_SESSION,
+ $instance->phpunit_add_definition('phpunit/testappsession', [
+ 'mode' => store::MODE_SESSION,
'component' => 'phpunit',
- 'area' => 'testappsession'
- ));
+ 'area' => 'testappsession',
+ ]);
$instance->phpunit_add_definition_mapping('phpunit/testappsession', 'testfilestore', 3);
$cache = cache::make('phpunit', 'testappsession');
$user1 = $this->getDataGenerator()->create_user();
@@ -2044,17 +2028,17 @@ class cache_test extends \advanced_testcase {
* Test two session caches being used at once to confirm collisions don't occur.
*/
public function test_dual_session_caches(): void {
- $instance = cache_config_testing::instance(true);
- $instance->phpunit_add_definition('phpunit/testsess1', array(
- 'mode' => cache_store::MODE_SESSION,
+ $instance = cache_config_testing::instance();
+ $instance->phpunit_add_definition('phpunit/testsess1', [
+ 'mode' => store::MODE_SESSION,
'component' => 'phpunit',
- 'area' => 'testsess1'
- ));
- $instance->phpunit_add_definition('phpunit/testsess2', array(
- 'mode' => cache_store::MODE_SESSION,
+ 'area' => 'testsess1',
+ ]);
+ $instance->phpunit_add_definition('phpunit/testsess2', [
+ 'mode' => store::MODE_SESSION,
'component' => 'phpunit',
- 'area' => 'testsess2'
- ));
+ 'area' => 'testsess2',
+ ]);
$cache1 = cache::make('phpunit', 'testsess1');
$cache2 = cache::make('phpunit', 'testsess2');
@@ -2079,8 +2063,8 @@ class cache_test extends \advanced_testcase {
*/
public function test_session_cache_switch_user_multiple(): void {
$this->resetAfterTest(true);
- $cache1 = cache::make_from_params(cache_store::MODE_SESSION, 'phpunit', 'sessioncache1');
- $cache2 = cache::make_from_params(cache_store::MODE_SESSION, 'phpunit', 'sessioncache2');
+ $cache1 = cache::make_from_params(store::MODE_SESSION, 'phpunit', 'sessioncache1');
+ $cache2 = cache::make_from_params(store::MODE_SESSION, 'phpunit', 'sessioncache2');
$user1 = $this->getDataGenerator()->create_user();
$user2 = $this->getDataGenerator()->create_user();
@@ -2108,20 +2092,18 @@ class cache_test extends \advanced_testcase {
/**
* The application locking feature should work with caches that support multiple identifiers
* (static cache and MongoDB with a specific setting).
- *
- * @covers \cache_application
*/
public function test_application_locking_multiple_identifier_cache(): void {
// Get an arbitrary definition (modinfo).
- $instance = cache_config_testing::instance(true);
+ $instance = cache_config_testing::instance();
$definitions = $instance->get_definitions();
- $definition = \cache_definition::load('phpunit', $definitions['core/coursemodinfo']);
+ $definition = definition::load('phpunit', $definitions['core/coursemodinfo']);
- // Set up a static cache using that definition, wrapped in cache_application so we can do
+ // Set up a static cache using that definition, wrapped in application_cache so we can do
// locking.
$store = new \cachestore_static('test');
$store->initialise($definition);
- $cache = new cache_application($definition, $store);
+ $cache = new application_cache($definition, $store);
// Test the three locking functions.
$cache->acquire_lock('frog');
@@ -2131,21 +2113,19 @@ class cache_test extends \advanced_testcase {
/**
* Test requiring a lock before attempting to set a key.
- *
- * @covers ::set_implementation
*/
public function test_application_locking_before_write(): void {
- $instance = cache_config_testing::instance(true);
- $instance->phpunit_add_definition('phpunit/test_application_locking', array(
- 'mode' => cache_store::MODE_APPLICATION,
+ $instance = cache_config_testing::instance();
+ $instance->phpunit_add_definition('phpunit/test_application_locking', [
+ 'mode' => store::MODE_APPLICATION,
'component' => 'phpunit',
'area' => 'test_application_locking',
'staticacceleration' => true,
'staticaccelerationsize' => 1,
- 'requirelockingbeforewrite' => true
- ));
+ 'requirelockingbeforewrite' => true,
+ ]);
$cache = cache::make('phpunit', 'test_application_locking');
- $this->assertInstanceOf(cache_application::class, $cache);
+ $this->assertInstanceOf(application_cache::class, $cache);
$cache->acquire_lock('a');
try {
@@ -2156,21 +2136,23 @@ class cache_test extends \advanced_testcase {
try {
$cache->set('b', 'B');
$this->fail();
- } catch (\coding_exception $e) {
+ } catch (coding_exception $e) {
$this->assertStringContainsString(
- 'Attempted to set cache key "b" without a lock. ' .
+ 'Attempted to set cache key "b" without a lock. ' .
'Locking before writes is required for phpunit/test_application_locking',
- $e->getMessage());
+ $e->getMessage()
+ );
}
// Set many without full lock.
try {
$cache->set_many(['a' => 'AA', 'b' => 'BB']);
$this->fail();
- } catch (\coding_exception $e) {
+ } catch (coding_exception $e) {
$this->assertStringContainsString(
- 'Attempted to set cache key "b" without a lock.',
- $e->getMessage());
+ 'Attempted to set cache key "b" without a lock.',
+ $e->getMessage()
+ );
}
// Check it didn't set key a either.
@@ -2194,10 +2176,11 @@ class cache_test extends \advanced_testcase {
try {
$cache->delete('b');
$this->fail();
- } catch (\coding_exception $e) {
+ } catch (coding_exception $e) {
$this->assertStringContainsString(
- 'Attempted to delete cache key "b" without a lock.',
- $e->getMessage());
+ 'Attempted to delete cache key "b" without a lock.',
+ $e->getMessage()
+ );
}
// Delete many without full lock.
@@ -2205,10 +2188,11 @@ class cache_test extends \advanced_testcase {
try {
$cache->delete_many(['a', 'b']);
$this->fail();
- } catch (\coding_exception $e) {
+ } catch (coding_exception $e) {
$this->assertStringContainsString(
- 'Attempted to delete cache key "b" without a lock.',
- $e->getMessage());
+ 'Attempted to delete cache key "b" without a lock.',
+ $e->getMessage()
+ );
}
// Nothing was deleted.
$this->assertEquals('AAA', $cache->get('a'));
@@ -2230,27 +2214,26 @@ class cache_test extends \advanced_testcase {
/**
* Test that locking before write works when writing across multiple layers.
*
- * @covers \cache_application
- * @return void
+ * @covers \core_cache\application_cache
*/
public function test_application_locking_multiple_layers(): void {
- $instance = cache_config_testing::instance(true);
- $instance->phpunit_add_definition('phpunit/test_application_locking', array(
- 'mode' => cache_store::MODE_APPLICATION,
+ $instance = cache_config_testing::instance();
+ $instance->phpunit_add_definition('phpunit/test_application_locking', [
+ 'mode' => store::MODE_APPLICATION,
'component' => 'phpunit',
'area' => 'test_application_locking',
'staticacceleration' => true,
'staticaccelerationsize' => 1,
- 'requirelockingbeforewrite' => true
- ), false);
+ 'requirelockingbeforewrite' => true,
+ ], false);
$instance->phpunit_add_file_store('phpunittest1');
$instance->phpunit_add_file_store('phpunittest2');
$instance->phpunit_add_definition_mapping('phpunit/test_application_locking', 'phpunittest1', 1);
$instance->phpunit_add_definition_mapping('phpunit/test_application_locking', 'phpunittest2', 2);
$cache = cache::make('phpunit', 'test_application_locking');
- $this->assertInstanceOf(cache_application::class, $cache);
+ $this->assertInstanceOf(application_cache::class, $cache);
// Check that we can set a key across multiple layers.
$cache->acquire_lock('a');
@@ -2281,7 +2264,7 @@ class cache_test extends \advanced_testcase {
$instance->phpunit_add_file_store('phpunittest3');
$instance->phpunit_add_definition_mapping('phpunit/test_application_locking', 'phpunittest3', 3);
$cache = cache::make('phpunit', 'test_application_locking');
- $this->assertInstanceOf(cache_application::class, $cache);
+ $this->assertInstanceOf(application_cache::class, $cache);
// Check that we can set a key across multiple layers.
$cache->acquire_lock('a');
@@ -2310,19 +2293,19 @@ class cache_test extends \advanced_testcase {
/**
* Tests that locking fails correctly when either layer of a 2-layer cache has a lock already.
*
- * @covers \cache_application
+ * @covers \core_cache\application_cache
*/
public function test_application_locking_multiple_layers_failures(): void {
- $instance = cache_config_testing::instance(true);
- $instance->phpunit_add_definition('phpunit/test_application_locking', array(
- 'mode' => cache_store::MODE_APPLICATION,
+ $instance = cache_config_testing::instance();
+ $instance->phpunit_add_definition('phpunit/test_application_locking', [
+ 'mode' => store::MODE_APPLICATION,
'component' => 'phpunit',
'area' => 'test_application_locking',
'staticacceleration' => true,
'staticaccelerationsize' => 1,
- 'requirelockingbeforewrite' => true
- ), false);
+ 'requirelockingbeforewrite' => true,
+ ], false);
$instance->phpunit_add_file_store('phpunittest1');
$instance->phpunit_add_file_store('phpunittest2');
$instance->phpunit_add_definition_mapping('phpunit/test_application_locking', 'phpunittest1', 1);
@@ -2349,7 +2332,7 @@ class cache_test extends \advanced_testcase {
$lockwaitprop->setValue($sharedstore, 1);
// Get key details and the cache identifier.
- $hashedkey = cache_helper::hash_key('apple', $definition);
+ $hashedkey = helper::hash_key('apple', $definition);
$localidentifier = $cache->get_identifier();
$sharedidentifier = $sharedcache->get_identifier();
@@ -2359,7 +2342,7 @@ class cache_test extends \advanced_testcase {
try {
$cache->acquire_lock('apple');
$this->fail();
- } catch (\moodle_exception $e) {
+ } catch (moodle_exception $e) { // phpcs:ignore Generic.CodeAnalysis.EmptyStatement.DetectedCatch
}
// Neither store is locked by us, shared store still locked.
@@ -2376,8 +2359,7 @@ class cache_test extends \advanced_testcase {
try {
$cache->acquire_lock('apple');
$this->fail();
- } catch (\moodle_exception $e) {
-
+ } catch (moodle_exception $e) { // phpcs:ignore Generic.CodeAnalysis.EmptyStatement.DetectedCatch
}
// Neither store is locked by us, local store still locked.
@@ -2399,24 +2381,24 @@ class cache_test extends \advanced_testcase {
}
/**
- * Test the static cache_helper method purge_stores_used_by_definition.
+ * Test the static helper method purge_stores_used_by_definition.
*/
public function test_purge_stores_used_by_definition(): void {
- $instance = cache_config_testing::instance(true);
- $instance->phpunit_add_definition('phpunit/test_purge_stores_used_by_definition', array(
- 'mode' => cache_store::MODE_APPLICATION,
+ $instance = cache_config_testing::instance();
+ $instance->phpunit_add_definition('phpunit/test_purge_stores_used_by_definition', [
+ 'mode' => store::MODE_APPLICATION,
'component' => 'phpunit',
- 'area' => 'test_purge_stores_used_by_definition'
- ));
+ 'area' => 'test_purge_stores_used_by_definition',
+ ]);
$cache = cache::make('phpunit', 'test_purge_stores_used_by_definition');
- $this->assertInstanceOf(cache_application::class, $cache);
+ $this->assertInstanceOf(application_cache::class, $cache);
$this->assertTrue($cache->set('test', 'test'));
unset($cache);
- cache_helper::purge_stores_used_by_definition('phpunit', 'test_purge_stores_used_by_definition');
+ helper::purge_stores_used_by_definition('phpunit', 'test_purge_stores_used_by_definition');
$cache = cache::make('phpunit', 'test_purge_stores_used_by_definition');
- $this->assertInstanceOf(cache_application::class, $cache);
+ $this->assertInstanceOf(application_cache::class, $cache);
$this->assertFalse($cache->get('test'));
}
@@ -2424,45 +2406,45 @@ class cache_test extends \advanced_testcase {
* Test purge routines.
*/
public function test_purge_routines(): void {
- $instance = cache_config_testing::instance(true);
- $instance->phpunit_add_definition('phpunit/purge1', array(
- 'mode' => cache_store::MODE_APPLICATION,
+ $instance = cache_config_testing::instance();
+ $instance->phpunit_add_definition('phpunit/purge1', [
+ 'mode' => store::MODE_APPLICATION,
'component' => 'phpunit',
- 'area' => 'purge1'
- ));
- $instance->phpunit_add_definition('phpunit/purge2', array(
- 'mode' => cache_store::MODE_APPLICATION,
+ 'area' => 'purge1',
+ ]);
+ $instance->phpunit_add_definition('phpunit/purge2', [
+ 'mode' => store::MODE_APPLICATION,
'component' => 'phpunit',
'area' => 'purge2',
- 'requireidentifiers' => array(
- 'id'
- )
- ));
+ 'requireidentifiers' => [
+ 'id',
+ ],
+ ]);
- $factory = cache_factory::instance();
+ $factory = factory::instance();
$definition = $factory->create_definition('phpunit', 'purge1');
$this->assertFalse($definition->has_required_identifiers());
$cache = $factory->create_cache($definition);
- $this->assertInstanceOf(cache_application::class, $cache);
+ $this->assertInstanceOf(application_cache::class, $cache);
$this->assertTrue($cache->set('test', 'test'));
$this->assertTrue($cache->has('test'));
- cache_helper::purge_by_definition('phpunit', 'purge1');
+ helper::purge_by_definition('phpunit', 'purge1');
$this->assertFalse($cache->has('test'));
- $factory = cache_factory::instance();
+ $factory = factory::instance();
$definition = $factory->create_definition('phpunit', 'purge2');
$this->assertTrue($definition->has_required_identifiers());
$cache = $factory->create_cache($definition);
- $this->assertInstanceOf(cache_application::class, $cache);
+ $this->assertInstanceOf(application_cache::class, $cache);
$this->assertTrue($cache->set('test', 'test'));
$this->assertTrue($cache->has('test'));
- cache_helper::purge_stores_used_by_definition('phpunit', 'purge2');
+ helper::purge_stores_used_by_definition('phpunit', 'purge2');
$this->assertFalse($cache->has('test'));
try {
- cache_helper::purge_by_definition('phpunit', 'purge2');
+ helper::purge_by_definition('phpunit', 'purge2');
$this->fail('Should not be able to purge a definition required identifiers without providing them.');
- } catch (\coding_exception $ex) {
+ } catch (coding_exception $ex) {
$this->assertStringContainsString('Identifier required for cache has not been provided', $ex->getMessage());
}
}
@@ -2471,9 +2453,9 @@ class cache_test extends \advanced_testcase {
* Tests that ad-hoc caches are correctly purged with a purge_all call.
*/
public function test_purge_all_with_adhoc_caches(): void {
- $cache = cache::make_from_params(cache_store::MODE_REQUEST, 'core_cache', 'test');
+ $cache = cache::make_from_params(store::MODE_REQUEST, 'core_cache', 'test');
$cache->set('test', 123);
- cache_helper::purge_all();
+ helper::purge_all();
$this->assertFalse($cache->get('test'));
}
@@ -2481,50 +2463,50 @@ class cache_test extends \advanced_testcase {
* Test that the default stores all support searching.
*/
public function test_defaults_support_searching(): void {
- $instance = cache_config_testing::instance(true);
- $instance->phpunit_add_definition('phpunit/search1', array(
- 'mode' => cache_store::MODE_APPLICATION,
+ $instance = cache_config_testing::instance();
+ $instance->phpunit_add_definition('phpunit/search1', [
+ 'mode' => store::MODE_APPLICATION,
'component' => 'phpunit',
'area' => 'search1',
- 'requiresearchable' => true
- ));
- $instance->phpunit_add_definition('phpunit/search2', array(
- 'mode' => cache_store::MODE_SESSION,
+ 'requiresearchable' => true,
+ ]);
+ $instance->phpunit_add_definition('phpunit/search2', [
+ 'mode' => store::MODE_SESSION,
'component' => 'phpunit',
'area' => 'search2',
- 'requiresearchable' => true
- ));
- $instance->phpunit_add_definition('phpunit/search3', array(
- 'mode' => cache_store::MODE_REQUEST,
+ 'requiresearchable' => true,
+ ]);
+ $instance->phpunit_add_definition('phpunit/search3', [
+ 'mode' => store::MODE_REQUEST,
'component' => 'phpunit',
'area' => 'search3',
- 'requiresearchable' => true
- ));
- $factory = cache_factory::instance();
+ 'requiresearchable' => true,
+ ]);
+ $factory = factory::instance();
// Test application cache is searchable.
$definition = $factory->create_definition('phpunit', 'search1');
- $this->assertInstanceOf(cache_definition::class, $definition);
- $this->assertEquals(cache_store::IS_SEARCHABLE, $definition->get_requirements_bin() & cache_store::IS_SEARCHABLE);
+ $this->assertInstanceOf(definition::class, $definition);
+ $this->assertEquals(store::IS_SEARCHABLE, $definition->get_requirements_bin() & store::IS_SEARCHABLE);
$cache = $factory->create_cache($definition);
- $this->assertInstanceOf(cache_application::class, $cache);
- $this->assertArrayHasKey('cache_is_searchable', $cache->phpunit_get_store_implements());
+ $this->assertInstanceOf(application_cache::class, $cache);
+ $this->assertInstanceOf(searchable_cache_interface::class, $cache->get_store());
// Test session cache is searchable.
$definition = $factory->create_definition('phpunit', 'search2');
- $this->assertInstanceOf(cache_definition::class, $definition);
- $this->assertEquals(cache_store::IS_SEARCHABLE, $definition->get_requirements_bin() & cache_store::IS_SEARCHABLE);
+ $this->assertInstanceOf(definition::class, $definition);
+ $this->assertEquals(store::IS_SEARCHABLE, $definition->get_requirements_bin() & store::IS_SEARCHABLE);
$cache = $factory->create_cache($definition);
- $this->assertInstanceOf(cache_session::class, $cache);
- $this->assertArrayHasKey('cache_is_searchable', $cache->phpunit_get_store_implements());
+ $this->assertInstanceOf(session_cache::class, $cache);
+ $this->assertInstanceOf(searchable_cache_interface::class, $cache->get_store());
// Test request cache is searchable.
$definition = $factory->create_definition('phpunit', 'search3');
- $this->assertInstanceOf(cache_definition::class, $definition);
- $this->assertEquals(cache_store::IS_SEARCHABLE, $definition->get_requirements_bin() & cache_store::IS_SEARCHABLE);
+ $this->assertInstanceOf(definition::class, $definition);
+ $this->assertEquals(store::IS_SEARCHABLE, $definition->get_requirements_bin() & store::IS_SEARCHABLE);
$cache = $factory->create_cache($definition);
- $this->assertInstanceOf(cache_request::class, $cache);
- $this->assertArrayHasKey('cache_is_searchable', $cache->phpunit_get_store_implements());
+ $this->assertInstanceOf(request_cache::class, $cache);
+ $this->assertInstanceOf(searchable_cache_interface::class, $cache->get_store());
}
/**
@@ -2535,48 +2517,48 @@ class cache_test extends \advanced_testcase {
*/
public function test_static_acceleration(): void {
$instance = cache_config_testing::instance();
- $instance->phpunit_add_definition('phpunit/accelerated', array(
- 'mode' => cache_store::MODE_APPLICATION,
+ $instance->phpunit_add_definition('phpunit/accelerated', [
+ 'mode' => store::MODE_APPLICATION,
'component' => 'phpunit',
'area' => 'accelerated',
'staticacceleration' => true,
'staticaccelerationsize' => 3,
- ));
- $instance->phpunit_add_definition('phpunit/accelerated2', array(
- 'mode' => cache_store::MODE_APPLICATION,
+ ]);
+ $instance->phpunit_add_definition('phpunit/accelerated2', [
+ 'mode' => store::MODE_APPLICATION,
'component' => 'phpunit',
'area' => 'accelerated2',
'staticacceleration' => true,
'staticaccelerationsize' => 3,
- ));
- $instance->phpunit_add_definition('phpunit/accelerated3', array(
- 'mode' => cache_store::MODE_APPLICATION,
+ ]);
+ $instance->phpunit_add_definition('phpunit/accelerated3', [
+ 'mode' => store::MODE_APPLICATION,
'component' => 'phpunit',
'area' => 'accelerated3',
'staticacceleration' => true,
'staticaccelerationsize' => 3,
- ));
- $instance->phpunit_add_definition('phpunit/accelerated4', array(
- 'mode' => cache_store::MODE_APPLICATION,
+ ]);
+ $instance->phpunit_add_definition('phpunit/accelerated4', [
+ 'mode' => store::MODE_APPLICATION,
'component' => 'phpunit',
'area' => 'accelerated4',
'staticacceleration' => true,
'staticaccelerationsize' => 4,
- ));
- $instance->phpunit_add_definition('phpunit/simpledataarea1', array(
- 'mode' => cache_store::MODE_APPLICATION,
+ ]);
+ $instance->phpunit_add_definition('phpunit/simpledataarea1', [
+ 'mode' => store::MODE_APPLICATION,
'component' => 'phpunit',
'area' => 'simpledataarea1',
'staticacceleration' => true,
- 'simpledata' => false
- ));
- $instance->phpunit_add_definition('phpunit/simpledataarea2', array(
- 'mode' => cache_store::MODE_APPLICATION,
+ 'simpledata' => false,
+ ]);
+ $instance->phpunit_add_definition('phpunit/simpledataarea2', [
+ 'mode' => store::MODE_APPLICATION,
'component' => 'phpunit',
'area' => 'simpledataarea2',
'staticacceleration' => true,
- 'simpledata' => true
- ));
+ 'simpledata' => true,
+ ]);
$cache = cache::make('phpunit', 'accelerated');
$this->assertInstanceOf(cache_phpunit_application::class, $cache);
@@ -2586,7 +2568,7 @@ class cache_test extends \advanced_testcase {
$this->assertTrue($cache->set('b', 'B'));
$this->assertTrue($cache->set('c', 'C'));
$this->assertEquals('A', $cache->get('a'));
- $this->assertEquals(array('b' => 'B', 'c' => 'C'), $cache->get_many(array('b', 'c')));
+ $this->assertEquals(['b' => 'B', 'c' => 'C'], $cache->get_many(['b', 'c']));
// Make sure all items are in static acceleration array.
$this->assertEquals('A', $cache->phpunit_static_acceleration_get('a'));
@@ -2629,7 +2611,7 @@ class cache_test extends \advanced_testcase {
$this->assertEquals('D', $cache->phpunit_static_acceleration_get('d'));
$this->assertEquals('E', $cache->phpunit_static_acceleration_get('e'));
- // Store a cacheable_object, get many times and ensure each time wake_for_cache is used.
+ // Store a cacheable_object_interface, get many times and ensure each time wake_for_cache is used.
// Both get and get_many are tested. Two cache entries are used to ensure the times aren't
// confused with multiple calls to get()/get_many().
$startmicrotime = microtime(true);
@@ -2650,7 +2632,7 @@ class cache_test extends \advanced_testcase {
$this->assertGreaterThanOrEqual($staticaccelerationreturntime, $cachevalue->propertytime);
$backingstorereturntime = $cachevalue->propertytime;
- $results = $cache->get_many(array('b'));
+ $results = $cache->get_many(['b']);
$this->assertInstanceOf(cache_phpunit_dummy_object::class, $results['b']);
$this->assertGreaterThanOrEqual($staticaccelerationreturntimeb, $results['b']->propertytime);
$backingstorereturntimeb = $results['b']->propertytime;
@@ -2662,7 +2644,7 @@ class cache_test extends \advanced_testcase {
$this->assertInstanceOf(cache_phpunit_dummy_object::class, $cachevalue);
$this->assertGreaterThanOrEqual($backingstorereturntime, $cachevalue->propertytime);
- $results = $cache->get_many(array('b'));
+ $results = $cache->get_many(['b']);
$this->assertInstanceOf(cache_phpunit_dummy_object::class, $results['b']);
$this->assertGreaterThanOrEqual($backingstorereturntimeb, $results['b']->propertytime);
@@ -2692,7 +2674,7 @@ class cache_test extends \advanced_testcase {
$this->assertFalse($cache->phpunit_static_acceleration_get('c'));
// Current keys in the array: d, e, a.
- $this->assertEquals(array('c' => 'C'), $cache->get_many(array('c')));
+ $this->assertEquals(['c' => 'C'], $cache->get_many(['c']));
// Current keys in the array: e, a, c.
$this->assertEquals('E', $cache->phpunit_static_acceleration_get('e'));
$this->assertEquals('A', $cache->phpunit_static_acceleration_get('a'));
@@ -2723,7 +2705,7 @@ class cache_test extends \advanced_testcase {
$this->assertEquals('D', $cache->phpunit_static_acceleration_get('d'));
$this->assertEquals('E', $cache->phpunit_static_acceleration_get('e'));
- $this->assertEquals(2, $cache->set_many(array('b' => 'B3', 'c' => 'C3')));
+ $this->assertEquals(2, $cache->set_many(['b' => 'B3', 'c' => 'C3']));
$this->assertFalse($cache->phpunit_static_acceleration_get('a'));
$this->assertEquals('B3', $cache->phpunit_static_acceleration_get('b'));
$this->assertEquals('C3', $cache->phpunit_static_acceleration_get('c'));
@@ -2764,9 +2746,9 @@ class cache_test extends \advanced_testcase {
}
public function test_identifiers_have_separate_caches(): void {
- $cachepg = cache::make('core', 'databasemeta', array('dbfamily' => 'pgsql'));
+ $cachepg = cache::make('core', 'databasemeta', ['dbfamily' => 'pgsql']);
$cachepg->set(1, 'here');
- $cachemy = cache::make('core', 'databasemeta', array('dbfamily' => 'mysql'));
+ $cachemy = cache::make('core', 'databasemeta', ['dbfamily' => 'mysql']);
$cachemy->set(2, 'there');
$this->assertEquals('here', $cachepg->get(1));
$this->assertEquals('there', $cachemy->get(2));
@@ -2780,30 +2762,30 @@ class cache_test extends \advanced_testcase {
$instance = cache_config_testing::instance();
$applicationid = 'phpunit/applicationperf';
- $instance->phpunit_add_definition($applicationid, array(
- 'mode' => cache_store::MODE_APPLICATION,
+ $instance->phpunit_add_definition($applicationid, [
+ 'mode' => store::MODE_APPLICATION,
'component' => 'phpunit',
- 'area' => 'applicationperf'
- ));
+ 'area' => 'applicationperf',
+ ]);
$sessionid = 'phpunit/sessionperf';
- $instance->phpunit_add_definition($sessionid, array(
- 'mode' => cache_store::MODE_SESSION,
+ $instance->phpunit_add_definition($sessionid, [
+ 'mode' => store::MODE_SESSION,
'component' => 'phpunit',
- 'area' => 'sessionperf'
- ));
+ 'area' => 'sessionperf',
+ ]);
$requestid = 'phpunit/requestperf';
- $instance->phpunit_add_definition($requestid, array(
- 'mode' => cache_store::MODE_REQUEST,
+ $instance->phpunit_add_definition($requestid, [
+ 'mode' => store::MODE_REQUEST,
'component' => 'phpunit',
- 'area' => 'requestperf'
- ));
+ 'area' => 'requestperf',
+ ]);
$application = cache::make('phpunit', 'applicationperf');
$session = cache::make('phpunit', 'sessionperf');
$request = cache::make('phpunit', 'requestperf');
// Check that no stats are recorded for these definitions yet.
- $stats = cache_helper::get_stats();
+ $stats = helper::get_stats();
$this->assertArrayNotHasKey($applicationid, $stats);
$this->assertArrayHasKey($sessionid, $stats); // Session cache sets a key on construct.
$this->assertArrayNotHasKey($requestid, $stats);
@@ -2819,7 +2801,7 @@ class cache_test extends \advanced_testcase {
$this->assertFalse($request->get('missMe'));
$this->assertFalse($request->get('missMe'));
- $endstats = cache_helper::get_stats();
+ $endstats = helper::get_stats();
$this->assertEquals(2, $endstats[$applicationid]['stores']['default_application']['misses']);
$this->assertEquals(0, $endstats[$applicationid]['stores']['default_application']['hits']);
$this->assertEquals(0, $endstats[$applicationid]['stores']['default_application']['sets']);
@@ -2830,7 +2812,7 @@ class cache_test extends \advanced_testcase {
$this->assertEquals(0, $endstats[$requestid]['stores']['default_request']['hits']);
$this->assertEquals(0, $endstats[$requestid]['stores']['default_request']['sets']);
- $startstats = cache_helper::get_stats();
+ $startstats = helper::get_stats();
// Check that stores register sets.
$this->assertTrue($application->set('setMe1', 1));
@@ -2843,7 +2825,7 @@ class cache_test extends \advanced_testcase {
$this->assertTrue($request->set('setMe3', 3));
$this->assertTrue($request->set('setMe4', 4));
- $endstats = cache_helper::get_stats();
+ $endstats = helper::get_stats();
$this->assertEquals(0, $endstats[$applicationid]['stores']['default_application']['misses'] -
$startstats[$applicationid]['stores']['default_application']['misses']);
$this->assertEquals(0, $endstats[$applicationid]['stores']['default_application']['hits'] -
@@ -2863,7 +2845,7 @@ class cache_test extends \advanced_testcase {
$this->assertEquals(4, $endstats[$requestid]['stores']['default_request']['sets'] -
$startstats[$requestid]['stores']['default_request']['sets']);
- $startstats = cache_helper::get_stats();
+ $startstats = helper::get_stats();
// Check that stores register hits.
$this->assertEquals($application->get('setMe1'), 1);
@@ -2876,7 +2858,7 @@ class cache_test extends \advanced_testcase {
$this->assertEquals($request->get('setMe3'), 3);
$this->assertEquals($request->get('setMe4'), 4);
- $endstats = cache_helper::get_stats();
+ $endstats = helper::get_stats();
$this->assertEquals(0, $endstats[$applicationid]['stores']['default_application']['misses'] -
$startstats[$applicationid]['stores']['default_application']['misses']);
$this->assertEquals(2, $endstats[$applicationid]['stores']['default_application']['hits'] -
@@ -2896,14 +2878,14 @@ class cache_test extends \advanced_testcase {
$this->assertEquals(0, $endstats[$requestid]['stores']['default_request']['sets'] -
$startstats[$requestid]['stores']['default_request']['sets']);
- $startstats = cache_helper::get_stats();
+ $startstats = helper::get_stats();
// Check that stores register through get_many.
- $application->get_many(array('setMe1', 'setMe2'));
- $session->get_many(array('setMe1', 'setMe2', 'setMe3'));
- $request->get_many(array('setMe1', 'setMe2', 'setMe3', 'setMe4'));
+ $application->get_many(['setMe1', 'setMe2']);
+ $session->get_many(['setMe1', 'setMe2', 'setMe3']);
+ $request->get_many(['setMe1', 'setMe2', 'setMe3', 'setMe4']);
- $endstats = cache_helper::get_stats();
+ $endstats = helper::get_stats();
$this->assertEquals(0, $endstats[$applicationid]['stores']['default_application']['misses'] -
$startstats[$applicationid]['stores']['default_application']['misses']);
$this->assertEquals(2, $endstats[$applicationid]['stores']['default_application']['hits'] -
@@ -2923,14 +2905,14 @@ class cache_test extends \advanced_testcase {
$this->assertEquals(0, $endstats[$requestid]['stores']['default_request']['sets'] -
$startstats[$requestid]['stores']['default_request']['sets']);
- $startstats = cache_helper::get_stats();
+ $startstats = helper::get_stats();
// Check that stores register through set_many.
$this->assertEquals(2, $application->set_many(['setMe1' => 1, 'setMe2' => 2]));
$this->assertEquals(3, $session->set_many(['setMe1' => 1, 'setMe2' => 2, 'setMe3' => 3]));
$this->assertEquals(4, $request->set_many(['setMe1' => 1, 'setMe2' => 2, 'setMe3' => 3, 'setMe4' => 4]));
- $endstats = cache_helper::get_stats();
+ $endstats = helper::get_stats();
$this->assertEquals(0, $endstats[$applicationid]['stores']['default_application']['misses'] -
$startstats[$applicationid]['stores']['default_application']['misses']);
@@ -2957,7 +2939,7 @@ class cache_test extends \advanced_testcase {
*
* @return array
*/
- public function static_acceleration_performance_provider(): array {
+ public static function static_acceleration_performance_provider(): array {
// Note: These are the delta values, not the absolute values.
// Also note that the set will actually store the valuein the static cache immediately.
$validfirst = [
@@ -2965,7 +2947,7 @@ class cache_test extends \advanced_testcase {
'hits' => 1,
'misses' => 0,
],
- cache_store::STATIC_ACCEL => [
+ store::STATIC_ACCEL => [
'hits' => 0,
'misses' => 1,
],
@@ -2976,7 +2958,7 @@ class cache_test extends \advanced_testcase {
'hits' => 0,
'misses' => 0,
],
- cache_store::STATIC_ACCEL => [
+ store::STATIC_ACCEL => [
'hits' => 1,
'misses' => 0,
],
@@ -2987,7 +2969,7 @@ class cache_test extends \advanced_testcase {
'hits' => 0,
'misses' => 1,
],
- cache_store::STATIC_ACCEL => [
+ store::STATIC_ACCEL => [
'hits' => 0,
'misses' => 1,
],
@@ -2997,11 +2979,12 @@ class cache_test extends \advanced_testcase {
'hits' => 0,
'misses' => 1,
],
- cache_store::STATIC_ACCEL => [
+ store::STATIC_ACCEL => [
'hits' => 0,
'misses' => 1,
],
- ];;
+ ];
+ ;
return [
'Truthy' => [
@@ -3052,7 +3035,7 @@ class cache_test extends \advanced_testcase {
$instance = cache_config_testing::instance();
$instance->phpunit_add_definition('phpunit/accelerated', [
- 'mode' => cache_store::MODE_APPLICATION,
+ 'mode' => store::MODE_APPLICATION,
'component' => 'phpunit',
'area' => 'accelerated',
'staticacceleration' => true,
@@ -3064,12 +3047,12 @@ class cache_test extends \advanced_testcase {
$this->assertTrue($cache->set('value', $value));
- $checkstats = function(
+ $checkstats = function (
array $start,
array $expectedstats,
): array {
$applicationid = 'phpunit/accelerated';
- $endstats = cache_helper::get_stats();
+ $endstats = helper::get_stats();
$start = $start[$applicationid]['stores'];
$end = $endstats[$applicationid]['stores'];
@@ -3091,12 +3074,12 @@ class cache_test extends \advanced_testcase {
};
// Reset the cache factory so that we can get the stats from a fresh instance.
- $factory = cache_factory::instance();
+ $factory = factory::instance();
$factory->reset_cache_instances();
$cache = cache::make('phpunit', 'accelerated');
// Get the initial stats.
- $startstats = cache_helper::get_stats();
+ $startstats = helper::get_stats();
// Fetching the value the first time should seed the static cache from the application cache.
$this->assertEquals($value, $cache->get('value'));
@@ -3116,27 +3099,27 @@ class cache_test extends \advanced_testcase {
// Create cache store with static acceleration.
$instance = cache_config_testing::instance();
$applicationid = 'phpunit/applicationperf';
- $instance->phpunit_add_definition($applicationid, array(
- 'mode' => cache_store::MODE_APPLICATION,
+ $instance->phpunit_add_definition($applicationid, [
+ 'mode' => store::MODE_APPLICATION,
'component' => 'phpunit',
'area' => 'applicationperf',
'simplekeys' => true,
'staticacceleration' => true,
- 'staticaccelerationsize' => 3
- ));
+ 'staticaccelerationsize' => 3,
+ ]);
$application = cache::make('phpunit', 'applicationperf');
// Check that stores register sets.
$this->assertTrue($application->set('setMe1', 1));
$this->assertTrue($application->set('setMe2', 0));
- $this->assertTrue($application->set('setMe3', array()));
+ $this->assertTrue($application->set('setMe3', []));
$this->assertTrue($application->get('setMe1') !== false);
$this->assertTrue($application->get('setMe2') !== false);
$this->assertTrue($application->get('setMe3') !== false);
// Check that the static acceleration worked, even on empty arrays and the number 0.
- $endstats = cache_helper::get_stats();
+ $endstats = helper::get_stats();
$this->assertEquals(0, $endstats[$applicationid]['stores']['** static accel. **']['misses']);
$this->assertEquals(3, $endstats[$applicationid]['stores']['** static accel. **']['hits']);
}
@@ -3148,30 +3131,30 @@ class cache_test extends \advanced_testcase {
$instance = cache_config_testing::instance();
$applicationid = 'phpunit/applicationperfoff';
- $instance->phpunit_add_definition($applicationid, array(
- 'mode' => cache_store::MODE_APPLICATION,
+ $instance->phpunit_add_definition($applicationid, [
+ 'mode' => store::MODE_APPLICATION,
'component' => 'phpunit',
- 'area' => 'applicationperfoff'
- ));
+ 'area' => 'applicationperfoff',
+ ]);
$sessionid = 'phpunit/sessionperfoff';
- $instance->phpunit_add_definition($sessionid, array(
- 'mode' => cache_store::MODE_SESSION,
+ $instance->phpunit_add_definition($sessionid, [
+ 'mode' => store::MODE_SESSION,
'component' => 'phpunit',
- 'area' => 'sessionperfoff'
- ));
+ 'area' => 'sessionperfoff',
+ ]);
$requestid = 'phpunit/requestperfoff';
- $instance->phpunit_add_definition($requestid, array(
- 'mode' => cache_store::MODE_REQUEST,
+ $instance->phpunit_add_definition($requestid, [
+ 'mode' => store::MODE_REQUEST,
'component' => 'phpunit',
- 'area' => 'requestperfoff'
- ));
+ 'area' => 'requestperfoff',
+ ]);
$application = cache::make('phpunit', 'applicationperfoff');
$session = cache::make('phpunit', 'sessionperfoff');
$request = cache::make('phpunit', 'requestperfoff');
// Check that no stats are recorded for these definitions yet.
- $stats = cache_helper::get_stats();
+ $stats = helper::get_stats();
$this->assertArrayNotHasKey($applicationid, $stats);
$this->assertArrayNotHasKey($sessionid, $stats);
$this->assertArrayNotHasKey($requestid, $stats);
@@ -3188,7 +3171,7 @@ class cache_test extends \advanced_testcase {
$this->assertEquals(4, $request->get('setMe'));
// Check that no stats are being recorded for these definitions.
- $endstats = cache_helper::get_stats();
+ $endstats = helper::get_stats();
$this->assertArrayNotHasKey($applicationid, $endstats);
$this->assertArrayNotHasKey($sessionid, $endstats);
$this->assertArrayNotHasKey($requestid, $endstats);
@@ -3204,24 +3187,24 @@ class cache_test extends \advanced_testcase {
*/
public function test_session_event_purge_same_second(): void {
$instance = cache_config_testing::instance();
- $instance->phpunit_add_definition('phpunit/eventpurgetest', array(
- 'mode' => cache_store::MODE_SESSION,
+ $instance->phpunit_add_definition('phpunit/eventpurgetest', [
+ 'mode' => store::MODE_SESSION,
'component' => 'phpunit',
'area' => 'eventpurgetest',
- 'invalidationevents' => array(
+ 'invalidationevents' => [
'crazyevent',
- )
- ));
+ ],
+ ]);
// Create the cache, set a value, and immediately purge it by event.
$cache = cache::make('phpunit', 'eventpurgetest');
$cache->set('testkey1', 'test data 1');
$this->assertEquals('test data 1', $cache->get('testkey1'));
- cache_helper::purge_by_event('crazyevent');
+ helper::purge_by_event('crazyevent');
$this->assertFalse($cache->get('testkey1'));
// Set up the cache again in the same request and add a new value back in.
- $factory = cache_factory::instance();
+ $factory = factory::instance();
$factory->reset_cache_instances();
$cache = cache::make('phpunit', 'eventpurgetest');
$cache->set('testkey1', 'test data 2');
@@ -3229,7 +3212,7 @@ class cache_test extends \advanced_testcase {
// Trick the cache into thinking that this is a new request.
cache_phpunit_cache::simulate_new_request();
- $factory = cache_factory::instance();
+ $factory = factory::instance();
$factory->reset_cache_instances();
// Set up the cache again.
@@ -3247,11 +3230,11 @@ class cache_test extends \advanced_testcase {
// Prepare a dummy session cache configuration.
$config = cache_config_testing::instance();
- $config->phpunit_add_definition('phpunit/test_session_distinct_storage_key', array(
- 'mode' => cache_store::MODE_SESSION,
+ $config->phpunit_add_definition('phpunit/test_session_distinct_storage_key', [
+ 'mode' => store::MODE_SESSION,
'component' => 'phpunit',
- 'area' => 'test_session_distinct_storage_key'
- ));
+ 'area' => 'test_session_distinct_storage_key',
+ ]);
// First anonymous user's session cache.
cache_phpunit_session::phpunit_mockup_session_id('foo');
@@ -3259,21 +3242,21 @@ class cache_test extends \advanced_testcase {
$cache1 = cache::make('phpunit', 'test_session_distinct_storage_key');
// Reset cache instances to emulate a new request.
- cache_factory::instance()->reset_cache_instances();
+ factory::instance()->reset_cache_instances();
// Another anonymous user's session cache.
cache_phpunit_session::phpunit_mockup_session_id('bar');
$this->setUser(0);
$cache2 = cache::make('phpunit', 'test_session_distinct_storage_key');
- cache_factory::instance()->reset_cache_instances();
+ factory::instance()->reset_cache_instances();
// Guest user's session cache.
cache_phpunit_session::phpunit_mockup_session_id('baz');
$this->setGuestUser();
$cache3 = cache::make('phpunit', 'test_session_distinct_storage_key');
- cache_factory::instance()->reset_cache_instances();
+ factory::instance()->reset_cache_instances();
// Same guest user's session cache but in another browser window.
cache_phpunit_session::phpunit_mockup_session_id('baz');
diff --git a/cache/tests/config_writer_test.php b/cache/tests/config_writer_test.php
index 40a5cbc235c..cf027cbf317 100644
--- a/cache/tests/config_writer_test.php
+++ b/cache/tests/config_writer_test.php
@@ -17,16 +17,6 @@
namespace core_cache;
use cache_config_testing;
-use cache_config_writer;
-use cache_factory;
-use cache_store;
-
-defined('MOODLE_INTERNAL') || die();
-
-// Include the necessary evils.
-global $CFG;
-require_once($CFG->dirroot.'/cache/locallib.php');
-require_once($CFG->dirroot.'/cache/tests/fixtures/lib.php');
/**
* PHPunit tests for the cache API and in particular the cache config writer.
@@ -35,15 +25,25 @@ require_once($CFG->dirroot.'/cache/tests/fixtures/lib.php');
* @category test
* @copyright 2012 Sam Hemelryk
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ * @covers \core_cache\config_writer
*/
-class config_writer_test extends \advanced_testcase {
+final class config_writer_test extends \advanced_testcase {
+ /**
+ * Load required libraries and fixtures.
+ */
+ public static function setUpBeforeClass(): void {
+ global $CFG;
+
+ require_once($CFG->dirroot . '/cache/tests/fixtures/lib.php');
+ parent::setUpBeforeClass();
+ }
/**
* Set things back to the default before each test.
*/
public function setUp(): void {
parent::setUp();
- cache_factory::reset();
+ factory::reset();
cache_config_testing::create_default_configuration();
}
@@ -52,22 +52,22 @@ class config_writer_test extends \advanced_testcase {
*/
public static function tearDownAfterClass(): void {
parent::tearDownAfterClass();
- cache_factory::reset();
+ factory::reset();
}
/**
* Test getting an instance. Pretty basic.
*/
public function test_instance(): void {
- $config = cache_config_writer::instance();
- $this->assertInstanceOf('cache_config_writer', $config);
+ $config = config_writer::instance();
+ $this->assertInstanceOf(config_writer::class, $config);
}
/**
* Test the default configuration.
*/
public function test_default_configuration(): void {
- $config = cache_config_writer::instance();
+ $config = config_writer::instance();
// First check stores.
$stores = $config->get_all_stores();
@@ -82,13 +82,13 @@ class config_writer_test extends \advanced_testcase {
$this->assertArrayHasKey('default', $store);
// Check the mode, we need at least one default store of each mode.
if (!empty($store['default'])) {
- if ($store['modes'] & cache_store::MODE_APPLICATION) {
+ if ($store['modes'] & store::MODE_APPLICATION) {
$hasapplication = true;
}
- if ($store['modes'] & cache_store::MODE_SESSION) {
+ if ($store['modes'] & store::MODE_SESSION) {
$hassession = true;
}
- if ($store['modes'] & cache_store::MODE_REQUEST) {
+ if ($store['modes'] & store::MODE_REQUEST) {
$hasrequest = true;
}
}
@@ -111,7 +111,7 @@ class config_writer_test extends \advanced_testcase {
}
$this->assertTrue($eventinvalidation, 'Missing the event invalidation definition.');
- // Next mode mappings
+ // Next mode mappings.
$mappings = $config->get_mode_mappings();
$hasapplication = false;
$hassession = false;
@@ -121,13 +121,13 @@ class config_writer_test extends \advanced_testcase {
$this->assertArrayHasKey('mode', $mode);
$this->assertArrayHasKey('store', $mode);
- if ($mode['mode'] === cache_store::MODE_APPLICATION) {
+ if ($mode['mode'] === store::MODE_APPLICATION) {
$hasapplication = true;
}
- if ($mode['mode'] === cache_store::MODE_SESSION) {
+ if ($mode['mode'] === store::MODE_SESSION) {
$hassession = true;
}
- if ($mode['mode'] === cache_store::MODE_REQUEST) {
+ if ($mode['mode'] === store::MODE_REQUEST) {
$hasrequest = true;
}
}
@@ -135,7 +135,7 @@ class config_writer_test extends \advanced_testcase {
$this->assertTrue($hassession, 'There is no mapping for the session mode.');
$this->assertTrue($hasrequest, 'There is no mapping for the request mode.');
- // Finally check config locks
+ // Finally check config locks.
$locks = $config->get_locks();
foreach ($locks as $lock) {
$this->assertArrayHasKey('name', $lock);
@@ -150,14 +150,14 @@ class config_writer_test extends \advanced_testcase {
* Test updating the definitions.
*/
public function test_update_definitions(): void {
- $config = cache_config_writer::instance();
+ $config = config_writer::instance();
// Remove the definition.
$config->phpunit_remove_definition('core/string');
$definitions = $config->get_definitions();
// Check it is gone.
$this->assertFalse(array_key_exists('core/string', $definitions));
// Update definitions. This should re-add it.
- cache_config_writer::update_definitions();
+ config_writer::update_definitions();
$definitions = $config->get_definitions();
// Check it is back again.
$this->assertTrue(array_key_exists('core/string', $definitions));
@@ -167,18 +167,18 @@ class config_writer_test extends \advanced_testcase {
* Test adding/editing/deleting store instances.
*/
public function test_add_edit_delete_plugin_instance(): void {
- $config = cache_config_writer::instance();
+ $config = config_writer::instance();
$this->assertArrayNotHasKey('addplugintest', $config->get_all_stores());
$this->assertArrayNotHasKey('addplugintestwlock', $config->get_all_stores());
// Add a default file instance.
$config->add_store_instance('addplugintest', 'file');
- cache_factory::reset();
- $config = cache_config_writer::instance();
+ factory::reset();
+ $config = config_writer::instance();
$this->assertArrayHasKey('addplugintest', $config->get_all_stores());
// Add a store with a lock described.
- $config->add_store_instance('addplugintestwlock', 'file', array('lock' => 'default_file_lock'));
+ $config->add_store_instance('addplugintestwlock', 'file', ['lock' => 'default_file_lock']);
$this->assertArrayHasKey('addplugintestwlock', $config->get_all_stores());
$config->delete_store_instance('addplugintest');
@@ -190,7 +190,7 @@ class config_writer_test extends \advanced_testcase {
$this->assertArrayNotHasKey('addplugintestwlock', $config->get_all_stores());
// Add a default file instance.
- $config->add_store_instance('storeconfigtest', 'file', array('test' => 'a', 'one' => 'two'));
+ $config->add_store_instance('storeconfigtest', 'file', ['test' => 'a', 'one' => 'two']);
$stores = $config->get_all_stores();
$this->assertArrayHasKey('storeconfigtest', $stores);
$this->assertArrayHasKey('configuration', $stores['storeconfigtest']);
@@ -199,7 +199,7 @@ class config_writer_test extends \advanced_testcase {
$this->assertEquals('a', $stores['storeconfigtest']['configuration']['test']);
$this->assertEquals('two', $stores['storeconfigtest']['configuration']['one']);
- $config->edit_store_instance('storeconfigtest', 'file', array('test' => 'b', 'one' => 'three'));
+ $config->edit_store_instance('storeconfigtest', 'file', ['test' => 'b', 'one' => 'three']);
$stores = $config->get_all_stores();
$this->assertArrayHasKey('storeconfigtest', $stores);
$this->assertArrayHasKey('configuration', $stores['storeconfigtest']);
@@ -214,22 +214,22 @@ class config_writer_test extends \advanced_testcase {
$config->delete_store_instance('default_application');
$this->fail('Default store deleted. This should not be possible!');
} catch (\Exception $e) {
- $this->assertInstanceOf('cache_exception', $e);
+ $this->assertInstanceOf(\core_cache\exception\cache_exception::class, $e);
}
try {
$config->delete_store_instance('some_crazy_store');
$this->fail('You should not be able to delete a store that does not exist.');
} catch (\Exception $e) {
- $this->assertInstanceOf('cache_exception', $e);
+ $this->assertInstanceOf(\core_cache\exception\cache_exception::class, $e);
}
try {
// Try with a plugin that does not exist.
- $config->add_store_instance('storeconfigtest', 'shallowfail', array('test' => 'a', 'one' => 'two'));
+ $config->add_store_instance('storeconfigtest', 'shallowfail', ['test' => 'a', 'one' => 'two']);
$this->fail('You should not be able to add an instance of a store that does not exist.');
} catch (\Exception $e) {
- $this->assertInstanceOf('cache_exception', $e);
+ $this->assertInstanceOf(\core_cache\exception\cache_exception::class, $e);
}
}
@@ -237,17 +237,17 @@ class config_writer_test extends \advanced_testcase {
* Test setting some mode mappings.
*/
public function test_set_mode_mappings(): void {
- $config = cache_config_writer::instance();
+ $config = config_writer::instance();
$this->assertTrue($config->add_store_instance('setmodetest', 'file'));
- $this->assertTrue($config->set_mode_mappings(array(
- cache_store::MODE_APPLICATION => array('setmodetest', 'default_application'),
- cache_store::MODE_SESSION => array('default_session'),
- cache_store::MODE_REQUEST => array('default_request'),
- )));
+ $this->assertTrue($config->set_mode_mappings([
+ store::MODE_APPLICATION => ['setmodetest', 'default_application'],
+ store::MODE_SESSION => ['default_session'],
+ store::MODE_REQUEST => ['default_request'],
+ ]));
$mappings = $config->get_mode_mappings();
$setmodetestfound = false;
foreach ($mappings as $mapping) {
- if ($mapping['store'] == 'setmodetest' && $mapping['mode'] == cache_store::MODE_APPLICATION) {
+ if ($mapping['store'] == 'setmodetest' && $mapping['mode'] == store::MODE_APPLICATION) {
$setmodetestfound = true;
}
}
@@ -258,30 +258,30 @@ class config_writer_test extends \advanced_testcase {
* Test setting some definition mappings.
*/
public function test_set_definition_mappings(): void {
- $config = cache_config_testing::instance(true);
- $config->phpunit_add_definition('phpunit/testdefinition', array(
- 'mode' => cache_store::MODE_APPLICATION,
+ $config = cache_config_testing::instance();
+ $config->phpunit_add_definition('phpunit/testdefinition', [
+ 'mode' => store::MODE_APPLICATION,
'component' => 'phpunit',
- 'area' => 'testdefinition'
- ));
+ 'area' => 'testdefinition',
+ ]);
- $config = cache_config_writer::instance();
+ $config = config_writer::instance();
$this->assertTrue($config->add_store_instance('setdefinitiontest', 'file'));
$this->assertIsArray($config->get_definition_by_id('phpunit/testdefinition'));
- $config->set_definition_mappings('phpunit/testdefinition', array('setdefinitiontest', 'default_application'));
+ $config->set_definition_mappings('phpunit/testdefinition', ['setdefinitiontest', 'default_application']);
try {
- $config->set_definition_mappings('phpunit/testdefinition', array('something that does not exist'));
+ $config->set_definition_mappings('phpunit/testdefinition', ['something that does not exist']);
$this->fail('You should not be able to set a mapping for a store that does not exist.');
} catch (\Exception $e) {
- $this->assertInstanceOf('coding_exception', $e);
+ $this->assertInstanceOf(\core\exception\coding_exception::class, $e);
}
try {
- $config->set_definition_mappings('something/crazy', array('setdefinitiontest'));
+ $config->set_definition_mappings('something/crazy', ['setdefinitiontest']);
$this->fail('You should not be able to set a mapping for a definition that does not exist.');
} catch (\Exception $e) {
- $this->assertInstanceOf('coding_exception', $e);
+ $this->assertInstanceOf(\core\exception\coding_exception::class, $e);
}
}
}
diff --git a/cache/tests/fixtures/cache_phpunit_dummy_datasource_versionable.php b/cache/tests/fixtures/cache_phpunit_dummy_datasource_versionable.php
index ef0743e3f89..8f23b7407a1 100644
--- a/cache/tests/fixtures/cache_phpunit_dummy_datasource_versionable.php
+++ b/cache/tests/fixtures/cache_phpunit_dummy_datasource_versionable.php
@@ -14,6 +14,8 @@
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see .
+use core_cache\versionable_data_source_interface;
+
/**
* A dummy datasource which supports versioning.
*
@@ -21,8 +23,9 @@
* @copyright 2021 The Open University
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
-class cache_phpunit_dummy_datasource_versionable extends cache_phpunit_dummy_datasource
- implements cache_data_source_versionable {
+class cache_phpunit_dummy_datasource_versionable extends cache_phpunit_dummy_datasource implements
+ versionable_data_source_interface
+{
/** @var array Data in cache */
protected $data = [];
@@ -35,8 +38,7 @@ class cache_phpunit_dummy_datasource_versionable extends cache_phpunit_dummy_dat
* @param cache_definition $definition
* @return cache_phpunit_dummy_datasource New object
*/
- public static function get_instance_for_cache(cache_definition $definition):
- cache_phpunit_dummy_datasource_versionable {
+ public static function get_instance_for_cache(cache_definition $definition): cache_phpunit_dummy_datasource_versionable {
self::$lastinstance = new cache_phpunit_dummy_datasource_versionable();
return self::$lastinstance;
}
@@ -81,4 +83,3 @@ class cache_phpunit_dummy_datasource_versionable extends cache_phpunit_dummy_dat
return $value->data;
}
}
-
diff --git a/cache/tests/fixtures/cachestore_file_with_ttl_wrappers.php b/cache/tests/fixtures/cachestore_file_with_ttl_wrappers.php
index c5752a7904f..60827a72575 100644
--- a/cache/tests/fixtures/cachestore_file_with_ttl_wrappers.php
+++ b/cache/tests/fixtures/cachestore_file_with_ttl_wrappers.php
@@ -30,8 +30,7 @@ class cachestore_file_with_ttl_wrappers extends cachestore_file {
* @param array $configuration Configuration
* @return int Supported features
*/
- public static function get_supported_features(array $configuration = array()) {
+ public static function get_supported_features(array $configuration = []) {
return parent::get_supported_features($configuration) - self::SUPPORTS_NATIVE_TTL;
}
}
-
diff --git a/cache/tests/fixtures/lib.php b/cache/tests/fixtures/lib.php
index 92d3f2e4a0d..f774f39a3c2 100644
--- a/cache/tests/fixtures/lib.php
+++ b/cache/tests/fixtures/lib.php
@@ -20,7 +20,7 @@
* This file is part of Moodle's cache API, affectionately called MUC.
* It contains the components that are requried in order to use caching.
*
- * @package core
+ * @package core_cache
* @category cache
* @copyright 2012 Sam Hemelryk
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
@@ -28,7 +28,7 @@
defined('MOODLE_INTERNAL') || die();
-require_once($CFG->dirroot.'/cache/locallib.php');
+use core_cache\store;
/**
* Override the default cache configuration for our own maniacal purposes.
@@ -41,7 +41,6 @@ require_once($CFG->dirroot.'/cache/locallib.php');
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class cache_config_testing extends cache_config_writer {
-
/**
* Creates the default configuration and saves it.
*
@@ -57,7 +56,7 @@ class cache_config_testing extends cache_config_writer {
// HACK ALERT.
// We probably need to come up with a better way to create the default stores, or at least ensure 100% that the
// default store plugins are protected from deletion.
- $writer = new self;
+ $writer = new self();
$writer->configstores = self::get_default_stores();
$writer->configdefinitions = self::locate_definitions();
$defaultapplication = 'default_application';
@@ -65,50 +64,50 @@ class cache_config_testing extends cache_config_writer {
$appdefine = defined('TEST_CACHE_USING_APPLICATION_STORE') ? TEST_CACHE_USING_APPLICATION_STORE : false;
if ($appdefine !== false && preg_match('/^[a-zA-Z][a-zA-Z0-9_]+$/', $appdefine)) {
$expectedstore = $appdefine;
- $file = $CFG->dirroot.'/cache/stores/'.$appdefine.'/lib.php';
- $class = 'cachestore_'.$appdefine;
+ $file = $CFG->dirroot . '/cache/stores/' . $appdefine . '/lib.php';
+ $class = 'cachestore_' . $appdefine;
if (file_exists($file)) {
require_once($file);
}
if (class_exists($class) && $class::ready_to_be_used_for_testing()) {
- /* @var cache_store $class */
- $writer->configstores['test_application'] = array(
+ /* @var store $class */
+ $writer->configstores['test_application'] = [
'name' => 'test_application',
'plugin' => $expectedstore,
'modes' => $class::get_supported_modes(),
'features' => $class::get_supported_features(),
- 'configuration' => $class::unit_test_configuration()
- );
+ 'configuration' => $class::unit_test_configuration(),
+ ];
$defaultapplication = 'test_application';
}
}
- $writer->configmodemappings = array(
- array(
- 'mode' => cache_store::MODE_APPLICATION,
+ $writer->configmodemappings = [
+ [
+ 'mode' => store::MODE_APPLICATION,
'store' => $defaultapplication,
- 'sort' => -1
- ),
- array(
- 'mode' => cache_store::MODE_SESSION,
+ 'sort' => -1,
+ ],
+ [
+ 'mode' => store::MODE_SESSION,
'store' => 'default_session',
- 'sort' => -1
- ),
- array(
- 'mode' => cache_store::MODE_REQUEST,
+ 'sort' => -1,
+ ],
+ [
+ 'mode' => store::MODE_REQUEST,
'store' => 'default_request',
- 'sort' => -1
- )
- );
- $writer->configlocks = array(
- 'default_file_lock' => array(
+ 'sort' => -1,
+ ],
+ ];
+ $writer->configlocks = [
+ 'default_file_lock' => [
'name' => 'cachelock_file_default',
'type' => 'cachelock_file',
'dir' => 'filelocks',
- 'default' => true
- )
- );
+ 'default' => true,
+ ],
+ ];
$factory = cache_factory::instance();
// We expect the cache to be initialising presently. If its not then something has gone wrong and likely
@@ -135,13 +134,12 @@ class cache_config_testing extends cache_config_writer {
protected static function get_config_file_path() {
global $CFG;
// We always use this path.
- $configpath = $CFG->dataroot.'/muc/config.php';
+ $configpath = $CFG->dataroot . '/muc/config.php';
if (!empty($CFG->altcacheconfigpath)) {
-
// No need to check we are within a test here, this is the cache config class that gets used
// only when one of those is true.
- if (!defined('TEST_CACHE_USING_ALT_CACHE_CONFIG_PATH') || !TEST_CACHE_USING_ALT_CACHE_CONFIG_PATH) {
+ if (!defined('TEST_CACHE_USING_ALT_CACHE_CONFIG_PATH') || !TEST_CACHE_USING_ALT_CACHE_CONFIG_PATH) {
// TEST_CACHE_USING_ALT_CACHE_CONFIG_PATH has not being defined or is false, we want to use the default.
return $configpath;
}
@@ -149,7 +147,7 @@ class cache_config_testing extends cache_config_writer {
$path = $CFG->altcacheconfigpath;
if (is_dir($path) && is_writable($path)) {
// Its a writable directory, thats fine. Convert it to a file.
- $path = $CFG->altcacheconfigpath.'/cacheconfig.php';
+ $path = $CFG->altcacheconfigpath . '/cacheconfig.php';
}
if (is_readable($path)) {
$directory = dirname($configpath);
@@ -180,13 +178,13 @@ class cache_config_testing extends cache_config_writer {
public function phpunit_add_definition($area, array $properties, $addmapping = true) {
if (!array_key_exists('overrideclass', $properties)) {
switch ($properties['mode']) {
- case cache_store::MODE_APPLICATION:
+ case store::MODE_APPLICATION:
$properties['overrideclass'] = 'cache_phpunit_application';
break;
- case cache_store::MODE_SESSION:
+ case store::MODE_SESSION:
$properties['overrideclass'] = 'cache_phpunit_session';
break;
- case cache_store::MODE_REQUEST:
+ case store::MODE_REQUEST:
$properties['overrideclass'] = 'cache_phpunit_request';
break;
}
@@ -194,13 +192,13 @@ class cache_config_testing extends cache_config_writer {
$this->configdefinitions[$area] = $properties;
if ($addmapping) {
switch ($properties['mode']) {
- case cache_store::MODE_APPLICATION:
+ case store::MODE_APPLICATION:
$this->phpunit_add_definition_mapping($area, 'default_application', 0);
break;
- case cache_store::MODE_SESSION:
+ case store::MODE_SESSION:
$this->phpunit_add_definition_mapping($area, 'default_session', 0);
break;
- case cache_store::MODE_REQUEST:
+ case store::MODE_REQUEST:
$this->phpunit_add_definition_mapping($area, 'default_request', 0);
break;
}
@@ -219,7 +217,7 @@ class cache_config_testing extends cache_config_writer {
* Removes the configured stores so that there are none available.
*/
public function phpunit_remove_stores() {
- $this->configstores = array();
+ $this->configstores = [];
}
/**
@@ -234,19 +232,19 @@ class cache_config_testing extends cache_config_writer {
if (!$nativettl) {
require_once(__DIR__ . '/cachestore_file_with_ttl_wrappers.php');
}
- $this->configstores[$name] = array(
+ $this->configstores[$name] = [
'name' => $name,
'plugin' => 'file',
- 'configuration' => array(
- 'path' => ''
- ),
+ 'configuration' => [
+ 'path' => '',
+ ],
'features' => 6,
'modes' => 3,
'mappingsonly' => false,
'class' => $nativettl ? 'cachestore_file' : 'cachestore_file_with_ttl_wrappers',
'default' => false,
- 'lock' => 'cachelock_file_default'
- );
+ 'lock' => 'cachelock_file_default',
+ ];
}
/**
@@ -267,16 +265,16 @@ class cache_config_testing extends cache_config_writer {
* @param string $name
*/
public function phpunit_add_session_store($name) {
- $this->configstores[$name] = array(
+ $this->configstores[$name] = [
'name' => $name,
'plugin' => 'session',
- 'configuration' => array(),
+ 'configuration' => [],
'features' => 14,
'modes' => 2,
'default' => true,
'class' => 'cachestore_session',
'lock' => 'cachelock_file_default',
- );
+ ];
}
/**
@@ -290,11 +288,11 @@ class cache_config_testing extends cache_config_writer {
* @param int $sort
*/
public function phpunit_add_definition_mapping($definition, $store, $sort) {
- $this->configdefinitionmappings[] = array(
+ $this->configdefinitionmappings[] = [
'store' => $store,
'definition' => $definition,
- 'sort' => (int)$sort
- );
+ 'sort' => (int)$sort,
+ ];
}
/**
@@ -304,7 +302,7 @@ class cache_config_testing extends cache_config_writer {
*/
public function get_site_identifier() {
global $CFG;
- return $CFG->wwwroot.'phpunit';
+ return $CFG->wwwroot . 'phpunit';
}
/**
@@ -363,7 +361,7 @@ class cache_phpunit_dummy_object extends stdClass implements cacheable_object {
* @return array
*/
public function prepare_to_cache() {
- return array($this->property1.'_ptc', $this->property2.'_ptc', $this->propertytime);
+ return [$this->property1 . '_ptc', $this->property2 . '_ptc', $this->propertytime];
}
/**
* Returns this object from the cache
@@ -377,9 +375,8 @@ class cache_phpunit_dummy_object extends stdClass implements cacheable_object {
do {
$time = microtime(true);
} while ($time == $data[2]);
-
}
- return new cache_phpunit_dummy_object(array_shift($data).'_wfc', array_shift($data).'_wfc', $time);
+ return new cache_phpunit_dummy_object(array_shift($data) . '_wfc', array_shift($data) . '_wfc', $time);
}
}
@@ -407,7 +404,7 @@ class cache_phpunit_dummy_datasource implements cache_data_source {
* @return string
*/
public function load_for_cache($key) {
- return $key.' has no value really.';
+ return $key . ' has no value really.';
}
/**
@@ -417,9 +414,9 @@ class cache_phpunit_dummy_datasource implements cache_data_source {
* @return array
*/
public function load_many_for_cache(array $keys) {
- $return = array();
+ $return = [];
foreach ($keys as $key) {
- $return[$key] = $key.' has no value really.';
+ $return[$key] = $key . ' has no value really.';
}
return $return;
}
@@ -434,6 +431,10 @@ class cache_phpunit_dummy_datasource implements cache_data_source {
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class cache_phpunit_application extends cache_application {
+ #[\Override]
+ public function get_store() {
+ return parent::get_store();
+ }
/**
* Returns the class of the store immediately associated with this cache.
@@ -482,10 +483,14 @@ class cache_phpunit_application extends cache_application {
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class cache_phpunit_session extends cache_session {
-
/** @var Static member used for emulating the behaviour of session_id() during the tests. */
protected static $sessionidmockup = 'phpunitmockupsessionid';
+ #[\Override]
+ public function get_store() {
+ return parent::get_store();
+ }
+
/**
* Returns the class of the store immediately associated with this cache.
* @return string
@@ -537,6 +542,10 @@ class cache_phpunit_session extends cache_session {
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class cache_phpunit_request extends cache_request {
+ #[\Override]
+ public function get_store() {
+ return parent::get_store();
+ }
/**
* Returns the class of the store immediately associated with this cache.
diff --git a/cache/tests/fixtures/stores.php b/cache/tests/fixtures/stores.php
index f415272c88c..55f89c95b38 100644
--- a/cache/tests/fixtures/stores.php
+++ b/cache/tests/fixtures/stores.php
@@ -14,17 +14,6 @@
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see .
-/**
- * Cache store test fixtures.
- *
- * @package core
- * @category cache
- * @copyright 2013 Sam Hemelryk
- * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
- */
-
-defined('MOODLE_INTERNAL') || die();
-
/**
* An abstract class to make writing unit tests for cache stores very easy.
*
@@ -34,7 +23,6 @@ defined('MOODLE_INTERNAL') || die();
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
abstract class cachestore_tests extends advanced_testcase {
-
/**
* Returns the class name for the store.
*
@@ -49,7 +37,7 @@ abstract class cachestore_tests extends advanced_testcase {
public function setUp(): void {
$class = $this->get_class_name();
if (!class_exists($class) || !$class::are_requirements_met()) {
- $this->markTestSkipped('Could not test '.$class.'. Requirements are not met.');
+ $this->markTestSkipped('Could not test ' . $class . '. Requirements are not met.');
}
parent::setUp();
}
@@ -62,10 +50,10 @@ abstract class cachestore_tests extends advanced_testcase {
$modes = $class::get_supported_modes();
if ($modes & cache_store::MODE_APPLICATION) {
$definition = cache_definition::load_adhoc(cache_store::MODE_APPLICATION, $class, 'phpunit_test');
- $instance = new $class($class.'_test', $class::unit_test_configuration());
+ $instance = new $class($class . '_test', $class::unit_test_configuration());
if (!$instance->is_ready()) {
- $this->markTestSkipped('Could not test '.$class.'. No test instance configured for application caches.');
+ $this->markTestSkipped('Could not test ' . $class . '. No test instance configured for application caches.');
} else {
$instance->initialise($definition);
$this->run_tests($instance);
@@ -73,10 +61,10 @@ abstract class cachestore_tests extends advanced_testcase {
}
if ($modes & cache_store::MODE_SESSION) {
$definition = cache_definition::load_adhoc(cache_store::MODE_SESSION, $class, 'phpunit_test');
- $instance = new $class($class.'_test', $class::unit_test_configuration());
+ $instance = new $class($class . '_test', $class::unit_test_configuration());
if (!$instance->is_ready()) {
- $this->markTestSkipped('Could not test '.$class.'. No test instance configured for session caches.');
+ $this->markTestSkipped('Could not test ' . $class . '. No test instance configured for session caches.');
} else {
$instance->initialise($definition);
$this->run_tests($instance);
@@ -84,10 +72,10 @@ abstract class cachestore_tests extends advanced_testcase {
}
if ($modes & cache_store::MODE_REQUEST) {
$definition = cache_definition::load_adhoc(cache_store::MODE_REQUEST, $class, 'phpunit_test');
- $instance = new $class($class.'_test', $class::unit_test_configuration());
+ $instance = new $class($class . '_test', $class::unit_test_configuration());
if (!$instance->is_ready()) {
- $this->markTestSkipped('Could not test '.$class.'. No test instance configured for request caches.');
+ $this->markTestSkipped('Could not test ' . $class . '. No test instance configured for request caches.');
} else {
$instance->initialise($definition);
$this->run_tests($instance);
@@ -99,7 +87,7 @@ abstract class cachestore_tests extends advanced_testcase {
* Test the store for basic functionality.
*/
public function run_tests(cache_store $instance) {
- $object = new stdClass;
+ $object = new stdClass();
$object->data = 1;
// Test set with a string.
@@ -163,31 +151,31 @@ abstract class cachestore_tests extends advanced_testcase {
$this->assertFalse($instance->get('test2'));
// Test set_many.
- $outcome = $instance->set_many(array(
- array('key' => 'many1', 'value' => 'many1'),
- array('key' => 'many2', 'value' => 'many2'),
- array('key' => 'many3', 'value' => 'many3'),
- array('key' => 'many4', 'value' => 'many4'),
- array('key' => 'many5', 'value' => 'many5')
- ));
+ $outcome = $instance->set_many([
+ ['key' => 'many1', 'value' => 'many1'],
+ ['key' => 'many2', 'value' => 'many2'],
+ ['key' => 'many3', 'value' => 'many3'],
+ ['key' => 'many4', 'value' => 'many4'],
+ ['key' => 'many5', 'value' => 'many5'],
+ ]);
$this->assertSame(5, $outcome);
$this->assertSame('many1', $instance->get('many1'));
$this->assertSame('many5', $instance->get('many5'));
$this->assertFalse($instance->get('many6'));
// Test get_many.
- $result = $instance->get_many(array('many1', 'many3', 'many5', 'many6'));
+ $result = $instance->get_many(['many1', 'many3', 'many5', 'many6']);
$this->assertIsArray($result);
$this->assertCount(4, $result);
- $this->assertSame(array(
+ $this->assertSame([
'many1' => 'many1',
'many3' => 'many3',
'many5' => 'many5',
'many6' => false,
- ), $result);
+ ], $result);
// Test delete_many.
- $this->assertSame(3, $instance->delete_many(array('many2', 'many3', 'many4')));
- $this->assertSame(2, $instance->delete_many(array('many1', 'many5', 'many6')));
+ $this->assertSame(3, $instance->delete_many(['many2', 'many3', 'many4']));
+ $this->assertSame(2, $instance->delete_many(['many1', 'many5', 'many6']));
}
}
diff --git a/cache/tests/store_test.php b/cache/tests/store_test.php
index 34e9169b6c6..ec4e9d2576c 100644
--- a/cache/tests/store_test.php
+++ b/cache/tests/store_test.php
@@ -17,14 +17,14 @@
namespace core_cache;
/**
- * Unit tests for cache_store functionality.
+ * Unit tests for \core_cache\store functionality.
*
* @package core_cache
* @copyright 2021 The Open University
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ * @covers \core_cache\store
*/
-class store_test extends \advanced_testcase {
-
+final class store_test extends \advanced_testcase {
/**
* Tests the default implementation of cache_size_details, which does some
* complicated statistics.
@@ -67,11 +67,11 @@ class store_test extends \advanced_testcase {
protected static function create_static_store(): \cachestore_static {
require_once(__DIR__ . '/../stores/static/lib.php');
$store = new \cachestore_static('frog');
- $definition = \cache_definition::load('zombie', [
- 'mode' => \cache_store::MODE_REQUEST,
- 'component' => 'phpunit',
- 'area' => 'store_test',
- 'simplekeys' => true
+ $definition = definition::load('zombie', [
+ 'mode' => store::MODE_REQUEST,
+ 'component' => 'phpunit',
+ 'area' => 'store_test',
+ 'simplekeys' => true,
]);
$store->initialise($definition);
return $store;
diff --git a/cache/usage.php b/cache/usage.php
index 6309e901589..a36637238e8 100644
--- a/cache/usage.php
+++ b/cache/usage.php
@@ -27,7 +27,7 @@ require_once('../config.php');
require_once($CFG->dirroot . '/lib/adminlib.php');
admin_externalpage_setup('cacheusage');
-$adminhelper = cache_factory::instance()->get_administration_display_helper();
+$adminhelper = \core_cache\factory::instance()->get_administration_display_helper();
raise_memory_limit(MEMORY_EXTRA);
$samples = optional_param('samples', 50, PARAM_INT);
diff --git a/course/classes/cache/course_image.php b/course/classes/cache/course_image.php
index e609232172c..bfe6f4c2d5e 100644
--- a/course/classes/cache/course_image.php
+++ b/course/classes/cache/course_image.php
@@ -16,8 +16,8 @@
namespace core_course\cache;
-use cache_data_source;
-use cache_definition;
+use core_cache\data_source_interface;
+use core_cache\definition;
use moodle_url;
use core_course_list_element;
@@ -30,7 +30,7 @@ use core_course_list_element;
* @copyright 2021 Catalyst IT
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
-class course_image implements cache_data_source {
+class course_image implements data_source_interface {
/** @var course_image */
protected static $instance = null;
@@ -39,10 +39,10 @@ class course_image implements cache_data_source {
* Returns an instance of the data source class that the cache can use for loading data using the other methods
* specified by this interface.
*
- * @param cache_definition $definition
+ * @param definition $definition
* @return \core_course\cache\course_image
*/
- public static function get_instance_for_cache(cache_definition $definition): course_image {
+ public static function get_instance_for_cache(definition $definition): course_image {
if (is_null(self::$instance)) {
self::$instance = new course_image();
}
diff --git a/course/tests/course_image_cache_test.php b/course/tests/course_image_cache_test.php
index 2a825e7dad0..e724af640b9 100644
--- a/course/tests/course_image_cache_test.php
+++ b/course/tests/course_image_cache_test.php
@@ -19,7 +19,7 @@ namespace core_course;
use context_user;
use context_course;
use ReflectionMethod;
-use cache_definition;
+use core_cache\definition;
use core_course\cache\course_image;
/**
@@ -97,7 +97,7 @@ class course_image_cache_test extends \advanced_testcase {
*/
public function test_get_image_url_from_overview_files_return_null_if_no_summary_files_in_the_course(): void {
$method = new ReflectionMethod(course_image::class, 'get_image_url_from_overview_files');
- $cache = course_image::get_instance_for_cache(new cache_definition());
+ $cache = course_image::get_instance_for_cache(new definition());
// Create course without files.
$course = $this->getDataGenerator()->create_course();
@@ -109,7 +109,7 @@ class course_image_cache_test extends \advanced_testcase {
*/
public function test_get_image_url_from_overview_files_returns_null_if_no_summary_images_in_the_course(): void {
$method = new ReflectionMethod(course_image::class, 'get_image_url_from_overview_files');
- $cache = course_image::get_instance_for_cache(new cache_definition());
+ $cache = course_image::get_instance_for_cache(new definition());
// Create course without image files.
$draftid2 = $this->fill_draft_area(['filename2.zip' => 'Test file contents2']);
@@ -122,7 +122,7 @@ class course_image_cache_test extends \advanced_testcase {
*/
public function test_get_image_url_from_overview_files_returns_url_if_there_is_a_summary_image(): void {
$method = new ReflectionMethod(course_image::class, 'get_image_url_from_overview_files');
- $cache = course_image::get_instance_for_cache(new cache_definition());
+ $cache = course_image::get_instance_for_cache(new definition());
// Create course without one image.
$draftid1 = $this->fill_draft_area(['filename1.jpg' => file_get_contents(__DIR__ . '/fixtures/image.jpg')]);
@@ -136,7 +136,7 @@ class course_image_cache_test extends \advanced_testcase {
*/
public function test_get_image_url_from_overview_files_returns_url_of_the_first_image_if_there_are_many_summary_images(): void {
$method = new ReflectionMethod(course_image::class, 'get_image_url_from_overview_files');
- $cache = course_image::get_instance_for_cache(new cache_definition());
+ $cache = course_image::get_instance_for_cache(new definition());
// Create course with two image files.
$draftid1 = $this->fill_draft_area([
@@ -154,7 +154,7 @@ class course_image_cache_test extends \advanced_testcase {
*/
public function test_get_image_url_from_overview_files_returns_url_of_the_first_image_if_there_are_many_summary_files(): void {
$method = new ReflectionMethod(course_image::class, 'get_image_url_from_overview_files');
- $cache = course_image::get_instance_for_cache(new cache_definition());
+ $cache = course_image::get_instance_for_cache(new definition());
// Create course with two image files and one zip file.
$draftid1 = $this->fill_draft_area([
diff --git a/install.php b/install.php
index 17646a4a3b4..fdc54da559e 100644
--- a/install.php
+++ b/install.php
@@ -219,7 +219,6 @@ require_once($CFG->libdir.'/deprecatedlib.php');
require_once($CFG->libdir.'/adminlib.php');
require_once($CFG->libdir.'/environmentlib.php');
require_once($CFG->libdir.'/componentlib.class.php');
-require_once($CFG->dirroot.'/cache/lib.php');
require('version.php');
$CFG->target_release = $release;
diff --git a/lib/classes/component.php b/lib/classes/component.php
index fa4e64daa77..f7f31a5a8c7 100644
--- a/lib/classes/component.php
+++ b/lib/classes/component.php
@@ -490,7 +490,7 @@ class component {
$keyclasses = [
\core\exception\moodle_exception::class,
\core\output\bootstrap_renderer::class,
- \core\router::class,
+ \core_cache\cache::class,
];
foreach ($keyclasses as $classname) {
if (!array_key_exists($classname, $cache['classmap'])) {
diff --git a/lib/db/legacyclasses.php b/lib/db/legacyclasses.php
index 6022f731d47..fa65093e6ba 100644
--- a/lib/db/legacyclasses.php
+++ b/lib/db/legacyclasses.php
@@ -50,6 +50,144 @@ $legacyclasses = [
\required_capability_exception::class => 'exception/required_capability_exception.php',
\webservice_parameter_exception::class => 'exception/webservice_parameter_exception.php',
+ // Cache API.
+ \cache::class => [
+ 'core_cache',
+ 'cache.php',
+ ],
+ \cache_application::class => [
+ 'core_cache',
+ 'application_cache.php',
+ ],
+ \cache_definition::class => [
+ 'core_cache',
+ 'definition.php',
+ ],
+ \cache_request::class => [
+ 'core_cache',
+ 'request_cache.php',
+ ],
+ \cache_session::class => [
+ 'core_cache',
+ 'session_cache.php',
+ ],
+ \cache_cached_object::class => [
+ 'core_cache',
+ 'cached_object.php',
+ ],
+ \cache_config::class => [
+ 'core_cache',
+ 'config.php',
+ ],
+ \cache_config_writer::class => [
+ 'core_cache',
+ 'config_writer.php',
+ ],
+ \cache_config_disabled::class => [
+ 'core_cache',
+ 'disabled_config.php',
+ ],
+ \cache_disabled::class => [
+ 'core_cache',
+ 'disabled_cache.php',
+ ],
+ \config_writer::class => [
+ 'core_cache',
+ 'config_writer.php',
+ ],
+ \cache_data_source::class => [
+ 'core_cache',
+ 'data_source_interface.php',
+ ],
+ \cache_data_source_versionable::class => [
+ 'core_cache',
+ 'versionable_data_source_interface.php',
+ ],
+ \cache_exception::class => [
+ 'core_cache',
+ 'exception/cache_exception.php',
+ ],
+ \cache_factory::class => [
+ 'core_cache',
+ 'factory.php',
+ ],
+ \cache_factory_disabled::class => [
+ 'core_cache',
+ 'disabled_factory.php',
+ ],
+ \cache_helper::class => [
+ 'core_cache',
+ 'helper.php',
+ ],
+ \cache_is_key_aware::class => [
+ 'core_cache',
+ 'key_aware_cache_interface.php',
+ ],
+ \cache_is_lockable::class => [
+ 'core_cache',
+ 'lockable_cache_interface.php',
+ ],
+ \cache_is_searchable::class => [
+ 'core_cache',
+ 'searchable_cache_interface.php',
+ ],
+ \cache_is_configurable::class => [
+ 'core_cache',
+ 'configurable_cache_interface.php',
+ ],
+ \cache_loader::class => [
+ 'core_cache',
+ 'loader_interface.php',
+ ],
+ \cache_loader_with_locking::class => [
+ 'core_cache',
+ 'loader_with_locking_interface.php',
+ ],
+ \cache_lock_interface::class => [
+ 'core_cache',
+ 'cache_lock_interface.php',
+ ],
+ \cache_store::class => [
+ 'core_cache',
+ 'store.php',
+ ],
+ \cache_store_interface::class => [
+ 'core_cache',
+ 'store_interface.php',
+ ],
+ \cache_ttl_wrapper::class => [
+ 'core_cache',
+ 'ttl_wrapper.php',
+ ],
+ \cacheable_object::class => [
+ 'core_cache',
+ 'cacheable_object_interface.php',
+ ],
+ \cacheable_object_array::class => [
+ 'core_cache',
+ 'cacheable_object_array.php',
+ ],
+ \cache_definition_mappings_form::class => [
+ 'core_cache',
+ 'form/cache_definition_mappings_form.php',
+ ],
+ \cache_definition_sharing_form::class => [
+ 'core_cache',
+ 'form/cache_definition_sharing_form.php',
+ ],
+ \cache_lock_form::class => [
+ 'core_cache',
+ 'form/cache_lock_form.php',
+ ],
+ \cache_mode_mappings_form::class => [
+ 'core_cache',
+ 'form/cache_mode_mappings_form.php',
+ ],
+ \cachestore_addinstance_form::class => [
+ 'core_cache',
+ 'form/cachestore_addinstance_form.php',
+ ],
+
// Output API.
\theme_config::class => 'output/theme_config.php',
\xhtml_container_stack::class => 'output/xhtml_container_stack.php',
diff --git a/lib/setup.php b/lib/setup.php
index 269c105bcaf..11d6d1d7148 100644
--- a/lib/setup.php
+++ b/lib/setup.php
@@ -313,7 +313,7 @@ if (!defined('CACHE_DISABLE_ALL')) {
}
// When set to true MUC (Moodle caching) will not use any of the defined or default stores.
-// The Cache API will continue to function however this will force the use of the cachestore_dummy so all requests
+// The Cache API will continue to function however this will force the use of the dummy_cachestore so all requests
// will be interacting with a static property and will never go to the proper cache stores.
// Useful if you need to avoid the stores for one reason or another.
if (!defined('CACHE_DISABLE_STORES')) {
@@ -638,7 +638,6 @@ require_once($CFG->libdir .'/sessionlib.php'); // All session and cookie re
require_once($CFG->libdir .'/editorlib.php'); // All text editor related functions and classes.
require_once($CFG->libdir .'/messagelib.php'); // Messagelib functions.
require_once($CFG->libdir .'/modinfolib.php'); // Cached information on course-module instances.
-require_once($CFG->dirroot.'/cache/lib.php'); // Cache API.
// Increase memory limits if possible.
raise_memory_limit(MEMORY_STANDARD);
diff --git a/message/classes/time_last_message_between_users.php b/message/classes/time_last_message_between_users.php
index 8f7e99a05e6..0a41ed922e3 100644
--- a/message/classes/time_last_message_between_users.php
+++ b/message/classes/time_last_message_between_users.php
@@ -14,18 +14,10 @@
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see .
-/**
- * Cache data source for the time of the last message between users.
- *
- * @package core_message
- * @category cache
- * @copyright 2016 Ryan Wyllie
- * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
- */
-
namespace core_message;
-defined('MOODLE_INTERNAL') || die();
+use core_cache\data_source_interface;
+use core_cache\definition;
/**
* Cache data source for the time of the last message in a conversation.
@@ -35,19 +27,19 @@ defined('MOODLE_INTERNAL') || die();
* @copyright 2016 Ryan Wyllie
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
-class time_last_message_between_users implements \cache_data_source {
+class time_last_message_between_users implements data_source_interface {
/** @var time_last_message_between_users the singleton instance of this class. */
protected static $instance = null;
/**
* Returns an instance of the data source class that the cache can use for loading data using the other methods
- * specified by the cache_data_source interface.
+ * specified by the data_source_interface interface.
*
- * @param \cache_definition $definition
+ * @param definition $definition
* @return object
*/
- public static function get_instance_for_cache(\cache_definition $definition) {
+ public static function get_instance_for_cache(definition $definition) {
if (is_null(self::$instance)) {
self::$instance = new time_last_message_between_users();
}
diff --git a/mod/assign/classes/cache/overrides.php b/mod/assign/classes/cache/overrides.php
index a9722b91393..0c9d8912baf 100644
--- a/mod/assign/classes/cache/overrides.php
+++ b/mod/assign/classes/cache/overrides.php
@@ -26,7 +26,8 @@ declare(strict_types=1);
namespace mod_assign\cache;
-use cache_definition;
+use core_cache\data_source_interface;
+use core_cache\definition;
/**
* Class assign_overrides
@@ -35,7 +36,7 @@ use cache_definition;
* @copyright 2021 Shamim Rezaie
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
-class overrides implements \cache_data_source {
+class overrides implements data_source_interface {
/** @var overrides the singleton instance of this class. */
protected static $instance = null;
@@ -44,10 +45,10 @@ class overrides implements \cache_data_source {
* Returns an instance of the data source class that the cache can use for loading data using the other methods
* specified by this interface.
*
- * @param cache_definition $definition
+ * @param definition $definition
* @return object
*/
- public static function get_instance_for_cache(cache_definition $definition): overrides {
+ public static function get_instance_for_cache(definition $definition): overrides {
if (is_null(self::$instance)) {
self::$instance = new overrides();
}
diff --git a/mod/lesson/classes/cache/overrides.php b/mod/lesson/classes/cache/overrides.php
index 889d9728c14..aec3b4f2f05 100644
--- a/mod/lesson/classes/cache/overrides.php
+++ b/mod/lesson/classes/cache/overrides.php
@@ -14,6 +14,13 @@
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see .
+declare(strict_types=1);
+
+namespace mod_lesson\cache;
+
+use core_cache\data_source_interface;
+use core_cache\definition;
+
/**
* Cache data source for the lesson overrides.
*
@@ -21,21 +28,7 @@
* @copyright 2021 Shamim Rezaie
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
-
-declare(strict_types=1);
-
-namespace mod_lesson\cache;
-
-use cache_definition;
-
-/**
- * Class lesson_overrides
- *
- * @package mod_lesson
- * @copyright 2021 Shamim Rezaie
- * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
- */
-class overrides implements \cache_data_source {
+class overrides implements data_source_interface {
/** @var overrides the singleton instance of this class. */
protected static $instance = null;
@@ -44,10 +37,10 @@ class overrides implements \cache_data_source {
* Returns an instance of the data source class that the cache can use for loading data using the other methods
* specified by this interface.
*
- * @param cache_definition $definition
+ * @param definition $definition
* @return object
*/
- public static function get_instance_for_cache(cache_definition $definition): overrides {
+ public static function get_instance_for_cache(definition $definition): overrides {
if (is_null(self::$instance)) {
self::$instance = new overrides();
}
diff --git a/mod/quiz/classes/cache/overrides.php b/mod/quiz/classes/cache/overrides.php
index 346d38d8ed7..4a6ff371e45 100644
--- a/mod/quiz/classes/cache/overrides.php
+++ b/mod/quiz/classes/cache/overrides.php
@@ -26,7 +26,8 @@ declare(strict_types=1);
namespace mod_quiz\cache;
-use cache_definition;
+use core_cache\data_source_interface;
+use core_cache\definition;
/**
* Class quiz_overrides
@@ -35,8 +36,7 @@ use cache_definition;
* @copyright 2021 Shamim Rezaie
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
-class overrides implements \cache_data_source {
-
+class overrides implements data_source_interface {
/** @var overrides the singleton instance of this class. */
protected static $instance = null;
@@ -44,10 +44,10 @@ class overrides implements \cache_data_source {
* Returns an instance of the data source class that the cache can use for loading data using the other methods
* specified by this interface.
*
- * @param cache_definition $definition
- * @return stdClass
+ * @param definition $definition
+ * @return overrides
*/
- public static function get_instance_for_cache(cache_definition $definition): overrides {
+ public static function get_instance_for_cache(definition $definition): overrides {
if (is_null(self::$instance)) {
self::$instance = new overrides();
}
@@ -64,7 +64,7 @@ class overrides implements \cache_data_source {
public function load_for_cache($key) {
global $DB;
- // Ignore getting data if this is a cache invalidation - {@see \cache_helper::purge_by_event()}.
+ // Ignore getting data if this is a cache invalidation - {@see \core_cache\helper::purge_by_event()}.
if ($key == 'lastinvalidation') {
return null;
}
diff --git a/mod/scorm/classes/cache/elements.php b/mod/scorm/classes/cache/elements.php
index fb5c7261bb8..5f8bfff762d 100644
--- a/mod/scorm/classes/cache/elements.php
+++ b/mod/scorm/classes/cache/elements.php
@@ -15,8 +15,11 @@
// along with Moodle. If not, see .
declare(strict_types=1);
+
namespace mod_scorm\cache;
-use cache_definition;
+
+use core_cache\data_source_interface;
+use core_cache\definition;
/**
* Cache data source for the scorm elements.
@@ -26,7 +29,7 @@ use cache_definition;
* @author Dan Marsden
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
-class elements implements \cache_data_source {
+class elements implements data_source_interface {
/** @var elements the singleton instance of this class. */
protected static $instance = null;
@@ -35,10 +38,10 @@ class elements implements \cache_data_source {
* Returns an instance of the data source class that the cache can use for loading data using the other methods
* specified by this interface.
*
- * @param cache_definition $definition
+ * @param definition $definition
* @return object
*/
- public static function get_instance_for_cache(cache_definition $definition): elements {
+ public static function get_instance_for_cache(definition $definition): elements {
if (is_null(self::$instance)) {
self::$instance = new elements();
}
diff --git a/question/engine/bank.php b/question/engine/bank.php
index 61224337184..84e86211d11 100644
--- a/question/engine/bank.php
+++ b/question/engine/bank.php
@@ -27,9 +27,13 @@
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
+use core_cache\application_cache;
+use core_cache\data_source_interface;
+use core_cache\definition;
use core_question\local\bank\question_version_status;
use core_question\output\question_version_info;
+
defined('MOODLE_INTERNAL') || die();
require_once(__DIR__ . '/../type/questiontypebase.php');
@@ -486,7 +490,7 @@ abstract class question_bank {
* @copyright 2009 The Open University
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
-class question_finder implements cache_data_source {
+class question_finder implements data_source_interface {
/** @var question_finder the singleton instance of this class. */
protected static $questionfinder = null;
@@ -500,13 +504,13 @@ class question_finder implements cache_data_source {
return self::$questionfinder;
}
- /* See cache_data_source::get_instance_for_cache. */
- public static function get_instance_for_cache(cache_definition $definition) {
+ #[\Override]
+ public static function get_instance_for_cache(definition $definition) {
return self::get_instance();
}
/**
- * @return cache_application the question definition cache we are using.
+ * @return application_cache the question definition cache we are using.
*/
protected function get_data_cache() {
// Do not double cache here because it may break cache resetting.
@@ -672,7 +676,7 @@ class question_finder implements cache_data_source {
$qubaids->from_where_params() + $params + $extraparams);
}
- /* See cache_data_source::load_for_cache. */
+ #[\Override]
public function load_for_cache($questionid) {
global $DB;
@@ -696,7 +700,7 @@ class question_finder implements cache_data_source {
return $questiondata;
}
- /* See cache_data_source::load_many_for_cache. */
+ #[\Override]
public function load_many_for_cache(array $questionids) {
global $DB;
diff --git a/r.php b/r.php
index 2d59ba587f4..9f965cfb490 100644
--- a/r.php
+++ b/r.php
@@ -50,7 +50,6 @@ require_once("{$CFG->libdir}/sessionlib.php"); // All session and cookie re
require_once("{$CFG->libdir}/editorlib.php"); // All text editor related functions and classes.
require_once("{$CFG->libdir}/messagelib.php"); // Messagelib functions.
require_once("{$CFG->libdir}/modinfolib.php"); // Cached information on course-module instances.
-require_once("{$CFG->dirroot}/cache/lib.php"); // Cache API.
$router = \core\di::get(\core\router::class);
$router->serve();