| 1 |
<?php |
| 2 |
|
| 3 |
/* |
| 4 |
* This file is part of Twig. |
| 5 |
* |
| 6 |
* (c) Fabien Potencier |
| 7 |
* |
| 8 |
* For the full copyright and license information, please view the LICENSE |
| 9 |
* file that was distributed with this source code. |
| 10 |
*/ |
| 11 |
namespace ElementorDeps\Twig\Cache; |
| 12 |
|
| 13 |
/** |
| 14 |
* Chains several caches together. |
| 15 |
* |
| 16 |
* Cached items are fetched from the first cache having them in its data store. |
| 17 |
* They are saved and deleted in all adapters at once. |
| 18 |
* |
| 19 |
* @author Quentin Devos <quentin@devos.pm> |
| 20 |
*/ |
| 21 |
final class ChainCache implements CacheInterface |
| 22 |
{ |
| 23 |
private $caches; |
| 24 |
/** |
| 25 |
* @param iterable<CacheInterface> $caches The ordered list of caches used to store and fetch cached items |
| 26 |
*/ |
| 27 |
public function __construct(iterable $caches) |
| 28 |
{ |
| 29 |
$this->caches = $caches; |
| 30 |
} |
| 31 |
public function generateKey(string $name, string $className) : string |
| 32 |
{ |
| 33 |
return $className . '#' . $name; |
| 34 |
} |
| 35 |
public function write(string $key, string $content) : void |
| 36 |
{ |
| 37 |
$splitKey = $this->splitKey($key); |
| 38 |
foreach ($this->caches as $cache) { |
| 39 |
$cache->write($cache->generateKey(...$splitKey), $content); |
| 40 |
} |
| 41 |
} |
| 42 |
public function load(string $key) : void |
| 43 |
{ |
| 44 |
[$name, $className] = $this->splitKey($key); |
| 45 |
foreach ($this->caches as $cache) { |
| 46 |
$cache->load($cache->generateKey($name, $className)); |
| 47 |
if (\class_exists($className, \false)) { |
| 48 |
break; |
| 49 |
} |
| 50 |
} |
| 51 |
} |
| 52 |
public function getTimestamp(string $key) : int |
| 53 |
{ |
| 54 |
$splitKey = $this->splitKey($key); |
| 55 |
foreach ($this->caches as $cache) { |
| 56 |
if (0 < ($timestamp = $cache->getTimestamp($cache->generateKey(...$splitKey)))) { |
| 57 |
return $timestamp; |
| 58 |
} |
| 59 |
} |
| 60 |
return 0; |
| 61 |
} |
| 62 |
/** |
| 63 |
* @return string[] |
| 64 |
*/ |
| 65 |
private function splitKey(string $key) : array |
| 66 |
{ |
| 67 |
return \array_reverse(\explode('#', $key, 2)); |
| 68 |
} |
| 69 |
} |
| 70 |
|