CappedMemoryCache.php 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  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. $this->cache[$key] = $value;
  43. $this->garbageCollect();
  44. }
  45. public function remove($key) {
  46. unset($this->cache[$key]);
  47. return true;
  48. }
  49. public function clear($prefix = '') {
  50. $this->cache = [];
  51. return true;
  52. }
  53. public function offsetExists($offset) {
  54. return $this->hasKey($offset);
  55. }
  56. public function &offsetGet($offset) {
  57. return $this->cache[$offset];
  58. }
  59. public function offsetSet($offset, $value) {
  60. $this->set($offset, $value);
  61. }
  62. public function offsetUnset($offset) {
  63. $this->remove($offset);
  64. }
  65. public function getData() {
  66. return $this->cache;
  67. }
  68. private function garbageCollect() {
  69. while (count($this->cache) > $this->capacity) {
  70. reset($this->cache);
  71. $key = key($this->cache);
  72. $this->remove($key);
  73. }
  74. }
  75. }