AbstractAdapter.php 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200
  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\Adapter;
  11. use Psr\Log\LoggerAwareInterface;
  12. use Psr\Log\LoggerInterface;
  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\AbstractAdapterTrait;
  17. use Symfony\Component\Cache\Traits\ContractsTrait;
  18. use Symfony\Contracts\Cache\CacheInterface;
  19. /**
  20. * @author Nicolas Grekas <p@tchwork.com>
  21. */
  22. abstract class AbstractAdapter implements AdapterInterface, CacheInterface, LoggerAwareInterface, ResettableInterface
  23. {
  24. /**
  25. * @internal
  26. */
  27. protected const NS_SEPARATOR = ':';
  28. use AbstractAdapterTrait;
  29. use ContractsTrait;
  30. private static $apcuSupported;
  31. private static $phpFilesSupported;
  32. protected function __construct(string $namespace = '', int $defaultLifetime = 0)
  33. {
  34. $this->namespace = '' === $namespace ? '' : CacheItem::validateKey($namespace).static::NS_SEPARATOR;
  35. if (null !== $this->maxIdLength && \strlen($namespace) > $this->maxIdLength - 24) {
  36. throw new InvalidArgumentException(sprintf('Namespace must be %d chars max, %d given ("%s").', $this->maxIdLength - 24, \strlen($namespace), $namespace));
  37. }
  38. $this->createCacheItem = \Closure::bind(
  39. static function ($key, $value, $isHit) {
  40. $item = new CacheItem();
  41. $item->key = $key;
  42. $item->value = $v = $value;
  43. $item->isHit = $isHit;
  44. // Detect wrapped values that encode for their expiry and creation duration
  45. // For compactness, these values are packed in the key of an array using
  46. // magic numbers in the form 9D-..-..-..-..-00-..-..-..-5F
  47. if (\is_array($v) && 1 === \count($v) && 10 === \strlen($k = (string) key($v)) && "\x9D" === $k[0] && "\0" === $k[5] && "\x5F" === $k[9]) {
  48. $item->value = $v[$k];
  49. $v = unpack('Ve/Nc', substr($k, 1, -1));
  50. $item->metadata[CacheItem::METADATA_EXPIRY] = $v['e'] + CacheItem::METADATA_EXPIRY_OFFSET;
  51. $item->metadata[CacheItem::METADATA_CTIME] = $v['c'];
  52. }
  53. return $item;
  54. },
  55. null,
  56. CacheItem::class
  57. );
  58. $getId = \Closure::fromCallable([$this, 'getId']);
  59. $this->mergeByLifetime = \Closure::bind(
  60. static function ($deferred, $namespace, &$expiredIds) use ($getId, $defaultLifetime) {
  61. $byLifetime = [];
  62. $now = microtime(true);
  63. $expiredIds = [];
  64. foreach ($deferred as $key => $item) {
  65. $key = (string) $key;
  66. if (null === $item->expiry) {
  67. $ttl = 0 < $defaultLifetime ? $defaultLifetime : 0;
  68. } elseif (0 === $item->expiry) {
  69. $ttl = 0;
  70. } elseif (0 >= $ttl = (int) (0.1 + $item->expiry - $now)) {
  71. $expiredIds[] = $getId($key);
  72. continue;
  73. }
  74. if (isset(($metadata = $item->newMetadata)[CacheItem::METADATA_TAGS])) {
  75. unset($metadata[CacheItem::METADATA_TAGS]);
  76. }
  77. // For compactness, expiry and creation duration are packed in the key of an array, using magic numbers as separators
  78. $byLifetime[$ttl][$getId($key)] = $metadata ? ["\x9D".pack('VN', (int) (0.1 + $metadata[self::METADATA_EXPIRY] - self::METADATA_EXPIRY_OFFSET), $metadata[self::METADATA_CTIME])."\x5F" => $item->value] : $item->value;
  79. }
  80. return $byLifetime;
  81. },
  82. null,
  83. CacheItem::class
  84. );
  85. }
  86. /**
  87. * Returns the best possible adapter that your runtime supports.
  88. *
  89. * Using ApcuAdapter makes system caches compatible with read-only filesystems.
  90. *
  91. * @return AdapterInterface
  92. */
  93. public static function createSystemCache(string $namespace, int $defaultLifetime, string $version, string $directory, LoggerInterface $logger = null)
  94. {
  95. $opcache = new PhpFilesAdapter($namespace, $defaultLifetime, $directory, true);
  96. if (null !== $logger) {
  97. $opcache->setLogger($logger);
  98. }
  99. if (!self::$apcuSupported = self::$apcuSupported ?? ApcuAdapter::isSupported()) {
  100. return $opcache;
  101. }
  102. if (\in_array(\PHP_SAPI, ['cli', 'phpdbg'], true) && !filter_var(ini_get('apc.enable_cli'), \FILTER_VALIDATE_BOOLEAN)) {
  103. return $opcache;
  104. }
  105. $apcu = new ApcuAdapter($namespace, (int) $defaultLifetime / 5, $version);
  106. if (null !== $logger) {
  107. $apcu->setLogger($logger);
  108. }
  109. return new ChainAdapter([$apcu, $opcache]);
  110. }
  111. public static function createConnection(string $dsn, array $options = [])
  112. {
  113. if (0 === strpos($dsn, 'redis:') || 0 === strpos($dsn, 'rediss:')) {
  114. return RedisAdapter::createConnection($dsn, $options);
  115. }
  116. if (0 === strpos($dsn, 'memcached:')) {
  117. return MemcachedAdapter::createConnection($dsn, $options);
  118. }
  119. if (0 === strpos($dsn, 'couchbase:')) {
  120. return CouchbaseBucketAdapter::createConnection($dsn, $options);
  121. }
  122. throw new InvalidArgumentException(sprintf('Unsupported DSN: "%s".', $dsn));
  123. }
  124. /**
  125. * {@inheritdoc}
  126. *
  127. * @return bool
  128. */
  129. public function commit()
  130. {
  131. $ok = true;
  132. $byLifetime = $this->mergeByLifetime;
  133. $byLifetime = $byLifetime($this->deferred, $this->namespace, $expiredIds);
  134. $retry = $this->deferred = [];
  135. if ($expiredIds) {
  136. $this->doDelete($expiredIds);
  137. }
  138. foreach ($byLifetime as $lifetime => $values) {
  139. try {
  140. $e = $this->doSave($values, $lifetime);
  141. } catch (\Exception $e) {
  142. }
  143. if (true === $e || [] === $e) {
  144. continue;
  145. }
  146. if (\is_array($e) || 1 === \count($values)) {
  147. foreach (\is_array($e) ? $e : array_keys($values) as $id) {
  148. $ok = false;
  149. $v = $values[$id];
  150. $type = get_debug_type($v);
  151. $message = sprintf('Failed to save key "{key}" of type %s%s', $type, $e instanceof \Exception ? ': '.$e->getMessage() : '.');
  152. CacheItem::log($this->logger, $message, ['key' => substr($id, \strlen($this->namespace)), 'exception' => $e instanceof \Exception ? $e : null, 'cache-adapter' => get_debug_type($this)]);
  153. }
  154. } else {
  155. foreach ($values as $id => $v) {
  156. $retry[$lifetime][] = $id;
  157. }
  158. }
  159. }
  160. // When bulk-save failed, retry each item individually
  161. foreach ($retry as $lifetime => $ids) {
  162. foreach ($ids as $id) {
  163. try {
  164. $v = $byLifetime[$lifetime][$id];
  165. $e = $this->doSave([$id => $v], $lifetime);
  166. } catch (\Exception $e) {
  167. }
  168. if (true === $e || [] === $e) {
  169. continue;
  170. }
  171. $ok = false;
  172. $type = get_debug_type($v);
  173. $message = sprintf('Failed to save key "{key}" of type %s%s', $type, $e instanceof \Exception ? ': '.$e->getMessage() : '.');
  174. CacheItem::log($this->logger, $message, ['key' => substr($id, \strlen($this->namespace)), 'exception' => $e instanceof \Exception ? $e : null, 'cache-adapter' => get_debug_type($this)]);
  175. }
  176. }
  177. return $ok;
  178. }
  179. }