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 CacheInterface[] */ |
17
|
|
|
private array $storages = []; |
18
|
|
|
|
19
|
19 |
|
public function __construct( |
20
|
|
|
private readonly CacheConfig $config, |
21
|
|
|
private readonly FactoryInterface $factory, |
22
|
|
|
private readonly ?EventDispatcherInterface $dispatcher = null, |
23
|
|
|
) { |
24
|
19 |
|
} |
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
|
18 |
|
private function resolve(?string $name): CacheInterface |
47
|
|
|
{ |
48
|
18 |
|
$config = $this->config->getStorageConfig($name); |
|
|
|
|
49
|
|
|
|
50
|
18 |
|
return $this->factory->make($config['type'], $config); |
51
|
|
|
} |
52
|
|
|
|
53
|
1 |
|
public function set(string $name, CacheInterface $cache): void |
54
|
|
|
{ |
55
|
1 |
|
$this->storages[$name] = $cache; |
56
|
|
|
} |
57
|
|
|
|
58
|
1 |
|
public function has(string $name): bool |
59
|
|
|
{ |
60
|
1 |
|
return \array_key_exists($name, $this->storages); |
61
|
|
|
} |
62
|
|
|
} |
63
|
|
|
|