1
0

CappedMemoryCache.php 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. <?php
  2. /**
  3. * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
  4. * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
  5. * SPDX-License-Identifier: AGPL-3.0-only
  6. */
  7. namespace OC\Cache;
  8. use OCP\ICache;
  9. /**
  10. * In-memory cache with a capacity limit to keep memory usage in check
  11. *
  12. * Uses a simple FIFO expiry mechanism
  13. * @template T
  14. * @deprecated 25.0.0 use OCP\Cache\CappedMemoryCache instead
  15. */
  16. class CappedMemoryCache implements ICache, \ArrayAccess {
  17. private $capacity;
  18. /** @var T[] */
  19. private $cache = [];
  20. public function __construct($capacity = 512) {
  21. $this->capacity = $capacity;
  22. }
  23. public function hasKey($key): bool {
  24. return isset($this->cache[$key]);
  25. }
  26. /**
  27. * @return ?T
  28. */
  29. public function get($key) {
  30. return $this->cache[$key] ?? null;
  31. }
  32. /**
  33. * @param string $key
  34. * @param T $value
  35. * @param int $ttl
  36. * @return bool
  37. */
  38. public function set($key, $value, $ttl = 0): bool {
  39. if (is_null($key)) {
  40. $this->cache[] = $value;
  41. } else {
  42. $this->cache[$key] = $value;
  43. }
  44. $this->garbageCollect();
  45. return true;
  46. }
  47. public function remove($key) {
  48. unset($this->cache[$key]);
  49. return true;
  50. }
  51. public function clear($prefix = '') {
  52. $this->cache = [];
  53. return true;
  54. }
  55. public function offsetExists($offset): bool {
  56. return $this->hasKey($offset);
  57. }
  58. /**
  59. * @return T
  60. */
  61. #[\ReturnTypeWillChange]
  62. public function &offsetGet($offset) {
  63. return $this->cache[$offset];
  64. }
  65. /**
  66. * @param string $offset
  67. * @param T $value
  68. * @return void
  69. */
  70. public function offsetSet($offset, $value): void {
  71. $this->set($offset, $value);
  72. }
  73. public function offsetUnset($offset): void {
  74. $this->remove($offset);
  75. }
  76. /**
  77. * @return T[]
  78. */
  79. public function getData() {
  80. return $this->cache;
  81. }
  82. private function garbageCollect() {
  83. while (count($this->cache) > $this->capacity) {
  84. reset($this->cache);
  85. $key = key($this->cache);
  86. $this->remove($key);
  87. }
  88. }
  89. public static function isAvailable(): bool {
  90. return true;
  91. }
  92. }