|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Tactics\CommandBusBundle\CommandBus; |
|
4
|
|
|
|
|
5
|
|
|
use Tactics\CommandBusBundle\Command\Command; |
|
6
|
|
|
use Tactics\CommandBusBundle\CommandHandler\CommandHandler; |
|
7
|
|
|
use Tactics\CommandBusBundle\Exception\DuplicateHandlerException; |
|
8
|
|
|
use Tactics\CommandBusBundle\NamingStrategy\NamingStrategy; |
|
9
|
|
|
|
|
10
|
|
|
/** |
|
11
|
|
|
* Class SimpleCommandBus |
|
12
|
|
|
* @package Tactics\CommandBusBundle\CommandBus |
|
13
|
|
|
*/ |
|
14
|
|
|
class SimpleCommandBus implements CommandBus |
|
15
|
|
|
{ |
|
16
|
|
|
/** |
|
17
|
|
|
* @var array |
|
18
|
|
|
*/ |
|
19
|
|
|
private $handlers = []; |
|
20
|
|
|
|
|
21
|
|
|
/** |
|
22
|
|
|
* @var \Tactics\CommandBusBundle\NamingStrategy\NamingStrategy |
|
23
|
|
|
*/ |
|
24
|
|
|
private $namingStrategy; |
|
25
|
|
|
|
|
26
|
|
|
/**e |
|
27
|
|
|
* @param NamingStrategy $namingStrategy |
|
28
|
|
|
*/ |
|
29
|
|
|
public function __construct(NamingStrategy $namingStrategy) |
|
30
|
|
|
{ |
|
31
|
|
|
$this->namingStrategy = $namingStrategy; |
|
32
|
|
|
} |
|
33
|
|
|
|
|
34
|
|
|
/** |
|
35
|
|
|
* @inheritDoc |
|
36
|
|
|
*/ |
|
37
|
|
|
public function registerHandler(CommandHandler $handler) |
|
38
|
|
|
{ |
|
39
|
|
|
$this->guardAgainstDuplicateHandlers($handler); |
|
40
|
|
|
$this->handlers[$this->namingStrategy->getCommandHandlerName($handler)] = $handler; |
|
41
|
|
|
} |
|
42
|
|
|
|
|
43
|
|
|
/** |
|
44
|
|
|
* @inheritDoc |
|
45
|
|
|
*/ |
|
46
|
|
|
public function getHandlers() |
|
47
|
|
|
{ |
|
48
|
|
|
return $this->handlers; |
|
49
|
|
|
} |
|
50
|
|
|
|
|
51
|
|
|
/** |
|
52
|
|
|
* @inheritDoc |
|
53
|
|
|
*/ |
|
54
|
|
|
public function handle(Command $command) |
|
55
|
|
|
{ |
|
56
|
|
|
$handler = $this->findHandler($this->namingStrategy->getCommandName($command)); |
|
57
|
|
|
|
|
58
|
|
|
if (! $handler) { |
|
59
|
|
|
return; |
|
60
|
|
|
} |
|
61
|
|
|
|
|
62
|
|
|
$handler->handle($command); |
|
63
|
|
|
} |
|
64
|
|
|
|
|
65
|
|
|
/** |
|
66
|
|
|
* @param CommandHandler $handler |
|
67
|
|
|
* @throws DuplicateHandlerException |
|
68
|
|
|
*/ |
|
69
|
|
|
private function guardAgainstDuplicateHandlers(CommandHandler $handler) |
|
70
|
|
|
{ |
|
71
|
|
|
if ($this->findHandler($this->namingStrategy->getCommandHandlerName($handler))) { |
|
72
|
|
|
throw new DuplicateHandlerException($handler); |
|
73
|
|
|
} |
|
74
|
|
|
} |
|
75
|
|
|
|
|
76
|
|
|
/** |
|
77
|
|
|
* @param string $needle |
|
78
|
|
|
* @return CommandHandler |
|
79
|
|
|
*/ |
|
80
|
|
|
private function findHandler($needle) |
|
81
|
|
|
{ |
|
82
|
|
|
return array_key_exists($needle, $this->handlers) |
|
83
|
|
|
? $this->handlers[$needle] |
|
84
|
|
|
: null; |
|
85
|
|
|
} |
|
86
|
|
|
} |