ArrayTrait.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\Cache\Traits;
  11. use Psr\Log\LoggerAwareTrait;
  12. use Symfony\Component\Cache\CacheItem;
  13. /**
  14. * @author Nicolas Grekas <p@tchwork.com>
  15. *
  16. * @internal
  17. */
  18. trait ArrayTrait
  19. {
  20. use LoggerAwareTrait;
  21. private $storeSerialized;
  22. private $values = [];
  23. private $expiries = [];
  24. /**
  25. * Returns all cached values, with cache miss as null.
  26. *
  27. * @return array
  28. */
  29. public function getValues()
  30. {
  31. return $this->values;
  32. }
  33. /**
  34. * {@inheritdoc}
  35. */
  36. public function hasItem($key)
  37. {
  38. CacheItem::validateKey($key);
  39. return isset($this->expiries[$key]) && ($this->expiries[$key] > time() || !$this->deleteItem($key));
  40. }
  41. /**
  42. * {@inheritdoc}
  43. */
  44. public function clear()
  45. {
  46. $this->values = $this->expiries = [];
  47. return true;
  48. }
  49. /**
  50. * {@inheritdoc}
  51. */
  52. public function deleteItem($key)
  53. {
  54. CacheItem::validateKey($key);
  55. unset($this->values[$key], $this->expiries[$key]);
  56. return true;
  57. }
  58. /**
  59. * {@inheritdoc}
  60. */
  61. public function reset()
  62. {
  63. $this->clear();
  64. }
  65. private function generateItems(array $keys, $now, $f)
  66. {
  67. foreach ($keys as $i => $key) {
  68. try {
  69. if (!$isHit = isset($this->expiries[$key]) && ($this->expiries[$key] > $now || !$this->deleteItem($key))) {
  70. $this->values[$key] = $value = null;
  71. } elseif (!$this->storeSerialized) {
  72. $value = $this->values[$key];
  73. } elseif ('b:0;' === $value = $this->values[$key]) {
  74. $value = false;
  75. } elseif (false === $value = unserialize($value)) {
  76. $this->values[$key] = $value = null;
  77. $isHit = false;
  78. }
  79. } catch (\Exception $e) {
  80. CacheItem::log($this->logger, 'Failed to unserialize key "{key}"', ['key' => $key, 'exception' => $e]);
  81. $this->values[$key] = $value = null;
  82. $isHit = false;
  83. }
  84. unset($keys[$i]);
  85. yield $key => $f($key, $value, $isHit);
  86. }
  87. foreach ($keys as $key) {
  88. yield $key => $f($key, null, false);
  89. }
  90. }
  91. }