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
wmc 9
eloc 20
c 1
b 0
f 0
dl 0
loc 57
rs 10

5 Methods

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