|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
/** |
|
4
|
|
|
* (c) 2018 Douglas Reith. |
|
5
|
|
|
* |
|
6
|
|
|
* For the full copyright and license information, please view the LICENSE |
|
7
|
|
|
* file that was distributed with this source code. |
|
8
|
|
|
*/ |
|
9
|
|
|
declare(strict_types=1); |
|
10
|
|
|
|
|
11
|
|
|
namespace Reith\ToyRobot\Infrastructure\Bus; |
|
12
|
|
|
|
|
13
|
|
|
use Assert\Assertion; |
|
14
|
|
|
use Reith\ToyRobot\Messaging\BusInterface; |
|
15
|
|
|
|
|
16
|
|
|
abstract class AbstractBus implements BusInterface |
|
17
|
|
|
{ |
|
18
|
|
|
// Message handlers |
|
19
|
|
|
private $handlers; |
|
20
|
|
|
|
|
21
|
|
|
/** |
|
22
|
|
|
* @param mixed $handler |
|
23
|
|
|
*/ |
|
24
|
|
|
public function registerHandler($handler): AbstractBus |
|
25
|
|
|
{ |
|
26
|
|
|
// Expect the handler to be an object |
|
27
|
|
|
Assertion::isObject($handler); |
|
28
|
|
|
|
|
29
|
|
|
$this->handlers[] = new HandlerWrapper($handler); |
|
30
|
|
|
|
|
31
|
|
|
return $this; |
|
32
|
|
|
} |
|
33
|
|
|
|
|
34
|
|
|
/** |
|
35
|
|
|
* @param mixed $message |
|
36
|
|
|
* @throws \Assert\AssertionFailedException |
|
37
|
|
|
*/ |
|
38
|
|
|
public function post($message): void |
|
39
|
|
|
{ |
|
40
|
|
|
// Expect the message to be an object to use reflection |
|
41
|
|
|
// and match the handler method |
|
42
|
|
|
Assertion::isObject($message); |
|
43
|
|
|
|
|
44
|
|
|
$messageHandler = $this->findHandler($message); |
|
45
|
|
|
|
|
46
|
|
|
// Run the command |
|
47
|
|
|
call_user_func($messageHandler, $message); |
|
48
|
|
|
} |
|
49
|
|
|
|
|
50
|
|
|
/** |
|
51
|
|
|
* @return callable |
|
52
|
|
|
* @throws \RuntimeException |
|
53
|
|
|
*/ |
|
54
|
|
|
private function findHandler($message): callable |
|
55
|
|
|
{ |
|
56
|
|
|
// In this implementation the first handler wins but |
|
57
|
|
|
// actually we would want to fail if there is more than |
|
58
|
|
|
// one for Commands and Queries |
|
59
|
|
|
foreach ($this->handlers as $handler) { |
|
60
|
|
|
if ($callable = $handler->getCallable($message)) { |
|
61
|
|
|
return $callable; |
|
62
|
|
|
} |
|
63
|
|
|
} |
|
64
|
|
|
|
|
65
|
|
|
throw new \RuntimeException( |
|
66
|
|
|
sprintf('No handler was found for message [%s]', get_class($message)) |
|
67
|
|
|
); |
|
68
|
|
|
} |
|
69
|
|
|
} |
|
70
|
|
|
|