Passed
Pull Request — master (#1142)
by Alexander
11:10
created

CacheManager::set()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
eloc 1
dl 0
loc 3
ccs 2
cts 2
cp 1
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 2
crap 1
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);
0 ignored issues
show
Bug introduced by
It seems like $name can also be of type null; however, parameter $name of Spiral\Cache\Config\Cach...fig::getStorageConfig() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

48
        $config = $this->config->getStorageConfig(/** @scrutinizer ignore-type */ $name);
Loading history...
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