CacheTrait.php 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373
  1. <?php
  2. /**
  3. * @package Grav\Framework\Cache
  4. *
  5. * @copyright Copyright (c) 2015 - 2022 Trilby Media, LLC. All rights reserved.
  6. * @license MIT License; see LICENSE file for details.
  7. */
  8. namespace Grav\Framework\Cache;
  9. use DateInterval;
  10. use DateTime;
  11. use Grav\Framework\Cache\Exception\InvalidArgumentException;
  12. use stdClass;
  13. use Traversable;
  14. use function array_key_exists;
  15. use function get_class;
  16. use function gettype;
  17. use function is_array;
  18. use function is_int;
  19. use function is_object;
  20. use function is_string;
  21. use function strlen;
  22. /**
  23. * Cache trait for PSR-16 compatible "Simple Cache" implementation
  24. * @package Grav\Framework\Cache
  25. */
  26. trait CacheTrait
  27. {
  28. /** @var string */
  29. private $namespace = '';
  30. /** @var int|null */
  31. private $defaultLifetime = null;
  32. /** @var stdClass */
  33. private $miss;
  34. /** @var bool */
  35. private $validation = true;
  36. /**
  37. * Always call from constructor.
  38. *
  39. * @param string $namespace
  40. * @param null|int|DateInterval $defaultLifetime
  41. * @return void
  42. * @throws InvalidArgumentException
  43. */
  44. protected function init($namespace = '', $defaultLifetime = null)
  45. {
  46. $this->namespace = (string) $namespace;
  47. $this->defaultLifetime = $this->convertTtl($defaultLifetime);
  48. $this->miss = new stdClass;
  49. }
  50. /**
  51. * @param bool $validation
  52. * @return void
  53. */
  54. public function setValidation($validation)
  55. {
  56. $this->validation = (bool) $validation;
  57. }
  58. /**
  59. * @return string
  60. */
  61. protected function getNamespace()
  62. {
  63. return $this->namespace;
  64. }
  65. /**
  66. * @return int|null
  67. */
  68. protected function getDefaultLifetime()
  69. {
  70. return $this->defaultLifetime;
  71. }
  72. /**
  73. * @param string $key
  74. * @param mixed|null $default
  75. * @return mixed|null
  76. * @throws InvalidArgumentException
  77. */
  78. public function get($key, $default = null)
  79. {
  80. $this->validateKey($key);
  81. $value = $this->doGet($key, $this->miss);
  82. return $value !== $this->miss ? $value : $default;
  83. }
  84. /**
  85. * @param string $key
  86. * @param mixed $value
  87. * @param null|int|DateInterval $ttl
  88. * @return bool
  89. * @throws InvalidArgumentException
  90. */
  91. public function set($key, $value, $ttl = null)
  92. {
  93. $this->validateKey($key);
  94. $ttl = $this->convertTtl($ttl);
  95. // If a negative or zero TTL is provided, the item MUST be deleted from the cache.
  96. return null !== $ttl && $ttl <= 0 ? $this->doDelete($key) : $this->doSet($key, $value, $ttl);
  97. }
  98. /**
  99. * @param string $key
  100. * @return bool
  101. * @throws InvalidArgumentException
  102. */
  103. public function delete($key)
  104. {
  105. $this->validateKey($key);
  106. return $this->doDelete($key);
  107. }
  108. /**
  109. * @return bool
  110. */
  111. public function clear()
  112. {
  113. return $this->doClear();
  114. }
  115. /**
  116. * @param iterable $keys
  117. * @param mixed|null $default
  118. * @return iterable
  119. * @throws InvalidArgumentException
  120. */
  121. public function getMultiple($keys, $default = null)
  122. {
  123. if ($keys instanceof Traversable) {
  124. $keys = iterator_to_array($keys, false);
  125. } elseif (!is_array($keys)) {
  126. $isObject = is_object($keys);
  127. throw new InvalidArgumentException(
  128. sprintf(
  129. 'Cache keys must be array or Traversable, "%s" given',
  130. $isObject ? get_class($keys) : gettype($keys)
  131. )
  132. );
  133. }
  134. if (empty($keys)) {
  135. return [];
  136. }
  137. $this->validateKeys($keys);
  138. $keys = array_unique($keys);
  139. $keys = array_combine($keys, $keys);
  140. $list = $this->doGetMultiple($keys, $this->miss);
  141. // Make sure that values are returned in the same order as the keys were given.
  142. $values = [];
  143. foreach ($keys as $key) {
  144. if (!array_key_exists($key, $list) || $list[$key] === $this->miss) {
  145. $values[$key] = $default;
  146. } else {
  147. $values[$key] = $list[$key];
  148. }
  149. }
  150. return $values;
  151. }
  152. /**
  153. * @param iterable $values
  154. * @param null|int|DateInterval $ttl
  155. * @return bool
  156. * @throws InvalidArgumentException
  157. */
  158. public function setMultiple($values, $ttl = null)
  159. {
  160. if ($values instanceof Traversable) {
  161. $values = iterator_to_array($values, true);
  162. } elseif (!is_array($values)) {
  163. $isObject = is_object($values);
  164. throw new InvalidArgumentException(
  165. sprintf(
  166. 'Cache values must be array or Traversable, "%s" given',
  167. $isObject ? get_class($values) : gettype($values)
  168. )
  169. );
  170. }
  171. $keys = array_keys($values);
  172. if (empty($keys)) {
  173. return true;
  174. }
  175. $this->validateKeys($keys);
  176. $ttl = $this->convertTtl($ttl);
  177. // If a negative or zero TTL is provided, the item MUST be deleted from the cache.
  178. return null !== $ttl && $ttl <= 0 ? $this->doDeleteMultiple($keys) : $this->doSetMultiple($values, $ttl);
  179. }
  180. /**
  181. * @param iterable $keys
  182. * @return bool
  183. * @throws InvalidArgumentException
  184. */
  185. public function deleteMultiple($keys)
  186. {
  187. if ($keys instanceof Traversable) {
  188. $keys = iterator_to_array($keys, false);
  189. } elseif (!is_array($keys)) {
  190. $isObject = is_object($keys);
  191. throw new InvalidArgumentException(
  192. sprintf(
  193. 'Cache keys must be array or Traversable, "%s" given',
  194. $isObject ? get_class($keys) : gettype($keys)
  195. )
  196. );
  197. }
  198. if (empty($keys)) {
  199. return true;
  200. }
  201. $this->validateKeys($keys);
  202. return $this->doDeleteMultiple($keys);
  203. }
  204. /**
  205. * @param string $key
  206. * @return bool
  207. * @throws InvalidArgumentException
  208. */
  209. public function has($key)
  210. {
  211. $this->validateKey($key);
  212. return $this->doHas($key);
  213. }
  214. /**
  215. * @param array $keys
  216. * @param mixed $miss
  217. * @return array
  218. */
  219. public function doGetMultiple($keys, $miss)
  220. {
  221. $results = [];
  222. foreach ($keys as $key) {
  223. $value = $this->doGet($key, $miss);
  224. if ($value !== $miss) {
  225. $results[$key] = $value;
  226. }
  227. }
  228. return $results;
  229. }
  230. /**
  231. * @param array $values
  232. * @param int|null $ttl
  233. * @return bool
  234. */
  235. public function doSetMultiple($values, $ttl)
  236. {
  237. $success = true;
  238. foreach ($values as $key => $value) {
  239. $success = $this->doSet($key, $value, $ttl) && $success;
  240. }
  241. return $success;
  242. }
  243. /**
  244. * @param array $keys
  245. * @return bool
  246. */
  247. public function doDeleteMultiple($keys)
  248. {
  249. $success = true;
  250. foreach ($keys as $key) {
  251. $success = $this->doDelete($key) && $success;
  252. }
  253. return $success;
  254. }
  255. /**
  256. * @param string|mixed $key
  257. * @return void
  258. * @throws InvalidArgumentException
  259. */
  260. protected function validateKey($key)
  261. {
  262. if (!is_string($key)) {
  263. throw new InvalidArgumentException(
  264. sprintf(
  265. 'Cache key must be string, "%s" given',
  266. is_object($key) ? get_class($key) : gettype($key)
  267. )
  268. );
  269. }
  270. if (!isset($key[0])) {
  271. throw new InvalidArgumentException('Cache key length must be greater than zero');
  272. }
  273. if (strlen($key) > 64) {
  274. throw new InvalidArgumentException(
  275. sprintf('Cache key length must be less than 65 characters, key had %d characters', strlen($key))
  276. );
  277. }
  278. if (strpbrk($key, '{}()/\@:') !== false) {
  279. throw new InvalidArgumentException(
  280. sprintf('Cache key "%s" contains reserved characters {}()/\@:', $key)
  281. );
  282. }
  283. }
  284. /**
  285. * @param array $keys
  286. * @return void
  287. * @throws InvalidArgumentException
  288. */
  289. protected function validateKeys($keys)
  290. {
  291. if (!$this->validation) {
  292. return;
  293. }
  294. foreach ($keys as $key) {
  295. $this->validateKey($key);
  296. }
  297. }
  298. /**
  299. * @param null|int|DateInterval $ttl
  300. * @return int|null
  301. * @throws InvalidArgumentException
  302. */
  303. protected function convertTtl($ttl)
  304. {
  305. if ($ttl === null) {
  306. return $this->getDefaultLifetime();
  307. }
  308. if (is_int($ttl)) {
  309. return $ttl;
  310. }
  311. if ($ttl instanceof DateInterval) {
  312. $date = DateTime::createFromFormat('U', '0');
  313. $ttl = $date ? (int)$date->add($ttl)->format('U') : 0;
  314. }
  315. throw new InvalidArgumentException(
  316. sprintf(
  317. 'Expiration date must be an integer, a DateInterval or null, "%s" given',
  318. is_object($ttl) ? get_class($ttl) : gettype($ttl)
  319. )
  320. );
  321. }
  322. }