AbstractCache.php 6.2 KB

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