PerCommandMiddleware   A
last analyzed

Complexity

Total Complexity 10

Size/Duplication

Total Lines 79
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Importance

Changes 0
Metric Value
wmc 10
lcom 1
cbo 1
dl 0
loc 79
rs 10
c 0
b 0
f 0

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A getBusForCommand() 0 24 5
A execute() 0 9 2
A getCommandMiddlewares() 0 4 1
A setCommandMiddlewares() 0 4 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
        /**
47
         * @var Middleware[]
48
         */
49
        $middlewares = [];
50
        foreach ($this->commandMiddlewares[$className] as $middleware) {
51
            if (is_array($middleware)) {
52
                $middlewares[] = $this->di->get(array_shift($middleware), $middleware);
53
            } elseif (is_string($middleware)) {
54
                $middlewares[] = $this->di->get($middleware);
55
            } else {
56
                throw new InvalidConfigException('Unsupported middleware config');
57
            }
58
        }
59
60
        return new CommandBus($middlewares);
61
    }
62
63
    /**
64
     * @param object $command
65
     * @param callable $next
66
     *
67
     * @return mixed
68
     */
69
    public function execute($command, callable $next)
70
    {
71
        $bus = $this->getBusForCommand($command);
72
        if ($bus === null) {
73
            return $next($command);
74
        }
75
76
        return $next($bus->handle($command));
77
    }
78
79
    /**
80
     * @return array
81
     */
82
    public function getCommandMiddlewares(): array
83
    {
84
        return $this->commandMiddlewares;
85
    }
86
87
    /**
88
     * @param array $commandMiddlewares
89
     */
90
    public function setCommandMiddlewares(array $commandMiddlewares): void
91
    {
92
        $this->commandMiddlewares = $commandMiddlewares;
93
    }
94
}
95