You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

87 lines
2.0 KiB

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