1 | <?php |
||
17 | abstract class AbstractBus implements BusInterface |
||
18 | { |
||
19 | // Message handlers |
||
20 | private $handlers; |
||
21 | |||
22 | private $logger; |
||
23 | |||
24 | /** |
||
25 | * @param LoggerInterface|null $logger |
||
26 | */ |
||
27 | 10 | public function __construct(?LoggerInterface $logger = null) |
|
31 | |||
32 | /** |
||
33 | * @param mixed $handler |
||
34 | */ |
||
35 | 4 | public function registerHandler($handler): AbstractBus |
|
44 | |||
45 | /** |
||
46 | * @param mixed $message |
||
47 | * |
||
48 | * @throws \Assert\AssertionFailedException |
||
49 | */ |
||
50 | 3 | public function post($message, ?callable $callback = null): void |
|
51 | { |
||
52 | // Expect the message to be an object to use reflection |
||
53 | // and match the handler method |
||
54 | 3 | Assertion::isObject($message); |
|
55 | |||
56 | 3 | $messageHandler = $this->findHandler($message); |
|
57 | |||
58 | 3 | $this->log( |
|
59 | 3 | sprintf( |
|
60 | 3 | 'Sending message [%s] to handler [%s::%s()]', |
|
61 | 3 | get_class($message), |
|
62 | 3 | get_class($messageHandler[0]), |
|
63 | 3 | $messageHandler[1] |
|
64 | ) |
||
65 | ); |
||
66 | |||
67 | // Run the command |
||
68 | 3 | $result = call_user_func($messageHandler, $message); |
|
69 | |||
70 | 3 | if ($callback) { |
|
71 | 2 | call_user_func($callback, $result); |
|
72 | } |
||
73 | 3 | } |
|
74 | |||
75 | /** |
||
76 | * @param string $msg |
||
77 | */ |
||
78 | 3 | private function log(string $msg): void |
|
86 | |||
87 | /** |
||
88 | * @return callable |
||
89 | * |
||
90 | * @throws \RuntimeException |
||
91 | */ |
||
92 | 3 | private function findHandler($message): callable |
|
107 | } |
||
108 |