ArrayCache.php 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. <?php
  2. namespace Doctrine\Common\Cache;
  3. use function time;
  4. /**
  5. * Array cache driver.
  6. *
  7. * @link www.doctrine-project.org
  8. */
  9. class ArrayCache extends CacheProvider
  10. {
  11. /** @var array[] $data each element being a tuple of [$data, $expiration], where the expiration is int|bool */
  12. private $data = [];
  13. /** @var int */
  14. private $hitsCount = 0;
  15. /** @var int */
  16. private $missesCount = 0;
  17. /** @var int */
  18. private $upTime;
  19. /**
  20. * {@inheritdoc}
  21. */
  22. public function __construct()
  23. {
  24. $this->upTime = time();
  25. }
  26. /**
  27. * {@inheritdoc}
  28. */
  29. protected function doFetch($id)
  30. {
  31. if (! $this->doContains($id)) {
  32. $this->missesCount += 1;
  33. return false;
  34. }
  35. $this->hitsCount += 1;
  36. return $this->data[$id][0];
  37. }
  38. /**
  39. * {@inheritdoc}
  40. */
  41. protected function doContains($id)
  42. {
  43. if (! isset($this->data[$id])) {
  44. return false;
  45. }
  46. $expiration = $this->data[$id][1];
  47. if ($expiration && $expiration < time()) {
  48. $this->doDelete($id);
  49. return false;
  50. }
  51. return true;
  52. }
  53. /**
  54. * {@inheritdoc}
  55. */
  56. protected function doSave($id, $data, $lifeTime = 0)
  57. {
  58. $this->data[$id] = [$data, $lifeTime ? time() + $lifeTime : false];
  59. return true;
  60. }
  61. /**
  62. * {@inheritdoc}
  63. */
  64. protected function doDelete($id)
  65. {
  66. unset($this->data[$id]);
  67. return true;
  68. }
  69. /**
  70. * {@inheritdoc}
  71. */
  72. protected function doFlush()
  73. {
  74. $this->data = [];
  75. return true;
  76. }
  77. /**
  78. * {@inheritdoc}
  79. */
  80. protected function doGetStats()
  81. {
  82. return [
  83. Cache::STATS_HITS => $this->hitsCount,
  84. Cache::STATS_MISSES => $this->missesCount,
  85. Cache::STATS_UPTIME => $this->upTime,
  86. Cache::STATS_MEMORY_USAGE => null,
  87. Cache::STATS_MEMORY_AVAILABLE => null,
  88. ];
  89. }
  90. }