Test Failed
Pull Request — master (#1095)
by Aleksei
10:19
created

InterceptorPipeline::withHandler()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 3
c 0
b 0
f 0
dl 0
loc 5
rs 10
cc 1
nc 1
nop 1
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 list<InterceptorInterface> */
0 ignored issues
show
Bug introduced by
The type Spiral\Interceptors\Handler\list was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
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