QueryBus::pushMiddleware()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 9
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 4
c 1
b 0
f 0
nc 1
nop 1
dl 0
loc 9
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace RemotelyLiving\PHPQueryBus;
6
7
use RemotelyLiving\PHPQueryBus\Interfaces;
8
9
final class QueryBus implements Interfaces\QueryBus
10
{
11
    private Interfaces\Resolver $resolver;
12
13
    /**
14
     * @var callable
15
     */
16
    private $callStack;
17
18
    public function __construct(Interfaces\Resolver $resolver)
19
    {
20
        $this->resolver = $resolver;
21
        $this->callStack = $this->seedCallStack();
22
    }
23
24
    public static function create(Interfaces\Resolver $resolver): self
25
    {
26
        return new static($resolver);
27
    }
28
29
    public function pushMiddleware(callable $middleware): Interfaces\QueryBus
30
    {
31
        $next = $this->callStack;
32
33
        $this->callStack = function (object $query) use ($middleware, $next): Interfaces\Result {
34
            return $middleware($query, $next);
35
        };
36
37
        return $this;
38
    }
39
40
    public function handle(object $query): Interfaces\Result
41
    {
42
        return ($this->callStack)($query);
43
    }
44
45
    private function seedCallStack(): callable
46
    {
47
        return function (object $query): Interfaces\Result {
48
            return $this->resolver->resolve($query)->handle($query, $this);
49
        };
50
    }
51
}
52