AbstractTrait.php 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  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\Traits;
  11. use Psr\Log\LoggerAwareTrait;
  12. use Symfony\Component\Cache\CacheItem;
  13. /**
  14. * @author Nicolas Grekas <p@tchwork.com>
  15. *
  16. * @internal
  17. */
  18. trait AbstractTrait
  19. {
  20. use LoggerAwareTrait;
  21. private $namespace;
  22. private $namespaceVersion = '';
  23. private $versioningIsEnabled = false;
  24. private $deferred = [];
  25. private $ids = [];
  26. /**
  27. * @var int|null The maximum length to enforce for identifiers or null when no limit applies
  28. */
  29. protected $maxIdLength;
  30. /**
  31. * Fetches several cache items.
  32. *
  33. * @param array $ids The cache identifiers to fetch
  34. *
  35. * @return array|\Traversable The corresponding values found in the cache
  36. */
  37. abstract protected function doFetch(array $ids);
  38. /**
  39. * Confirms if the cache contains specified cache item.
  40. *
  41. * @param string $id The identifier for which to check existence
  42. *
  43. * @return bool True if item exists in the cache, false otherwise
  44. */
  45. abstract protected function doHave($id);
  46. /**
  47. * Deletes all items in the pool.
  48. *
  49. * @param string $namespace The prefix used for all identifiers managed by this pool
  50. *
  51. * @return bool True if the pool was successfully cleared, false otherwise
  52. */
  53. abstract protected function doClear($namespace);
  54. /**
  55. * Removes multiple items from the pool.
  56. *
  57. * @param array $ids An array of identifiers that should be removed from the pool
  58. *
  59. * @return bool True if the items were successfully removed, false otherwise
  60. */
  61. abstract protected function doDelete(array $ids);
  62. /**
  63. * Persists several cache items immediately.
  64. *
  65. * @param array $values The values to cache, indexed by their cache identifier
  66. * @param int $lifetime The lifetime of the cached values, 0 for persisting until manual cleaning
  67. *
  68. * @return array|bool The identifiers that failed to be cached or a boolean stating if caching succeeded or not
  69. */
  70. abstract protected function doSave(array $values, int $lifetime);
  71. /**
  72. * {@inheritdoc}
  73. *
  74. * @return bool
  75. */
  76. public function hasItem($key)
  77. {
  78. $id = $this->getId($key);
  79. if (isset($this->deferred[$key])) {
  80. $this->commit();
  81. }
  82. try {
  83. return $this->doHave($id);
  84. } catch (\Exception $e) {
  85. CacheItem::log($this->logger, 'Failed to check if key "{key}" is cached: '.$e->getMessage(), ['key' => $key, 'exception' => $e]);
  86. return false;
  87. }
  88. }
  89. /**
  90. * {@inheritdoc}
  91. *
  92. * @param string $prefix
  93. *
  94. * @return bool
  95. */
  96. public function clear(/*string $prefix = ''*/)
  97. {
  98. $this->deferred = [];
  99. if ($cleared = $this->versioningIsEnabled) {
  100. if ('' === $namespaceVersionToClear = $this->namespaceVersion) {
  101. foreach ($this->doFetch([static::NS_SEPARATOR.$this->namespace]) as $v) {
  102. $namespaceVersionToClear = $v;
  103. }
  104. }
  105. $namespaceToClear = $this->namespace.$namespaceVersionToClear;
  106. $namespaceVersion = self::formatNamespaceVersion(mt_rand());
  107. try {
  108. $e = $this->doSave([static::NS_SEPARATOR.$this->namespace => $namespaceVersion], 0);
  109. } catch (\Exception $e) {
  110. }
  111. if (true !== $e && [] !== $e) {
  112. $cleared = false;
  113. $message = 'Failed to save the new namespace'.($e instanceof \Exception ? ': '.$e->getMessage() : '.');
  114. CacheItem::log($this->logger, $message, ['exception' => $e instanceof \Exception ? $e : null]);
  115. } else {
  116. $this->namespaceVersion = $namespaceVersion;
  117. $this->ids = [];
  118. }
  119. } else {
  120. $prefix = 0 < \func_num_args() ? (string) func_get_arg(0) : '';
  121. $namespaceToClear = $this->namespace.$prefix;
  122. }
  123. try {
  124. return $this->doClear($namespaceToClear) || $cleared;
  125. } catch (\Exception $e) {
  126. CacheItem::log($this->logger, 'Failed to clear the cache: '.$e->getMessage(), ['exception' => $e]);
  127. return false;
  128. }
  129. }
  130. /**
  131. * {@inheritdoc}
  132. *
  133. * @return bool
  134. */
  135. public function deleteItem($key)
  136. {
  137. return $this->deleteItems([$key]);
  138. }
  139. /**
  140. * {@inheritdoc}
  141. *
  142. * @return bool
  143. */
  144. public function deleteItems(array $keys)
  145. {
  146. $ids = [];
  147. foreach ($keys as $key) {
  148. $ids[$key] = $this->getId($key);
  149. unset($this->deferred[$key]);
  150. }
  151. try {
  152. if ($this->doDelete($ids)) {
  153. return true;
  154. }
  155. } catch (\Exception $e) {
  156. }
  157. $ok = true;
  158. // When bulk-delete failed, retry each item individually
  159. foreach ($ids as $key => $id) {
  160. try {
  161. $e = null;
  162. if ($this->doDelete([$id])) {
  163. continue;
  164. }
  165. } catch (\Exception $e) {
  166. }
  167. $message = 'Failed to delete key "{key}"'.($e instanceof \Exception ? ': '.$e->getMessage() : '.');
  168. CacheItem::log($this->logger, $message, ['key' => $key, 'exception' => $e]);
  169. $ok = false;
  170. }
  171. return $ok;
  172. }
  173. /**
  174. * Enables/disables versioning of items.
  175. *
  176. * When versioning is enabled, clearing the cache is atomic and doesn't require listing existing keys to proceed,
  177. * but old keys may need garbage collection and extra round-trips to the back-end are required.
  178. *
  179. * Calling this method also clears the memoized namespace version and thus forces a resynchonization of it.
  180. *
  181. * @param bool $enable
  182. *
  183. * @return bool the previous state of versioning
  184. */
  185. public function enableVersioning($enable = true)
  186. {
  187. $wasEnabled = $this->versioningIsEnabled;
  188. $this->versioningIsEnabled = (bool) $enable;
  189. $this->namespaceVersion = '';
  190. $this->ids = [];
  191. return $wasEnabled;
  192. }
  193. /**
  194. * {@inheritdoc}
  195. */
  196. public function reset()
  197. {
  198. if ($this->deferred) {
  199. $this->commit();
  200. }
  201. $this->namespaceVersion = '';
  202. $this->ids = [];
  203. }
  204. /**
  205. * Like the native unserialize() function but throws an exception if anything goes wrong.
  206. *
  207. * @param string $value
  208. *
  209. * @return mixed
  210. *
  211. * @throws \Exception
  212. *
  213. * @deprecated since Symfony 4.2, use DefaultMarshaller instead.
  214. */
  215. protected static function unserialize($value)
  216. {
  217. @trigger_error(sprintf('The "%s::unserialize()" method is deprecated since Symfony 4.2, use DefaultMarshaller instead.', __CLASS__), \E_USER_DEPRECATED);
  218. if ('b:0;' === $value) {
  219. return false;
  220. }
  221. $unserializeCallbackHandler = ini_set('unserialize_callback_func', __CLASS__.'::handleUnserializeCallback');
  222. try {
  223. if (false !== $value = unserialize($value)) {
  224. return $value;
  225. }
  226. throw new \DomainException('Failed to unserialize cached value.');
  227. } catch (\Error $e) {
  228. throw new \ErrorException($e->getMessage(), $e->getCode(), \E_ERROR, $e->getFile(), $e->getLine());
  229. } finally {
  230. ini_set('unserialize_callback_func', $unserializeCallbackHandler);
  231. }
  232. }
  233. private function getId($key): string
  234. {
  235. if ($this->versioningIsEnabled && '' === $this->namespaceVersion) {
  236. $this->ids = [];
  237. $this->namespaceVersion = '1'.static::NS_SEPARATOR;
  238. try {
  239. foreach ($this->doFetch([static::NS_SEPARATOR.$this->namespace]) as $v) {
  240. $this->namespaceVersion = $v;
  241. }
  242. $e = true;
  243. if ('1'.static::NS_SEPARATOR === $this->namespaceVersion) {
  244. $this->namespaceVersion = self::formatNamespaceVersion(time());
  245. $e = $this->doSave([static::NS_SEPARATOR.$this->namespace => $this->namespaceVersion], 0);
  246. }
  247. } catch (\Exception $e) {
  248. }
  249. if (true !== $e && [] !== $e) {
  250. $message = 'Failed to save the new namespace'.($e instanceof \Exception ? ': '.$e->getMessage() : '.');
  251. CacheItem::log($this->logger, $message, ['exception' => $e instanceof \Exception ? $e : null]);
  252. }
  253. }
  254. if (\is_string($key) && isset($this->ids[$key])) {
  255. return $this->namespace.$this->namespaceVersion.$this->ids[$key];
  256. }
  257. CacheItem::validateKey($key);
  258. $this->ids[$key] = $key;
  259. if (\count($this->ids) > 1000) {
  260. array_splice($this->ids, 0, 500); // stop memory leak if there are many keys
  261. }
  262. if (null === $this->maxIdLength) {
  263. return $this->namespace.$this->namespaceVersion.$key;
  264. }
  265. if (\strlen($id = $this->namespace.$this->namespaceVersion.$key) > $this->maxIdLength) {
  266. // Use MD5 to favor speed over security, which is not an issue here
  267. $this->ids[$key] = $id = substr_replace(base64_encode(hash('md5', $key, true)), static::NS_SEPARATOR, -(\strlen($this->namespaceVersion) + 2));
  268. $id = $this->namespace.$this->namespaceVersion.$id;
  269. }
  270. return $id;
  271. }
  272. /**
  273. * @internal
  274. */
  275. public static function handleUnserializeCallback($class)
  276. {
  277. throw new \DomainException('Class not found: '.$class);
  278. }
  279. private static function formatNamespaceVersion(int $value): string
  280. {
  281. return strtr(substr_replace(base64_encode(pack('V', $value)), static::NS_SEPARATOR, 5), '/', '_');
  282. }
  283. }