InMemoryLocator   A
last analyzed

Complexity

Total Complexity 6

Size/Duplication

Total Lines 60
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 6
lcom 1
cbo 1
dl 0
loc 60
ccs 14
cts 14
cp 1
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A addHandler() 0 4 1
A getHandlerForCommand() 0 8 2
A addHandlers() 0 6 2
1
<?php
2
3
namespace League\Tactician\Handler\Locator;
4
5
use League\Tactician\Exception\MissingHandlerException;
6
7
/**
8
 * Fetch handler instances from an in-memory collection.
9
 *
10
 * This locator allows you to bind a handler object to receive commands of a
11
 * certain class name. For example:
12
 *
13
 *      // Wire everything together
14
 *      $myHandler = new TaskAddedHandler($dependency1, $dependency2);
15
 *      $inMemoryLocator->addHandler($myHandler, 'My\TaskAddedCommand');
16
 *
17
 *      // Returns $myHandler
18
 *      $inMemoryLocator->getHandlerForCommand('My\TaskAddedCommand');
19
 */
20
class InMemoryLocator implements HandlerLocator
21
{
22
    /**
23
     * @var object[]
24
     */
25
    protected $handlers = [];
26
27
    /**
28
     * @param array $commandClassToHandlerMap
29
     */
30 5
    public function __construct(array $commandClassToHandlerMap = [])
31
    {
32 5
        $this->addHandlers($commandClassToHandlerMap);
33 5
    }
34
35
    /**
36
     * Bind a handler instance to receive all commands with a certain class
37
     *
38
     * @param object $handler Handler to receive class
39
     * @param string $commandClassName Command class e.g. "My\TaskAddedCommand"
40
     */
41 3
    public function addHandler($handler, $commandClassName)
42
    {
43 3
        $this->handlers[$commandClassName] = $handler;
44 3
    }
45
46
    /**
47
     * Allows you to add multiple handlers at once.
48
     *
49
     * The map should be an array in the format of:
50
     *  [
51
     *      AddTaskCommand::class      => $someHandlerInstance,
52
     *      CompleteTaskCommand::class => $someHandlerInstance,
53
     *  ]
54
     *
55
     * @param array $commandClassToHandlerMap
56
     */
57 5
    protected function addHandlers(array $commandClassToHandlerMap)
58
    {
59 5
        foreach ($commandClassToHandlerMap as $commandClass => $handler) {
60 2
            $this->addHandler($handler, $commandClass);
61
        }
62 5
    }
63
64
    /**
65
     * Returns the handler bound to the command's class name.
66
     *
67
     * @param string $commandName
68
     *
69
     * @return object
70
     */
71 4
    public function getHandlerForCommand($commandName)
72
    {
73 4
        if (!isset($this->handlers[$commandName])) {
74 1
            throw MissingHandlerException::forCommand($commandName);
75
        }
76
77 3
        return $this->handlers[$commandName];
78
    }
79
}
80