CommandBus::__construct()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 8
Ratio 100 %

Importance

Changes 0
Metric Value
dl 8
loc 8
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 4
nc 2
nop 1
1
<?php
2
3
namespace NilPortugues\MessageBus\CommandBus;
4
5
use NilPortugues\Assert\Assert;
6
use NilPortugues\MessageBus\CommandBus\Contracts\Command;
7
use NilPortugues\MessageBus\CommandBus\Contracts\CommandBusMiddleware as CommandBusMiddlewareInterface;
8
9 View Code Duplication
class CommandBus implements CommandBusMiddlewareInterface
0 ignored issues
show
Duplication introduced by
This class seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
10
{
11
    /** @var callable[] */
12
    protected $middleware = [];
13
14
    /**
15
     * StackedCommandBus constructor.
16
     *
17
     * @param callable[] $middleware
18
     */
19
    public function __construct(array $middleware = [])
20
    {
21
        foreach ($middleware as $commandBusMiddleware) {
22
            Assert::isInstanceOf($commandBusMiddleware, CommandBusMiddlewareInterface::class);
23
        }
24
25
        $this->middleware = $middleware;
26
    }
27
28
    /**
29
     * @param Command       $command
30
     * @param callable|null $next
31
     */
32
    public function __invoke(Command $command, callable $next = null)
33
    {
34
        $middleware = $this->middleware;
35
        $current = array_shift($middleware);
36
37
        if (empty($middleware) && !empty($current)) {
38
            $current->__invoke($command);
0 ignored issues
show
Bug introduced by
The method __invoke cannot be called on $current (of type callable).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
39
40
            return;
41
        }
42
43
        foreach ($middleware as $commandBusMiddleware) {
44
            $callable = function ($command) use ($commandBusMiddleware) {
45
                return $commandBusMiddleware($command);
46
            };
47
48
            $current->__invoke($command, $callable);
49
            $current = $commandBusMiddleware;
50
        }
51
    }
52
}
53