Passed
Pull Request — master (#600)
by Aleksei
08:16 queued 03:02
created

CacheInjector::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
c 1
b 0
f 0
nc 1
nop 1
dl 0
loc 3
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Spiral\Cache\Core;
6
7
use ReflectionClass;
8
use Spiral\Core\Container\InjectorInterface;
9
use Spiral\Core\Exception\Container\ContainerException;
10
use Spiral\Cache\Exception\InvalidArgumentException;
11
use Spiral\Cache\CacheStorageProviderInterface;
12
use Psr\SimpleCache\CacheInterface;
13
14
/**
15
 * @implements InjectorInterface<CacheInterface>
16
 */
17
final class CacheInjector implements InjectorInterface
18
{
19
    private CacheStorageProviderInterface $provider;
20
21
    public function __construct(CacheStorageProviderInterface $provider)
22
    {
23
        $this->provider = $provider;
24
    }
25
26
    public function createInjection(ReflectionClass $class, string $context = null): CacheInterface
27
    {
28
        try {
29
            if ($context === null) {
30
                $connection = $this->provider->storage();
31
            } else {
32
                // Get Cache by context
33
                try {
34
                    $connection = $this->provider->storage($context);
35
                } catch (InvalidArgumentException $e) {
36
                    // Case when context doesn't match to configured connections
37
                    return $this->provider->storage();
38
                }
39
            }
40
41
            $this->matchType($class, $context, $connection);
42
        } catch (\Throwable $e) {
43
            throw new ContainerException(sprintf("Can't inject the required cache. %s", $e->getMessage()), 0, $e);
44
        }
45
46
        return $connection;
47
    }
48
49
    /**
50
     * Check the resolved connection implements required type
51
     *
52
     * @throws \RuntimeException
53
     */
54
    private function matchType(ReflectionClass $class, ?string $context, CacheInterface $connection): void
55
    {
56
        $className = $class->getName();
57
        if ($className !== CacheInterface::class && !$connection instanceof $className) {
58
            throw new \RuntimeException(
59
                \sprintf(
60
                    "The cache obtained by the context `%s` doesn't match the type `%s`.",
61
                    $context ?? 'NULL',
62
                    $className
63
                )
64
            );
65
        }
66
    }
67
}
68