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.

CappedMemoryCache.php 2.0KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  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. }