Passed
Push — main ( 150a56...b2f07c )
by Breno
01:38
created

Resolver::build()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 5
c 0
b 0
f 0
nc 2
nop 1
dl 0
loc 9
rs 10
1
<?php
2
declare(strict_types=1);
3
4
namespace OniBus\Handler\Builder;
5
6
use OniBus\Attributes\Handler;
7
use OniBus\Handler\ClassMethod\ClassMethodExtractor;
8
use OniBus\Handler\ClassMethod\Extractor\CachedExtractor;
9
use OniBus\Handler\ClassMethod\Extractor\ExtractorUsingAttribute;
10
use OniBus\Handler\ClassMethod\Extractor\MethodFirstParameterExtractor;
11
use OniBus\Handler\ClassMethod\Mapper\DirectMapper;
12
use OniBus\Handler\ClassMethodResolver;
13
use OniBus\Handler\HandlerResolver;
14
use Psr\Container\ContainerInterface;
15
use Psr\SimpleCache\CacheInterface;
16
17
final class Resolver
18
{
19
    /**
20
     * @var ContainerInterface
21
     */
22
    protected $container;
23
24
    /**
25
     * @var CacheInterface
26
     */
27
    private $cache;
28
29
    /**
30
     * @var string
31
     */
32
    private $cacheKey;
33
34
    public function __construct(ContainerInterface $container)
35
    {
36
        $this->container = $container;
37
    }
38
39
    public static function new(ContainerInterface $container): self
40
    {
41
        return new self($container);
42
    }
43
44
    public function useCache(CacheInterface $cache, string $cacheKey): self
45
    {
46
        $this->cache = $cache;
47
        $this->cacheKey = $cacheKey;
48
        return $this;
49
    }
50
51
    public function inflectByAttribute(array $handlersFQCN, string $attribute = Handler::class): HandlerResolver
52
    {
53
        return $this->build(new ExtractorUsingAttribute($attribute, $handlersFQCN));
54
    }
55
56
    public function inflectByMethod(array $handlersFQCN, string $method = "__invoke"): HandlerResolver
57
    {
58
        return $this->build(new MethodFirstParameterExtractor($method, $handlersFQCN));
59
    }
60
61
    private function build(ClassMethodExtractor $extractor): HandlerResolver
62
    {
63
        if ($this->cache instanceof CacheInterface && !empty($this->cacheKey)) {
64
            $extractor = new CachedExtractor($extractor, $this->cache, $this->cacheKey);
65
        }
66
67
        return new ClassMethodResolver(
68
            $this->container,
69
            new DirectMapper(...$extractor->extractClassMethods())
70
        );
71
    }
72
}
73