| 1 |
<?php |
| 2 |
|
| 3 |
declare(strict_types=1); |
| 4 |
|
| 5 |
namespace UserAccessManager\Cache; |
| 6 |
|
| 7 |
use UserAccessManager\Wrapper\Wordpress; |
| 8 |
|
| 9 |
class Cache |
| 10 |
{ |
| 11 |
private ?CacheProviderInterface $cacheProvider = null; |
| 12 |
private array $cache = []; |
| 13 |
private array $runtimeCache = []; |
| 14 |
|
| 15 |
public function __construct( |
| 16 |
private Wordpress $wordpress, |
| 17 |
private CacheProviderFactory $cacheProviderFactory |
| 18 |
) { |
| 19 |
} |
| 20 |
|
| 21 |
public function getCacheProvider(): ?CacheProviderInterface |
| 22 |
{ |
| 23 |
return $this->cacheProvider; |
| 24 |
} |
| 25 |
|
| 26 |
public function setActiveCacheProvider(?string $key): void |
| 27 |
{ |
| 28 |
$this->cacheProvider = $this->getRegisteredCacheProviders()[$key] ?? null; |
| 29 |
$this->cacheProvider?->init(); |
| 30 |
} |
| 31 |
|
| 32 |
public function generateCacheKey(): string |
| 33 |
{ |
| 34 |
$arguments = func_get_args(); |
| 35 |
|
| 36 |
return implode('|', $arguments); |
| 37 |
} |
| 38 |
|
| 39 |
public function add(string $key, mixed $value): void |
| 40 |
{ |
| 41 |
$this->cacheProvider?->add($key, $value); |
| 42 |
$this->cache[$key] = $value; |
| 43 |
} |
| 44 |
|
| 45 |
public function get(string $key): mixed |
| 46 |
{ |
| 47 |
if (isset($this->cache[$key]) === false) { |
| 48 |
$this->cache[$key] = ($this->cacheProvider !== null) ? $this->cacheProvider->get($key) : null; |
| 49 |
} |
| 50 |
|
| 51 |
return $this->cache[$key]; |
| 52 |
} |
| 53 |
|
| 54 |
public function invalidate(string $key): void |
| 55 |
{ |
| 56 |
$this->cacheProvider?->invalidate($key); |
| 57 |
unset($this->cache[$key]); |
| 58 |
} |
| 59 |
|
| 60 |
public function addToRuntimeCache(string $key, mixed $value): void |
| 61 |
{ |
| 62 |
$this->runtimeCache[$key] = $value; |
| 63 |
} |
| 64 |
|
| 65 |
public function getFromRuntimeCache(string $key): mixed |
| 66 |
{ |
| 67 |
if (isset($this->runtimeCache[$key]) === true) { |
| 68 |
return $this->runtimeCache[$key]; |
| 69 |
} |
| 70 |
|
| 71 |
return null; |
| 72 |
} |
| 73 |
|
| 74 |
|
| 75 |
public function flushCache(): void |
| 76 |
{ |
| 77 |
$this->cache = []; |
| 78 |
$this->runtimeCache = []; |
| 79 |
} |
| 80 |
|
| 81 |
/** |
| 82 |
* @return CacheProviderInterface[] |
| 83 |
*/ |
| 84 |
public function getRegisteredCacheProviders(): array |
| 85 |
{ |
| 86 |
$fileSystemCacheProvider = $this->cacheProviderFactory->createFileSystemCacheProvider(); |
| 87 |
|
| 88 |
return $this->wordpress->applyFilters( |
| 89 |
'uam_registered_cache_handlers', |
| 90 |
[$fileSystemCacheProvider->getId() => $fileSystemCacheProvider] |
| 91 |
); |
| 92 |
} |
| 93 |
} |
| 94 |
|