Completed
Push — master ( 932cc5...b796f0 )
by Andrii
12:16
created

PerCommandMiddleware::setCommandMiddlewares()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
c 0
b 0
f 0
rs 10
cc 1
eloc 2
nc 1
nop 1
1
<?php
2
3
4
namespace hiapi\middlewares;
5
6
use League\Tactician\CommandBus;
7
use League\Tactician\Middleware;
8
use yii\base\InvalidConfigException;
9
use yii\di\Container;
10
11
/**
12
 * Class PerCommandMiddleware
13
 *
14
 * @author Dmytro Naumenko <[email protected]>
15
 */
16
class PerCommandMiddleware implements Middleware
17
{
18
    /**
19
     * @var array
20
     */
21
    public $commandMiddlewares; // TODO: make private after switching to yiisoft/di
22
    /**
23
     * @var Container
24
     */
25
    private $di;
26
27
    public function __construct(Container $di)
28
    {
29
        $this->di = $di;
30
    }
31
32
    /**
33
     * @param $command
34
     * @return CommandBus|null
35
     * @throws InvalidConfigException
36
     * @throws \yii\di\NotInstantiableException
37
     */
38
    private function getBusForCommand($command): ?CommandBus
39
    {
40
        $className = get_class($command);
41
42
        if (!isset($this->commandMiddlewares[$className])) {
43
            return null;
44
        }
45
46
        $middlewares = [];
47
        foreach ($this->commandMiddlewares[$className] as $middleware) {
48
            if (is_array($middleware)) {
49
                $middlewares[] = $this->di->get(array_shift($middleware), $middleware);
50
            } elseif (is_string($middleware)) {
51
                $middlewares[] = $this->di->get($middleware);
52
            } else {
53
                throw new InvalidConfigException('Unsupported middleware config');
54
            }
55
        }
56
57
        return new CommandBus($middlewares);
58
    }
59
60
    /**
61
     * @param object $command
62
     * @param callable $next
63
     *
64
     * @return mixed
65
     */
66
    public function execute($command, callable $next)
67
    {
68
        $bus = $this->getBusForCommand($command);
69
        if ($bus === null) {
70
            return $next($command);
71
        }
72
73
        return $next($bus->handle($command));
74
    }
75
76
    /**
77
     * @return array
78
     */
79
    public function getCommandMiddlewares(): array
80
    {
81
        return $this->commandMiddlewares;
82
    }
83
84
    /**
85
     * @param array $commandMiddlewares
86
     */
87
    public function setCommandMiddlewares(array $commandMiddlewares): void
88
    {
89
        $this->commandMiddlewares = $commandMiddlewares;
90
    }
91
}
92