|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace Spiral\Cache; |
|
6
|
|
|
|
|
7
|
|
|
use Psr\EventDispatcher\EventDispatcherInterface; |
|
8
|
|
|
use Psr\SimpleCache\CacheInterface; |
|
9
|
|
|
use Spiral\Cache\Config\CacheConfig; |
|
10
|
|
|
use Spiral\Core\Attribute\Singleton; |
|
11
|
|
|
use Spiral\Core\FactoryInterface; |
|
12
|
|
|
|
|
13
|
|
|
#[Singleton] |
|
14
|
|
|
class CacheManager implements CacheStorageProviderInterface, CacheStorageRegistryInterface |
|
15
|
|
|
{ |
|
16
|
|
|
/** @var array<non-empty-string, CacheInterface> */ |
|
|
|
|
|
|
17
|
|
|
private array $storages = []; |
|
18
|
|
|
|
|
19
|
20 |
|
public function __construct( |
|
20
|
|
|
private readonly CacheConfig $config, |
|
21
|
|
|
private readonly FactoryInterface $factory, |
|
22
|
|
|
private readonly ?EventDispatcherInterface $dispatcher = null, |
|
23
|
|
|
) { |
|
24
|
20 |
|
} |
|
25
|
|
|
|
|
26
|
19 |
|
public function storage(?string $name = null): CacheInterface |
|
27
|
|
|
{ |
|
28
|
19 |
|
$name ??= $this->config->getDefaultStorage(); |
|
29
|
|
|
|
|
30
|
|
|
// Replaces alias with real storage name |
|
31
|
19 |
|
$storage = $this->config->getAliases()[$name] ?? $name; |
|
32
|
|
|
|
|
33
|
19 |
|
$prefix = null; |
|
34
|
19 |
|
if (\is_array($storage)) { |
|
35
|
5 |
|
$prefix = !empty($storage['prefix']) ? $storage['prefix'] : null; |
|
36
|
5 |
|
$storage = $storage['storage']; |
|
37
|
|
|
} |
|
38
|
|
|
|
|
39
|
19 |
|
if (!isset($this->storages[$storage])) { |
|
40
|
18 |
|
$this->storages[$storage] = $this->resolve($storage); |
|
41
|
|
|
} |
|
42
|
|
|
|
|
43
|
19 |
|
return new CacheRepository($this->storages[$storage], $this->dispatcher, $prefix); |
|
44
|
|
|
} |
|
45
|
|
|
|
|
46
|
2 |
|
public function register(string $name, CacheInterface $cache): void |
|
47
|
|
|
{ |
|
48
|
2 |
|
$this->storages[$name] = $cache; |
|
49
|
|
|
} |
|
50
|
|
|
|
|
51
|
2 |
|
public function getCacheStorages(): array |
|
52
|
|
|
{ |
|
53
|
2 |
|
return $this->storages; |
|
54
|
|
|
} |
|
55
|
|
|
|
|
56
|
18 |
|
private function resolve(?string $name): CacheInterface |
|
57
|
|
|
{ |
|
58
|
18 |
|
$config = $this->config->getStorageConfig($name); |
|
|
|
|
|
|
59
|
|
|
|
|
60
|
18 |
|
return $this->factory->make($config['type'], $config); |
|
61
|
|
|
} |
|
62
|
|
|
} |
|
63
|
|
|
|