-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathYii2TacticianCommandBus.php
77 lines (59 loc) · 2.56 KB
/
Yii2TacticianCommandBus.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
<?php
declare(strict_types=1);
namespace AstrotechLabs\Yii2Tactician;
use Yii;
use InvalidArgumentException;
use RuntimeException;
use AstrotechLabs\Yii2Tactician\MethodName\Handle;
use AstrotechLabs\Yii2Tactician\ClassName\Suffix;
use yii\base\Component;
use League\Tactician\CommandBus;
use League\Tactician\Plugins\LockingMiddleware;
final class Yii2TacticianCommandBus extends Component
{
private CommandBus $commandBus;
public function init()
{
parent::init();
$handlerMiddleware = new CommandHandlerMiddleware(
Yii::$container,
new MapByNamingConvention(new Suffix('Handler'), new Handle())
);
$lockingMiddleware = new LockingMiddleware();
$this->commandBus = new CommandBus([$lockingMiddleware, $handlerMiddleware]);
}
/**
* @param string|object $command Command class object or string path
* @param array $parameters (Optional) Parameters to be used when string path is provided
* @return false|mixed
* @throws \yii\base\InvalidConfigException
* @throws \yii\di\NotInstantiableException
*/
public function handle($command, array $parameters = [])
{
if (is_string($command)) {
if (empty($parameters)) {
throw new InvalidArgumentException("You must provide parameters when command is a string path.");
}
/** @var \AstrotechLabs\Yii2Tactician\Handler $handleObject */
$handleObject = Yii::$container->get($command);
if (!($handleObject instanceof Handler)) {
throw new RuntimeException("Handler class '" . get_class($handleObject) . "' must implements '" . Handler::class . "' interface.");
}
if (!method_exists($handleObject, 'handle')) {
throw new RuntimeException("Handler class '" . get_class($handleObject) . "' must be a handle method.");
}
$commandClass = $handleObject->commandClassName();
if (!class_exists($commandClass)) {
throw new RuntimeException("Command class '{$commandClass}' doesn't exists.");
}
/** @var Command $command */
$command = $commandClass::create($parameters);
if (!($command instanceof Command)) {
throw new RuntimeException("Command class must implements '" . Command::class . "' interface.");
}
return call_user_func_array([$handleObject, 'handle'], [$command]);
}
return call_user_func_array([$this->commandBus, 'handle'], [$command]);
}
}