PageRenderTime 59ms CodeModel.GetById 33ms RepoModel.GetById 0ms app.codeStats 0ms

/src/Symfony/Component/Cache/Traits/AbstractTrait.php

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