MemoryCounterBackend.php 2.3 KB

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