Passed
Push — main ( 12f243...150a56 )
by Breno
01:53
created

Resolver   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 58
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 22
c 1
b 0
f 0
dl 0
loc 58
rs 10
wmc 9

5 Methods

Rating   Name   Duplication   Size   Complexity  
A inflectByAttribute() 0 10 3
A inflectByMethod() 0 10 3
A useCache() 0 5 1
A __construct() 0 3 1
A new() 0 3 1
1
<?php
2
declare(strict_types=1);
3
4
namespace OniBus\Handler\Builder;
5
6
use Habemus\Container;
7
use OniBus\Attributes\Handler;
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
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 inflectByAttribute(array $handlersFQCN, string $attribute = Handler::class): HandlerResolver
45
    {
46
        $extractor = new ExtractorUsingAttribute($attribute, $handlersFQCN);
47
        if ($this->cache instanceof CacheInterface && !empty($this->cacheKey)) {
48
            $extractor = new CachedExtractor($extractor, $this->cache, $this->cacheKey);
49
        }
50
51
        return new ClassMethodResolver(
52
            new Container(),
53
            new DirectMapper(...$extractor->extractClassMethods())
54
        );
55
    }
56
57
    public function inflectByMethod(array $handlersFQCN, string $method = "__invoke"): HandlerResolver
58
    {
59
        $extractor = new MethodFirstParameterExtractor($method, $handlersFQCN);
60
        if ($this->cache instanceof CacheInterface && !empty($this->cacheKey)) {
61
            $extractor = new CachedExtractor($extractor, $this->cache, $this->cacheKey);
62
        }
63
64
        return new ClassMethodResolver(
65
            new Container(),
66
            new DirectMapper(...$extractor->extractClassMethods())
67
        );
68
    }
69
70
    public function useCache(CacheInterface $cache, string $cacheKey): self
71
    {
72
        $this->cache = $cache;
73
        $this->cacheKey = $cacheKey;
74
        return $this;
75
    }
76
}
77