| 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(...$keyParts): string |
| 33 |
{ |
| 34 |
return implode('|', $keyParts); |
| 35 |
} |
| 36 |
|
| 37 |
public function add(string $key, mixed $value): void |
| 38 |
{ |
| 39 |
$this->cacheProvider?->add($key, $value); |
| 40 |
$this->cache[$key] = $value; |
| 41 |
} |
| 42 |
|
| 43 |
public function get(string $key): mixed |
| 44 |
{ |
| 45 |
if (isset($this->cache[$key]) === false) { |
| 46 |
$this->cache[$key] = $this->cacheProvider?->get($key); |
| 47 |
} |
| 48 |
|
| 49 |
return $this->cache[$key]; |
| 50 |
} |
| 51 |
|
| 52 |
public function invalidate(string $key): void |
| 53 |
{ |
| 54 |
$this->cacheProvider?->invalidate($key); |
| 55 |
unset($this->cache[$key]); |
| 56 |
} |
| 57 |
|
| 58 |
public function addToRuntimeCache(string $key, mixed $value): void |
| 59 |
{ |
| 60 |
$this->runtimeCache[$key] = $value; |
| 61 |
} |
| 62 |
|
| 63 |
public function getFromRuntimeCache(string $key): mixed |
| 64 |
{ |
| 65 |
return $this->runtimeCache[$key] ?? null; |
| 66 |
} |
| 67 |
|
| 68 |
public function flushCache(): void |
| 69 |
{ |
| 70 |
$this->cache = []; |
| 71 |
$this->runtimeCache = []; |
| 72 |
} |
| 73 |
|
| 74 |
/** |
| 75 |
* @return CacheProviderInterface[] |
| 76 |
*/ |
| 77 |
public function getRegisteredCacheProviders(): array |
| 78 |
{ |
| 79 |
$fileSystemCacheProvider = $this->cacheProviderFactory->createFileSystemCacheProvider(); |
| 80 |
$providers = [$fileSystemCacheProvider->getId() => $fileSystemCacheProvider]; |
| 81 |
|
| 82 |
if ($this->wordpress->isUsingExtObjectCache() === true) { |
| 83 |
$redisCacheProvider = $this->cacheProviderFactory->createRedisCacheProvider(); |
| 84 |
$providers[$redisCacheProvider->getId()] = $redisCacheProvider; |
| 85 |
} |
| 86 |
|
| 87 |
return $this->wordpress->applyFilters('uam_registered_cache_handlers', $providers); |
| 88 |
} |
| 89 |
} |
| 90 |
|