Passed
Pull Request — master (#1095)
by Aleksei
12:04
created

InterceptorPipeline::handle()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 15
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 0
Metric Value
eloc 7
c 0
b 0
f 0
dl 0
loc 15
ccs 0
cts 8
cp 0
rs 10
cc 3
nc 3
nop 1
crap 12
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Spiral\Interceptors\Handler;
6
7
use Psr\EventDispatcher\EventDispatcherInterface;
8
use Spiral\Interceptors\Context\CallContext;
9
use Spiral\Interceptors\Event\InterceptorCalling;
10
use Spiral\Interceptors\Exception\InterceptorException;
11
use Spiral\Interceptors\HandlerInterface;
12
use Spiral\Interceptors\InterceptorInterface;
13
14
/**
15
 * Interceptor pipeline.
16
 *
17
 * WARNING: make sure you don't use any legacy interceptors because they aren't supported with this pipeline.
18
 */
19
final class InterceptorPipeline implements HandlerInterface
20
{
21
    private ?HandlerInterface $handler = null;
22
23
    /** @var InterceptorInterface */
24
    private array $interceptors = [];
25
26
    private int $position = 0;
27
28
    public function __construct(
29
        private readonly ?EventDispatcherInterface $dispatcher = null
30
    ) {
31
    }
32
33
    public function addInterceptor(InterceptorInterface $interceptor): void
34
    {
35
        $this->interceptors[] = $interceptor;
36
    }
37
38
    public function withHandler(HandlerInterface $handler): self
39
    {
40
        $pipeline = clone $this;
41
        $pipeline->handler = $handler;
42
        return $pipeline;
43
    }
44
45
    /**
46
     * @throws \Throwable
47
     */
48
    public function handle(CallContext $context): mixed
49
    {
50
        if ($this->handler === null) {
51
            throw new InterceptorException('Unable to invoke pipeline without last handler.');
52
        }
53
54
        if (isset($this->interceptors[$this->position])) {
55
            $interceptor = $this->interceptors[$this->position];
56
57
            $this->dispatcher?->dispatch(new InterceptorCalling(context: $context, interceptor: $interceptor));
58
59
            return $interceptor->intercept($context, $this->next());
60
        }
61
62
        return $this->handler->handle($context);
63
    }
64
65
    private function next(): self
66
    {
67
        $pipeline = clone $this;
68
        ++$pipeline->position;
69
        return $pipeline;
70
    }
71
}
72