Passed
Push — master ( 9013bb...125cf1 )
by Kirill
03:56
created

Pipeline::process()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 1
c 1
b 0
f 0
dl 0
loc 3
rs 10
cc 1
nc 1
nop 2
1
<?php
2
3
/**
4
 * Spiral Framework.
5
 *
6
 * @license   MIT
7
 * @author    Anton Titov (Wolfy-J)
8
 */
9
10
declare(strict_types=1);
11
12
namespace Spiral\Http;
13
14
use Psr\Http\Message\ResponseInterface as Response;
15
use Psr\Http\Message\ServerRequestInterface as Request;
16
use Psr\Http\Server\MiddlewareInterface;
17
use Psr\Http\Server\RequestHandlerInterface;
18
use Spiral\Core\ScopeInterface;
19
use Spiral\Http\Exception\PipelineException;
20
use Spiral\Http\Traits\MiddlewareTrait;
21
22
/**
23
 * Pipeline used to pass request and response thought the chain of middleware.
24
 */
25
final class Pipeline implements RequestHandlerInterface, MiddlewareInterface
26
{
27
    use MiddlewareTrait;
28
29
    /** @var ScopeInterface */
30
    private $scope;
31
32
    /** @var int */
33
    private $position = 0;
34
35
    /** @var RequestHandlerInterface */
36
    private $handler;
37
38
    /**
39
     * @param ScopeInterface $scope
40
     */
41
    public function __construct(ScopeInterface $scope)
42
    {
43
        $this->scope = $scope;
44
    }
45
46
    /**
47
     * Configures pipeline with target endpoint.
48
     *
49
     * @param RequestHandlerInterface $handler
50
     * @return Pipeline
51
     *
52
     * @throws PipelineException
53
     */
54
    public function withHandler(RequestHandlerInterface $handler): self
55
    {
56
        $pipeline = clone $this;
57
        $pipeline->handler = $handler;
58
        $pipeline->position = 0;
59
60
        return $pipeline;
61
    }
62
63
    /**
64
     * @inheritdoc
65
     */
66
    public function process(Request $request, RequestHandlerInterface $handler): Response
67
    {
68
        return $this->withHandler($handler)->handle($request);
69
    }
70
71
    /**
72
     * @inheritdoc
73
     */
74
    public function handle(Request $request): Response
75
    {
76
        if (empty($this->handler)) {
77
            throw new PipelineException('Unable to run pipeline, no handler given.');
78
        }
79
80
        $position = $this->position++;
81
        if (isset($this->middleware[$position])) {
82
            return $this->middleware[$position]->process($request, $this);
83
        }
84
85
        return $this->scope->runScope([Request::class => $request], function () use ($request) {
86
            return $this->handler->handle($request);
87
        });
88
    }
89
}
90