Upgraded drupal core with security updates
[yaffs-website] / web / core / lib / Drupal / Core / Cache / MemoryCounterBackend.php
1 <?php
2
3 namespace Drupal\Core\Cache;
4
5 /**
6  * Defines a memory cache implementation that counts set and get calls.
7  *
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.
10  *
11  * @todo On the longrun this backend should be replaced by phpunit mock objects.
12  */
13 class MemoryCounterBackend extends MemoryBackend {
14
15   /**
16    * Stores a list of cache cid calls keyed by function name.
17    *
18    * @var array
19    */
20   protected $counter = [];
21
22   /**
23    * {@inheritdoc}
24    */
25   public function get($cid, $allow_invalid = FALSE) {
26     $this->increaseCounter(__FUNCTION__, $cid);
27     return parent::get($cid, $allow_invalid);
28   }
29
30   /**
31    * {@inheritdoc}
32    */
33   public function set($cid, $data, $expire = Cache::PERMANENT, array $tags = []) {
34     $this->increaseCounter(__FUNCTION__, $cid);
35     parent::set($cid, $data, $expire, $tags);
36   }
37
38   /**
39    * {@inheritdoc}
40    */
41   public function delete($cid) {
42     $this->increaseCounter(__FUNCTION__, $cid);
43     parent::delete($cid);
44   }
45
46   /**
47    * Increase the counter for a function with a certain cid.
48    *
49    * @param string $function
50    *   The called function.
51    * @param string $cid
52    *   The cache ID of the cache entry to increase the counter.
53    */
54   protected function increaseCounter($function, $cid) {
55     if (!isset($this->counter[$function][$cid])) {
56       $this->counter[$function][$cid] = 1;
57     }
58     else {
59       $this->counter[$function][$cid]++;
60     }
61   }
62
63   /**
64    * Returns the call counter for the get, set and delete methods.
65    *
66    * @param string $method
67    *   (optional) The name of the method to return the call counter for.
68    * @param string $cid
69    *   (optional) The name of the cache id to return the call counter for.
70    *
71    * @return int|array
72    *   An integer if both method and cid is given, an array otherwise.
73    */
74   public function getCounter($method = NULL, $cid = NULL) {
75     if ($method && $cid) {
76       return isset($this->counter[$method][$cid]) ? $this->counter[$method][$cid] : 0;
77     }
78     elseif ($method) {
79       return isset($this->counter[$method]) ? $this->counter[$method] : [];
80     }
81     else {
82       return $this->counter;
83     }
84   }
85
86   /**
87    * Resets the call counter.
88    */
89   public function resetCounter() {
90     $this->counter = [];
91   }
92
93 }