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

Resolver   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 53
Duplicated Lines 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 17
c 2
b 0
f 0
dl 0
loc 53
rs 10
wmc 8

6 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
A new() 0 3 1
A inflectByAttribute() 0 3 1
A inflectByMethod() 0 3 1
A useCache() 0 5 1
A build() 0 9 3
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