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