CappedMemoryCache.php 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. *
  5. * @author Robin Appelman <robin@icewind.nl>
  6. *
  7. * @license AGPL-3.0
  8. *
  9. * This code is free software: you can redistribute it and/or modify
  10. * it under the terms of the GNU Affero General Public License, version 3,
  11. * as published by the Free Software Foundation.
  12. *
  13. * This program is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. * GNU Affero General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU Affero General Public License, version 3,
  19. * along with this program. If not, see <http://www.gnu.org/licenses/>
  20. *
  21. */
  22. namespace OC\Cache;
  23. use OCP\ICache;
  24. /**
  25. * In-memory cache with a capacity limit to keep memory usage in check
  26. *
  27. * Uses a simple FIFO expiry mechanism
  28. */
  29. class CappedMemoryCache implements ICache, \ArrayAccess {
  30. private $capacity;
  31. private $cache = [];
  32. public function __construct($capacity = 512) {
  33. $this->capacity = $capacity;
  34. }
  35. public function hasKey($key) {
  36. return isset($this->cache[$key]);
  37. }
  38. public function get($key) {
  39. return isset($this->cache[$key]) ? $this->cache[$key] : null;
  40. }
  41. public function set($key, $value, $ttl = 0) {
  42. if (is_null($key)) {
  43. $this->cache[] = $value;
  44. } else {
  45. $this->cache[$key] = $value;
  46. }
  47. $this->garbageCollect();
  48. }
  49. public function remove($key) {
  50. unset($this->cache[$key]);
  51. return true;
  52. }
  53. public function clear($prefix = '') {
  54. $this->cache = [];
  55. return true;
  56. }
  57. public function offsetExists($offset) {
  58. return $this->hasKey($offset);
  59. }
  60. public function &offsetGet($offset) {
  61. return $this->cache[$offset];
  62. }
  63. public function offsetSet($offset, $value) {
  64. $this->set($offset, $value);
  65. }
  66. public function offsetUnset($offset) {
  67. $this->remove($offset);
  68. }
  69. public function getData() {
  70. return $this->cache;
  71. }
  72. private function garbageCollect() {
  73. while (count($this->cache) > $this->capacity) {
  74. reset($this->cache);
  75. $key = key($this->cache);
  76. $this->remove($key);
  77. }
  78. }
  79. }