Resolver   A
last analyzed

Complexity

Total Complexity 9

Size/Duplication

Total Lines 57
Duplicated Lines 0 %

Importance

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

5 Methods

Rating   Name   Duplication   Size   Complexity  
A create() 0 3 1
A __construct() 0 3 1
A pushHandler() 0 5 1
A resolve() 0 19 5
A pushHandlerDeferred() 0 5 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace RemotelyLiving\PHPQueryBus;
6
7
use Psr\Container\ContainerInterface;
8
use RemotelyLiving\PHPQueryBus\Exceptions;
9
use RemotelyLiving\PHPQueryBus\Interfaces;
10
11
final class Resolver implements Interfaces\Resolver
12
{
13
    private ?ContainerInterface $container;
14
15
    /**
16
     * @var \RemotelyLiving\PHPQueryBus\Interfaces\Handler[]
17
     */
18
    private array $map = [];
19
20
    /**
21
     * @var callable[]
22
     */
23
    private array $deferred = [];
24
25
    public function __construct(ContainerInterface $container = null)
26
    {
27
        $this->container = $container;
28
    }
29
30
    public static function create(ContainerInterface $container = null): Interfaces\Resolver
31
    {
32
        return new static($container);
33
    }
34
35
    public function resolve(object $query): Interfaces\Handler
36
    {
37
        $queryClass = get_class($query);
38
39
        if ($this->container && $this->container->has($queryClass)) {
40
            return $this->container->get($queryClass);
41
        }
42
43
        if (isset($this->map[$queryClass])) {
44
            return $this->map[$queryClass];
45
        }
46
47
        if (isset($this->deferred[$queryClass])) {
48
            $this->map[$queryClass] = $this->deferred[$queryClass]();
49
            unset($this->deferred[$queryClass]);
50
            return $this->map[$queryClass];
51
        }
52
53
        throw new Exceptions\OutOfBounds("Query Handler for {$queryClass} not found");
54
    }
55
56
    public function pushHandler(string $queryClass, Interfaces\Handler $handler): Interfaces\Resolver
57
    {
58
        $this->map[$queryClass] = $handler;
59
60
        return $this;
61
    }
62
63
    public function pushHandlerDeferred(string $class, callable $handlerFn): Interfaces\Resolver
64
    {
65
        $this->deferred[$class] = $handlerFn;
66
67
        return $this;
68
    }
69
}
70