PageRenderTime 49ms CodeModel.GetById 24ms RepoModel.GetById 0ms app.codeStats 0ms

/core/lib/Drupal/Core/Cache/ApcuBackend.php

http://github.com/drupal/drupal
PHP | 273 lines | 107 code | 33 blank | 133 comment | 8 complexity | 20bd1538b79d920b0ccb322daa26d7c2 MD5 | raw file
Possible License(s): GPL-2.0, LGPL-2.1
  1. <?php
  2. namespace Drupal\Core\Cache;
  3. use Drupal\Component\Assertion\Inspector;
  4. /**
  5. * Stores cache items in the Alternative PHP Cache User Cache (APCu).
  6. */
  7. class ApcuBackend implements CacheBackendInterface {
  8. /**
  9. * The name of the cache bin to use.
  10. *
  11. * @var string
  12. */
  13. protected $bin;
  14. /**
  15. * Prefix for all keys in the storage that belong to this site.
  16. *
  17. * @var string
  18. */
  19. protected $sitePrefix;
  20. /**
  21. * Prefix for all keys in this cache bin.
  22. *
  23. * Includes the site-specific prefix in $sitePrefix.
  24. *
  25. * @var string
  26. */
  27. protected $binPrefix;
  28. /**
  29. * The cache tags checksum provider.
  30. *
  31. * @var \Drupal\Core\Cache\CacheTagsChecksumInterface
  32. */
  33. protected $checksumProvider;
  34. /**
  35. * Constructs a new ApcuBackend instance.
  36. *
  37. * @param string $bin
  38. * The name of the cache bin.
  39. * @param string $site_prefix
  40. * The prefix to use for all keys in the storage that belong to this site.
  41. * @param \Drupal\Core\Cache\CacheTagsChecksumInterface $checksum_provider
  42. * The cache tags checksum provider.
  43. */
  44. public function __construct($bin, $site_prefix, CacheTagsChecksumInterface $checksum_provider) {
  45. $this->bin = $bin;
  46. $this->sitePrefix = $site_prefix;
  47. $this->checksumProvider = $checksum_provider;
  48. $this->binPrefix = $this->sitePrefix . '::' . $this->bin . '::';
  49. }
  50. /**
  51. * Prepends the APCu user variable prefix for this bin to a cache item ID.
  52. *
  53. * @param string $cid
  54. * The cache item ID to prefix.
  55. *
  56. * @return string
  57. * The APCu key for the cache item ID.
  58. */
  59. public function getApcuKey($cid) {
  60. return $this->binPrefix . $cid;
  61. }
  62. /**
  63. * {@inheritdoc}
  64. */
  65. public function get($cid, $allow_invalid = FALSE) {
  66. $cache = apcu_fetch($this->getApcuKey($cid));
  67. return $this->prepareItem($cache, $allow_invalid);
  68. }
  69. /**
  70. * {@inheritdoc}
  71. */
  72. public function getMultiple(&$cids, $allow_invalid = FALSE) {
  73. // Translate the requested cache item IDs to APCu keys.
  74. $map = [];
  75. foreach ($cids as $cid) {
  76. $map[$this->getApcuKey($cid)] = $cid;
  77. }
  78. $result = apcu_fetch(array_keys($map));
  79. $cache = [];
  80. if ($result) {
  81. foreach ($result as $key => $item) {
  82. $item = $this->prepareItem($item, $allow_invalid);
  83. if ($item) {
  84. $cache[$map[$key]] = $item;
  85. }
  86. }
  87. }
  88. unset($result);
  89. $cids = array_diff($cids, array_keys($cache));
  90. return $cache;
  91. }
  92. /**
  93. * Returns all cached items, optionally limited by a cache ID prefix.
  94. *
  95. * APCu is a memory cache, shared across all server processes. To prevent
  96. * cache item clashes with other applications/installations, every cache item
  97. * is prefixed with a unique string for this site. Therefore, functions like
  98. * apcu_clear_cache() cannot be used, and instead, a list of all cache items
  99. * belonging to this application need to be retrieved through this method
  100. * instead.
  101. *
  102. * @param string $prefix
  103. * (optional) A cache ID prefix to limit the result to.
  104. *
  105. * @return \APCUIterator
  106. * An APCUIterator containing matched items.
  107. */
  108. protected function getAll($prefix = '') {
  109. return $this->getIterator('/^' . preg_quote($this->getApcuKey($prefix), '/') . '/');
  110. }
  111. /**
  112. * Prepares a cached item.
  113. *
  114. * Checks that the item is either permanent or did not expire.
  115. *
  116. * @param object $cache
  117. * An item loaded from self::get() or self::getMultiple().
  118. * @param bool $allow_invalid
  119. * If TRUE, a cache item may be returned even if it is expired or has been
  120. * invalidated. See ::get().
  121. *
  122. * @return mixed
  123. * The cache item or FALSE if the item expired.
  124. */
  125. protected function prepareItem($cache, $allow_invalid) {
  126. if (!isset($cache->data)) {
  127. return FALSE;
  128. }
  129. $cache->tags = $cache->tags ? explode(' ', $cache->tags) : [];
  130. // Check expire time.
  131. $cache->valid = $cache->expire == Cache::PERMANENT || $cache->expire >= REQUEST_TIME;
  132. // Check if invalidateTags() has been called with any of the entry's tags.
  133. if (!$this->checksumProvider->isValid($cache->checksum, $cache->tags)) {
  134. $cache->valid = FALSE;
  135. }
  136. if (!$allow_invalid && !$cache->valid) {
  137. return FALSE;
  138. }
  139. return $cache;
  140. }
  141. /**
  142. * {@inheritdoc}
  143. */
  144. public function set($cid, $data, $expire = CacheBackendInterface::CACHE_PERMANENT, array $tags = []) {
  145. assert(Inspector::assertAllStrings($tags), 'Cache tags must be strings.');
  146. $tags = array_unique($tags);
  147. $cache = new \stdClass();
  148. $cache->cid = $cid;
  149. $cache->created = round(microtime(TRUE), 3);
  150. $cache->expire = $expire;
  151. $cache->tags = implode(' ', $tags);
  152. $cache->checksum = $this->checksumProvider->getCurrentChecksum($tags);
  153. // APCu serializes/unserializes any structure itself.
  154. $cache->serialized = 0;
  155. $cache->data = $data;
  156. // Expiration is handled by our own prepareItem(), not APCu.
  157. apcu_store($this->getApcuKey($cid), $cache);
  158. }
  159. /**
  160. * {@inheritdoc}
  161. */
  162. public function setMultiple(array $items = []) {
  163. foreach ($items as $cid => $item) {
  164. $this->set($cid, $item['data'], isset($item['expire']) ? $item['expire'] : CacheBackendInterface::CACHE_PERMANENT, isset($item['tags']) ? $item['tags'] : []);
  165. }
  166. }
  167. /**
  168. * {@inheritdoc}
  169. */
  170. public function delete($cid) {
  171. apcu_delete($this->getApcuKey($cid));
  172. }
  173. /**
  174. * {@inheritdoc}
  175. */
  176. public function deleteMultiple(array $cids) {
  177. apcu_delete(array_map([$this, 'getApcuKey'], $cids));
  178. }
  179. /**
  180. * {@inheritdoc}
  181. */
  182. public function deleteAll() {
  183. apcu_delete($this->getIterator('/^' . preg_quote($this->binPrefix, '/') . '/'));
  184. }
  185. /**
  186. * {@inheritdoc}
  187. */
  188. public function garbageCollection() {
  189. // APCu performs garbage collection automatically.
  190. }
  191. /**
  192. * {@inheritdoc}
  193. */
  194. public function removeBin() {
  195. apcu_delete($this->getIterator('/^' . preg_quote($this->binPrefix, '/') . '/'));
  196. }
  197. /**
  198. * {@inheritdoc}
  199. */
  200. public function invalidate($cid) {
  201. $this->invalidateMultiple([$cid]);
  202. }
  203. /**
  204. * {@inheritdoc}
  205. */
  206. public function invalidateMultiple(array $cids) {
  207. foreach ($this->getMultiple($cids) as $cache) {
  208. $this->set($cache->cid, $cache, REQUEST_TIME - 1);
  209. }
  210. }
  211. /**
  212. * {@inheritdoc}
  213. */
  214. public function invalidateAll() {
  215. foreach ($this->getAll() as $data) {
  216. $cid = str_replace($this->binPrefix, '', $data['key']);
  217. $this->set($cid, $data['value'], REQUEST_TIME - 1);
  218. }
  219. }
  220. /**
  221. * Instantiates and returns the APCUIterator class.
  222. *
  223. * @param mixed $search
  224. * A PCRE regular expression that matches against APC key names, either as a
  225. * string for a single regular expression, or as an array of regular
  226. * expressions. Or, optionally pass in NULL to skip the search.
  227. * @param int $format
  228. * The desired format, as configured with one or more of the APC_ITER_*
  229. * constants.
  230. * @param int $chunk_size
  231. * The chunk size. Must be a value greater than 0. The default value is 100.
  232. * @param int $list
  233. * The type to list. Either pass in APC_LIST_ACTIVE or APC_LIST_DELETED.
  234. *
  235. * @return \APCUIterator
  236. */
  237. protected function getIterator($search = NULL, $format = APC_ITER_ALL, $chunk_size = 100, $list = APC_LIST_ACTIVE) {
  238. return new \APCUIterator($search, $format, $chunk_size, $list);
  239. }
  240. }