AbstractCache.php 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181
  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\Simple;
  11. use Psr\Log\LoggerAwareInterface;
  12. use Psr\SimpleCache\CacheInterface;
  13. use Symfony\Component\Cache\CacheItem;
  14. use Symfony\Component\Cache\Exception\InvalidArgumentException;
  15. use Symfony\Component\Cache\ResettableInterface;
  16. use Symfony\Component\Cache\Traits\AbstractTrait;
  17. /**
  18. * @author Nicolas Grekas <p@tchwork.com>
  19. */
  20. abstract class AbstractCache implements CacheInterface, LoggerAwareInterface, ResettableInterface
  21. {
  22. use AbstractTrait {
  23. deleteItems as private;
  24. AbstractTrait::deleteItem as delete;
  25. AbstractTrait::hasItem as has;
  26. }
  27. private $defaultLifetime;
  28. protected function __construct(string $namespace = '', int $defaultLifetime = 0)
  29. {
  30. $this->defaultLifetime = max(0, $defaultLifetime);
  31. $this->namespace = '' === $namespace ? '' : CacheItem::validateKey($namespace).':';
  32. if (null !== $this->maxIdLength && \strlen($namespace) > $this->maxIdLength - 24) {
  33. throw new InvalidArgumentException(sprintf('Namespace must be %d chars max, %d given ("%s")', $this->maxIdLength - 24, \strlen($namespace), $namespace));
  34. }
  35. }
  36. /**
  37. * {@inheritdoc}
  38. */
  39. public function get($key, $default = null)
  40. {
  41. $id = $this->getId($key);
  42. try {
  43. foreach ($this->doFetch([$id]) as $value) {
  44. return $value;
  45. }
  46. } catch (\Exception $e) {
  47. CacheItem::log($this->logger, 'Failed to fetch key "{key}"', ['key' => $key, 'exception' => $e]);
  48. }
  49. return $default;
  50. }
  51. /**
  52. * {@inheritdoc}
  53. */
  54. public function set($key, $value, $ttl = null)
  55. {
  56. CacheItem::validateKey($key);
  57. return $this->setMultiple([$key => $value], $ttl);
  58. }
  59. /**
  60. * {@inheritdoc}
  61. */
  62. public function getMultiple($keys, $default = null)
  63. {
  64. if ($keys instanceof \Traversable) {
  65. $keys = iterator_to_array($keys, false);
  66. } elseif (!\is_array($keys)) {
  67. throw new InvalidArgumentException(sprintf('Cache keys must be array or Traversable, "%s" given', \is_object($keys) ? \get_class($keys) : \gettype($keys)));
  68. }
  69. $ids = [];
  70. foreach ($keys as $key) {
  71. $ids[] = $this->getId($key);
  72. }
  73. try {
  74. $values = $this->doFetch($ids);
  75. } catch (\Exception $e) {
  76. CacheItem::log($this->logger, 'Failed to fetch requested values', ['keys' => $keys, 'exception' => $e]);
  77. $values = [];
  78. }
  79. $ids = array_combine($ids, $keys);
  80. return $this->generateValues($values, $ids, $default);
  81. }
  82. /**
  83. * {@inheritdoc}
  84. */
  85. public function setMultiple($values, $ttl = null)
  86. {
  87. if (!\is_array($values) && !$values instanceof \Traversable) {
  88. throw new InvalidArgumentException(sprintf('Cache values must be array or Traversable, "%s" given', \is_object($values) ? \get_class($values) : \gettype($values)));
  89. }
  90. $valuesById = [];
  91. foreach ($values as $key => $value) {
  92. if (\is_int($key)) {
  93. $key = (string) $key;
  94. }
  95. $valuesById[$this->getId($key)] = $value;
  96. }
  97. if (false === $ttl = $this->normalizeTtl($ttl)) {
  98. return $this->doDelete(array_keys($valuesById));
  99. }
  100. try {
  101. $e = $this->doSave($valuesById, $ttl);
  102. } catch (\Exception $e) {
  103. }
  104. if (true === $e || [] === $e) {
  105. return true;
  106. }
  107. $keys = [];
  108. foreach (\is_array($e) ? $e : array_keys($valuesById) as $id) {
  109. $keys[] = substr($id, \strlen($this->namespace));
  110. }
  111. CacheItem::log($this->logger, 'Failed to save values', ['keys' => $keys, 'exception' => $e instanceof \Exception ? $e : null]);
  112. return false;
  113. }
  114. /**
  115. * {@inheritdoc}
  116. */
  117. public function deleteMultiple($keys)
  118. {
  119. if ($keys instanceof \Traversable) {
  120. $keys = iterator_to_array($keys, false);
  121. } elseif (!\is_array($keys)) {
  122. throw new InvalidArgumentException(sprintf('Cache keys must be array or Traversable, "%s" given', \is_object($keys) ? \get_class($keys) : \gettype($keys)));
  123. }
  124. return $this->deleteItems($keys);
  125. }
  126. private function normalizeTtl($ttl)
  127. {
  128. if (null === $ttl) {
  129. return $this->defaultLifetime;
  130. }
  131. if ($ttl instanceof \DateInterval) {
  132. $ttl = (int) \DateTime::createFromFormat('U', 0)->add($ttl)->format('U');
  133. }
  134. if (\is_int($ttl)) {
  135. return 0 < $ttl ? $ttl : false;
  136. }
  137. throw new InvalidArgumentException(sprintf('Expiration date must be an integer, a DateInterval or null, "%s" given', \is_object($ttl) ? \get_class($ttl) : \gettype($ttl)));
  138. }
  139. private function generateValues($values, &$keys, $default)
  140. {
  141. try {
  142. foreach ($values as $id => $value) {
  143. if (!isset($keys[$id])) {
  144. $id = key($keys);
  145. }
  146. $key = $keys[$id];
  147. unset($keys[$id]);
  148. yield $key => $value;
  149. }
  150. } catch (\Exception $e) {
  151. CacheItem::log($this->logger, 'Failed to fetch requested values', ['keys' => array_values($keys), 'exception' => $e]);
  152. }
  153. foreach ($keys as $key) {
  154. yield $key => $default;
  155. }
  156. }
  157. }