AbstractCache.php 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190
  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. /**
  23. * @internal
  24. */
  25. const NS_SEPARATOR = ':';
  26. use AbstractTrait {
  27. deleteItems as private;
  28. AbstractTrait::deleteItem as delete;
  29. AbstractTrait::hasItem as has;
  30. }
  31. private $defaultLifetime;
  32. /**
  33. * @param string $namespace
  34. * @param int $defaultLifetime
  35. */
  36. protected function __construct($namespace = '', $defaultLifetime = 0)
  37. {
  38. $this->defaultLifetime = max(0, (int) $defaultLifetime);
  39. $this->namespace = '' === $namespace ? '' : CacheItem::validateKey($namespace).':';
  40. if (null !== $this->maxIdLength && \strlen($namespace) > $this->maxIdLength - 24) {
  41. throw new InvalidArgumentException(sprintf('Namespace must be %d chars max, %d given ("%s").', $this->maxIdLength - 24, \strlen($namespace), $namespace));
  42. }
  43. }
  44. /**
  45. * {@inheritdoc}
  46. */
  47. public function get($key, $default = null)
  48. {
  49. $id = $this->getId($key);
  50. try {
  51. foreach ($this->doFetch([$id]) as $value) {
  52. return $value;
  53. }
  54. } catch (\Exception $e) {
  55. CacheItem::log($this->logger, 'Failed to fetch key "{key}"', ['key' => $key, 'exception' => $e]);
  56. }
  57. return $default;
  58. }
  59. /**
  60. * {@inheritdoc}
  61. */
  62. public function set($key, $value, $ttl = null)
  63. {
  64. CacheItem::validateKey($key);
  65. return $this->setMultiple([$key => $value], $ttl);
  66. }
  67. /**
  68. * {@inheritdoc}
  69. */
  70. public function getMultiple($keys, $default = null)
  71. {
  72. if ($keys instanceof \Traversable) {
  73. $keys = iterator_to_array($keys, false);
  74. } elseif (!\is_array($keys)) {
  75. throw new InvalidArgumentException(sprintf('Cache keys must be array or Traversable, "%s" given.', \is_object($keys) ? \get_class($keys) : \gettype($keys)));
  76. }
  77. $ids = [];
  78. foreach ($keys as $key) {
  79. $ids[] = $this->getId($key);
  80. }
  81. try {
  82. $values = $this->doFetch($ids);
  83. } catch (\Exception $e) {
  84. CacheItem::log($this->logger, 'Failed to fetch requested values', ['keys' => $keys, 'exception' => $e]);
  85. $values = [];
  86. }
  87. $ids = array_combine($ids, $keys);
  88. return $this->generateValues($values, $ids, $default);
  89. }
  90. /**
  91. * {@inheritdoc}
  92. */
  93. public function setMultiple($values, $ttl = null)
  94. {
  95. if (!\is_array($values) && !$values instanceof \Traversable) {
  96. throw new InvalidArgumentException(sprintf('Cache values must be array or Traversable, "%s" given.', \is_object($values) ? \get_class($values) : \gettype($values)));
  97. }
  98. $valuesById = [];
  99. foreach ($values as $key => $value) {
  100. if (\is_int($key)) {
  101. $key = (string) $key;
  102. }
  103. $valuesById[$this->getId($key)] = $value;
  104. }
  105. if (false === $ttl = $this->normalizeTtl($ttl)) {
  106. return $this->doDelete(array_keys($valuesById));
  107. }
  108. try {
  109. $e = $this->doSave($valuesById, $ttl);
  110. } catch (\Exception $e) {
  111. }
  112. if (true === $e || [] === $e) {
  113. return true;
  114. }
  115. $keys = [];
  116. foreach (\is_array($e) ? $e : array_keys($valuesById) as $id) {
  117. $keys[] = substr($id, \strlen($this->namespace));
  118. }
  119. CacheItem::log($this->logger, 'Failed to save values', ['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 requested values', ['keys' => array_values($keys), 'exception' => $e]);
  160. }
  161. foreach ($keys as $key) {
  162. yield $key => $default;
  163. }
  164. }
  165. }