AbstractTrait.php 8.4 KB

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