Passed
Pull Request — master (#405)
by Kirill
08:21 queued 04:03
created

Factory::decorateByAnnotations()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 3
c 1
b 0
f 0
nc 2
nop 1
dl 0
loc 7
rs 10
1
<?php
2
3
/**
4
 * This file is part of Spiral Framework package.
5
 *
6
 * For the full copyright and license information, please view the LICENSE
7
 * file that was distributed with this source code.
8
 */
9
10
declare(strict_types=1);
11
12
namespace Spiral\Attributes;
13
14
use Doctrine\Common\Annotations\AnnotationReader as DoctrineAnnotationReader;
15
use Doctrine\Common\Annotations\Reader as DoctrineReaderInterface;
16
use Psr\Cache\CacheItemPoolInterface;
17
use Psr\SimpleCache\CacheInterface;
18
use Spiral\Attributes\Composite\SelectiveReader;
19
20
class Factory implements FactoryInterface
21
{
22
    /**
23
     * @var CacheInterface|CacheItemPoolInterface|null
24
     */
25
    private $cache;
26
27
    /**
28
     * @param CacheInterface|CacheItemPoolInterface|null $cache
29
     * @return $this
30
     */
31
    public function withCache($cache): self
32
    {
33
        assert($cache instanceof CacheItemPoolInterface || $cache instanceof CacheInterface || $cache === null);
34
35
        $self = clone $this;
36
        $self->cache = $cache;
37
38
        return $self;
39
    }
40
41
    /**
42
     * {@inheritDoc}
43
     */
44
    public function create(): ReaderInterface
45
    {
46
        return $this->decorateByCache(
47
            $this->decorateByAnnotations(
48
                new AttributeReader()
49
            )
50
        );
51
    }
52
53
    /**
54
     * @param ReaderInterface $reader
55
     * @return ReaderInterface
56
     */
57
    private function decorateByAnnotations(ReaderInterface $reader): ReaderInterface
58
    {
59
        if (\interface_exists(DoctrineReaderInterface::class)) {
60
            $reader = new SelectiveReader([$reader, new DoctrineAnnotationReader()]);
61
        }
62
63
        return $reader;
64
    }
65
66
    /**
67
     * @param ReaderInterface $reader
68
     * @return ReaderInterface
69
     */
70
    private function decorateByCache(ReaderInterface $reader): ReaderInterface
71
    {
72
        switch (true) {
73
            case $this->cache instanceof CacheInterface:
74
                return new Psr16CachedReader($reader, $this->cache);
75
76
            case $this->cache instanceof CacheItemPoolInterface:
77
                return new Psr6CachedReader($reader, $this->cache);
78
79
            default:
80
                return $reader;
81
        }
82
    }
83
}
84