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): void |
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): void |
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
|
|
|
|