forked from prooph/service-bus
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathCommandBus.php
74 lines (61 loc) · 2.16 KB
/
CommandBus.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
<?php
/*
* This file is part of the prooph/service-bus.
* (c) 2014 - 2015 prooph software GmbH <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* Date: 09/14/14 - 16:32
*/
namespace Prooph\ServiceBus;
use Prooph\ServiceBus\Exception\RuntimeException;
/**
* Class CommandBus
*
* A command bus is capable of dispatching a message to a command handler.
* Only one handler per message is allowed!
*
* @package Prooph\ServiceBus
* @author Alexander Miertsch <[email protected]>
*/
class CommandBus extends MessageBus
{
/**
* @param mixed $command
* @return void
* @throws Exception\MessageDispatchException
*/
public function dispatch($command)
{
$actionEvent = $this->getActionEventEmitter()->getNewActionEvent();
$actionEvent->setTarget($this);
try {
$this->initialize($command, $actionEvent);
if ($actionEvent->getParam(self::EVENT_PARAM_MESSAGE_HANDLER) === null) {
$actionEvent->setName(self::EVENT_ROUTE);
$this->trigger($actionEvent);
}
if ($actionEvent->getParam(self::EVENT_PARAM_MESSAGE_HANDLER) === null) {
throw new RuntimeException(sprintf(
"CommandBus was not able to identify a CommandHandler for command %s",
$this->getMessageType($command)
));
}
if (is_string($actionEvent->getParam(self::EVENT_PARAM_MESSAGE_HANDLER))) {
$actionEvent->setName(self::EVENT_LOCATE_HANDLER);
$this->trigger($actionEvent);
}
$commandHandler = $actionEvent->getParam(self::EVENT_PARAM_MESSAGE_HANDLER);
if (is_callable($commandHandler)) {
$commandHandler($command);
} else {
$actionEvent->setName(self::EVENT_INVOKE_HANDLER);
$this->trigger($actionEvent);
}
$this->triggerFinalize($actionEvent);
} catch (\Exception $ex) {
$this->handleException($actionEvent, $ex);
}
}
}