PageRenderTime 43ms CodeModel.GetById 6ms RepoModel.GetById 0ms app.codeStats 0ms

/src/Symfony/Component/Cache/Adapter/AbstractAdapter.php

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