AbstractTrait.php 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  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 = strtr(substr_replace(base64_encode(pack('V', mt_rand())), static::NS_SEPARATOR, 5), '/', '_');
  107. try {
  108. $cleared = $this->doSave([static::NS_SEPARATOR.$this->namespace => $namespaceVersion], 0);
  109. } catch (\Exception $e) {
  110. $cleared = false;
  111. }
  112. if ($cleared = true === $cleared || [] === $cleared) {
  113. $this->namespaceVersion = $namespaceVersion;
  114. $this->ids = [];
  115. }
  116. } else {
  117. $prefix = 0 < \func_num_args() ? (string) func_get_arg(0) : '';
  118. $namespaceToClear = $this->namespace.$prefix;
  119. }
  120. try {
  121. return $this->doClear($namespaceToClear) || $cleared;
  122. } catch (\Exception $e) {
  123. CacheItem::log($this->logger, 'Failed to clear the cache: '.$e->getMessage(), ['exception' => $e]);
  124. return false;
  125. }
  126. }
  127. /**
  128. * {@inheritdoc}
  129. *
  130. * @return bool
  131. */
  132. public function deleteItem($key)
  133. {
  134. return $this->deleteItems([$key]);
  135. }
  136. /**
  137. * {@inheritdoc}
  138. *
  139. * @return bool
  140. */
  141. public function deleteItems(array $keys)
  142. {
  143. $ids = [];
  144. foreach ($keys as $key) {
  145. $ids[$key] = $this->getId($key);
  146. unset($this->deferred[$key]);
  147. }
  148. try {
  149. if ($this->doDelete($ids)) {
  150. return true;
  151. }
  152. } catch (\Exception $e) {
  153. }
  154. $ok = true;
  155. // When bulk-delete failed, retry each item individually
  156. foreach ($ids as $key => $id) {
  157. try {
  158. $e = null;
  159. if ($this->doDelete([$id])) {
  160. continue;
  161. }
  162. } catch (\Exception $e) {
  163. }
  164. $message = 'Failed to delete key "{key}"'.($e instanceof \Exception ? ': '.$e->getMessage() : '.');
  165. CacheItem::log($this->logger, $message, ['key' => $key, 'exception' => $e]);
  166. $ok = false;
  167. }
  168. return $ok;
  169. }
  170. /**
  171. * Enables/disables versioning of items.
  172. *
  173. * When versioning is enabled, clearing the cache is atomic and doesn't require listing existing keys to proceed,
  174. * but old keys may need garbage collection and extra round-trips to the back-end are required.
  175. *
  176. * Calling this method also clears the memoized namespace version and thus forces a resynchonization of it.
  177. *
  178. * @param bool $enable
  179. *
  180. * @return bool the previous state of versioning
  181. */
  182. public function enableVersioning($enable = true)
  183. {
  184. $wasEnabled = $this->versioningIsEnabled;
  185. $this->versioningIsEnabled = (bool) $enable;
  186. $this->namespaceVersion = '';
  187. $this->ids = [];
  188. return $wasEnabled;
  189. }
  190. /**
  191. * {@inheritdoc}
  192. */
  193. public function reset()
  194. {
  195. if ($this->deferred) {
  196. $this->commit();
  197. }
  198. $this->namespaceVersion = '';
  199. $this->ids = [];
  200. }
  201. /**
  202. * Like the native unserialize() function but throws an exception if anything goes wrong.
  203. *
  204. * @param string $value
  205. *
  206. * @return mixed
  207. *
  208. * @throws \Exception
  209. *
  210. * @deprecated since Symfony 4.2, use DefaultMarshaller instead.
  211. */
  212. protected static function unserialize($value)
  213. {
  214. @trigger_error(sprintf('The "%s::unserialize()" method is deprecated since Symfony 4.2, use DefaultMarshaller instead.', __CLASS__), \E_USER_DEPRECATED);
  215. if ('b:0;' === $value) {
  216. return false;
  217. }
  218. $unserializeCallbackHandler = ini_set('unserialize_callback_func', __CLASS__.'::handleUnserializeCallback');
  219. try {
  220. if (false !== $value = unserialize($value)) {
  221. return $value;
  222. }
  223. throw new \DomainException('Failed to unserialize cached value.');
  224. } catch (\Error $e) {
  225. throw new \ErrorException($e->getMessage(), $e->getCode(), \E_ERROR, $e->getFile(), $e->getLine());
  226. } finally {
  227. ini_set('unserialize_callback_func', $unserializeCallbackHandler);
  228. }
  229. }
  230. private function getId($key): string
  231. {
  232. if ($this->versioningIsEnabled && '' === $this->namespaceVersion) {
  233. $this->ids = [];
  234. $this->namespaceVersion = '1'.static::NS_SEPARATOR;
  235. try {
  236. foreach ($this->doFetch([static::NS_SEPARATOR.$this->namespace]) as $v) {
  237. $this->namespaceVersion = $v;
  238. }
  239. if ('1'.static::NS_SEPARATOR === $this->namespaceVersion) {
  240. $this->namespaceVersion = strtr(substr_replace(base64_encode(pack('V', time())), static::NS_SEPARATOR, 5), '/', '_');
  241. $this->doSave([static::NS_SEPARATOR.$this->namespace => $this->namespaceVersion], 0);
  242. }
  243. } catch (\Exception $e) {
  244. }
  245. }
  246. if (\is_string($key) && isset($this->ids[$key])) {
  247. return $this->namespace.$this->namespaceVersion.$this->ids[$key];
  248. }
  249. CacheItem::validateKey($key);
  250. $this->ids[$key] = $key;
  251. if (null === $this->maxIdLength) {
  252. return $this->namespace.$this->namespaceVersion.$key;
  253. }
  254. if (\strlen($id = $this->namespace.$this->namespaceVersion.$key) > $this->maxIdLength) {
  255. // Use MD5 to favor speed over security, which is not an issue here
  256. $this->ids[$key] = $id = substr_replace(base64_encode(hash('md5', $key, true)), static::NS_SEPARATOR, -(\strlen($this->namespaceVersion) + 2));
  257. $id = $this->namespace.$this->namespaceVersion.$id;
  258. }
  259. return $id;
  260. }
  261. /**
  262. * @internal
  263. */
  264. public static function handleUnserializeCallback($class)
  265. {
  266. throw new \DomainException('Class not found: '.$class);
  267. }
  268. }