CacheAdapter.php 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  1. <?php
  2. namespace Doctrine\Common\Cache\Psr6;
  3. use Doctrine\Common\Cache\Cache;
  4. use Doctrine\Common\Cache\ClearableCache;
  5. use Doctrine\Common\Cache\MultiDeleteCache;
  6. use Doctrine\Common\Cache\MultiGetCache;
  7. use Doctrine\Common\Cache\MultiPutCache;
  8. use Psr\Cache\CacheItemInterface;
  9. use Psr\Cache\CacheItemPoolInterface;
  10. use Symfony\Component\Cache\DoctrineProvider as SymfonyDoctrineProvider;
  11. use function array_key_exists;
  12. use function assert;
  13. use function count;
  14. use function current;
  15. use function get_class;
  16. use function gettype;
  17. use function is_object;
  18. use function is_string;
  19. use function microtime;
  20. use function sprintf;
  21. use function strpbrk;
  22. use const PHP_VERSION_ID;
  23. final class CacheAdapter implements CacheItemPoolInterface
  24. {
  25. private const RESERVED_CHARACTERS = '{}()/\@:';
  26. /** @var Cache */
  27. private $cache;
  28. /** @var array<CacheItem|TypedCacheItem> */
  29. private $deferredItems = [];
  30. public static function wrap(Cache $cache): CacheItemPoolInterface
  31. {
  32. if ($cache instanceof DoctrineProvider && ! $cache->getNamespace()) {
  33. return $cache->getPool();
  34. }
  35. if ($cache instanceof SymfonyDoctrineProvider && ! $cache->getNamespace()) {
  36. $getPool = function () {
  37. // phpcs:ignore Squiz.Scope.StaticThisUsage.Found
  38. return $this->pool;
  39. };
  40. return $getPool->bindTo($cache, SymfonyDoctrineProvider::class)();
  41. }
  42. return new self($cache);
  43. }
  44. private function __construct(Cache $cache)
  45. {
  46. $this->cache = $cache;
  47. }
  48. /** @internal */
  49. public function getCache(): Cache
  50. {
  51. return $this->cache;
  52. }
  53. /**
  54. * {@inheritDoc}
  55. */
  56. public function getItem($key): CacheItemInterface
  57. {
  58. assert(self::validKey($key));
  59. if (isset($this->deferredItems[$key])) {
  60. $this->commit();
  61. }
  62. $value = $this->cache->fetch($key);
  63. if (PHP_VERSION_ID >= 80000) {
  64. if ($value !== false) {
  65. return new TypedCacheItem($key, $value, true);
  66. }
  67. return new TypedCacheItem($key, null, false);
  68. }
  69. if ($value !== false) {
  70. return new CacheItem($key, $value, true);
  71. }
  72. return new CacheItem($key, null, false);
  73. }
  74. /**
  75. * {@inheritDoc}
  76. */
  77. public function getItems(array $keys = []): array
  78. {
  79. if ($this->deferredItems) {
  80. $this->commit();
  81. }
  82. assert(self::validKeys($keys));
  83. $values = $this->doFetchMultiple($keys);
  84. $items = [];
  85. if (PHP_VERSION_ID >= 80000) {
  86. foreach ($keys as $key) {
  87. if (array_key_exists($key, $values)) {
  88. $items[$key] = new TypedCacheItem($key, $values[$key], true);
  89. } else {
  90. $items[$key] = new TypedCacheItem($key, null, false);
  91. }
  92. }
  93. return $items;
  94. }
  95. foreach ($keys as $key) {
  96. if (array_key_exists($key, $values)) {
  97. $items[$key] = new CacheItem($key, $values[$key], true);
  98. } else {
  99. $items[$key] = new CacheItem($key, null, false);
  100. }
  101. }
  102. return $items;
  103. }
  104. /**
  105. * {@inheritDoc}
  106. */
  107. public function hasItem($key): bool
  108. {
  109. assert(self::validKey($key));
  110. if (isset($this->deferredItems[$key])) {
  111. $this->commit();
  112. }
  113. return $this->cache->contains($key);
  114. }
  115. public function clear(): bool
  116. {
  117. $this->deferredItems = [];
  118. if (! $this->cache instanceof ClearableCache) {
  119. return false;
  120. }
  121. return $this->cache->deleteAll();
  122. }
  123. /**
  124. * {@inheritDoc}
  125. */
  126. public function deleteItem($key): bool
  127. {
  128. assert(self::validKey($key));
  129. unset($this->deferredItems[$key]);
  130. return $this->cache->delete($key);
  131. }
  132. /**
  133. * {@inheritDoc}
  134. */
  135. public function deleteItems(array $keys): bool
  136. {
  137. foreach ($keys as $key) {
  138. assert(self::validKey($key));
  139. unset($this->deferredItems[$key]);
  140. }
  141. return $this->doDeleteMultiple($keys);
  142. }
  143. public function save(CacheItemInterface $item): bool
  144. {
  145. return $this->saveDeferred($item) && $this->commit();
  146. }
  147. public function saveDeferred(CacheItemInterface $item): bool
  148. {
  149. if (! $item instanceof CacheItem && ! $item instanceof TypedCacheItem) {
  150. return false;
  151. }
  152. $this->deferredItems[$item->getKey()] = $item;
  153. return true;
  154. }
  155. public function commit(): bool
  156. {
  157. if (! $this->deferredItems) {
  158. return true;
  159. }
  160. $now = microtime(true);
  161. $itemsCount = 0;
  162. $byLifetime = [];
  163. $expiredKeys = [];
  164. foreach ($this->deferredItems as $key => $item) {
  165. $lifetime = ($item->getExpiry() ?? $now) - $now;
  166. if ($lifetime < 0) {
  167. $expiredKeys[] = $key;
  168. continue;
  169. }
  170. ++$itemsCount;
  171. $byLifetime[(int) $lifetime][$key] = $item->get();
  172. }
  173. $this->deferredItems = [];
  174. switch (count($expiredKeys)) {
  175. case 0:
  176. break;
  177. case 1:
  178. $this->cache->delete(current($expiredKeys));
  179. break;
  180. default:
  181. $this->doDeleteMultiple($expiredKeys);
  182. break;
  183. }
  184. if ($itemsCount === 1) {
  185. return $this->cache->save($key, $item->get(), (int) $lifetime);
  186. }
  187. $success = true;
  188. foreach ($byLifetime as $lifetime => $values) {
  189. $success = $this->doSaveMultiple($values, $lifetime) && $success;
  190. }
  191. return $success;
  192. }
  193. public function __destruct()
  194. {
  195. $this->commit();
  196. }
  197. /**
  198. * @param mixed $key
  199. */
  200. private static function validKey($key): bool
  201. {
  202. if (! is_string($key)) {
  203. throw new InvalidArgument(sprintf('Cache key must be string, "%s" given.', is_object($key) ? get_class($key) : gettype($key)));
  204. }
  205. if ($key === '') {
  206. throw new InvalidArgument('Cache key length must be greater than zero.');
  207. }
  208. if (strpbrk($key, self::RESERVED_CHARACTERS) !== false) {
  209. throw new InvalidArgument(sprintf('Cache key "%s" contains reserved characters "%s".', $key, self::RESERVED_CHARACTERS));
  210. }
  211. return true;
  212. }
  213. /**
  214. * @param mixed[] $keys
  215. */
  216. private static function validKeys(array $keys): bool
  217. {
  218. foreach ($keys as $key) {
  219. self::validKey($key);
  220. }
  221. return true;
  222. }
  223. /**
  224. * @param mixed[] $keys
  225. */
  226. private function doDeleteMultiple(array $keys): bool
  227. {
  228. if ($this->cache instanceof MultiDeleteCache) {
  229. return $this->cache->deleteMultiple($keys);
  230. }
  231. $success = true;
  232. foreach ($keys as $key) {
  233. $success = $this->cache->delete($key) && $success;
  234. }
  235. return $success;
  236. }
  237. /**
  238. * @param mixed[] $keys
  239. *
  240. * @return mixed[]
  241. */
  242. private function doFetchMultiple(array $keys): array
  243. {
  244. if ($this->cache instanceof MultiGetCache) {
  245. return $this->cache->fetchMultiple($keys);
  246. }
  247. $values = [];
  248. foreach ($keys as $key) {
  249. $value = $this->cache->fetch($key);
  250. if (! $value) {
  251. continue;
  252. }
  253. $values[$key] = $value;
  254. }
  255. return $values;
  256. }
  257. /**
  258. * @param mixed[] $keysAndValues
  259. */
  260. private function doSaveMultiple(array $keysAndValues, int $lifetime = 0): bool
  261. {
  262. if ($this->cache instanceof MultiPutCache) {
  263. return $this->cache->saveMultiple($keysAndValues, $lifetime);
  264. }
  265. $success = true;
  266. foreach ($keysAndValues as $key => $value) {
  267. $success = $this->cache->save($key, $value, $lifetime) && $success;
  268. }
  269. return $success;
  270. }
  271. }