3 namespace Drupal\Core\Cache;
6 * Defines a memory cache implementation that counts set and get calls.
8 * This can be used to mock a cache backend where one needs to know how
9 * many times a cache entry was set or requested.
11 * @todo On the longrun this backend should be replaced by phpunit mock objects.
13 class MemoryCounterBackend extends MemoryBackend {
16 * Stores a list of cache cid calls keyed by function name.
20 protected $counter = [];
25 public function get($cid, $allow_invalid = FALSE) {
26 $this->increaseCounter(__FUNCTION__, $cid);
27 return parent::get($cid, $allow_invalid);
33 public function set($cid, $data, $expire = Cache::PERMANENT, array $tags = []) {
34 $this->increaseCounter(__FUNCTION__, $cid);
35 parent::set($cid, $data, $expire, $tags);
41 public function delete($cid) {
42 $this->increaseCounter(__FUNCTION__, $cid);
47 * Increase the counter for a function with a certain cid.
49 * @param string $function
50 * The called function.
52 * The cache ID of the cache entry to increase the counter.
54 protected function increaseCounter($function, $cid) {
55 if (!isset($this->counter[$function][$cid])) {
56 $this->counter[$function][$cid] = 1;
59 $this->counter[$function][$cid]++;
64 * Returns the call counter for the get, set and delete methods.
66 * @param string $method
67 * (optional) The name of the method to return the call counter for.
69 * (optional) The name of the cache id to return the call counter for.
72 * An integer if both method and cid is given, an array otherwise.
74 public function getCounter($method = NULL, $cid = NULL) {
75 if ($method && $cid) {
76 return isset($this->counter[$method][$cid]) ? $this->counter[$method][$cid] : 0;
79 return isset($this->counter[$method]) ? $this->counter[$method] : [];
82 return $this->counter;
87 * Resets the call counter.
89 public function resetCounter() {