Passed
Pull Request — master (#2)
by Victor
01:48
created

Pipeline::getNodeVisitors()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 3
ccs 2
cts 2
cp 1
rs 10
c 0
b 0
f 0
cc 1
eloc 1
nc 1
nop 0
crap 1
1
<?php
2
declare(strict_types=1);
3
4
namespace Shoot\Shoot;
5
6
use Psr\Http\Message\ServerRequestInterface;
7
8
final class Pipeline
9
{
10
    /** @var callable */
11
    private $middleware;
12
13
    /** @var ServerRequestInterface */
14
    private $request;
15
16
    /**
17
     * @param MiddlewareInterface[] $middleware
18
     */
19 13
    public function __construct(array $middleware = [])
20
    {
21 13
        $this->middleware = $this->chainMiddleware($middleware);
22 13
    }
23
24
    /**
25
     * During the execution of the callback, any middleware in the pipeline will have access to the given request
26
     * object.
27
     *
28
     * @param ServerRequestInterface $request  The current HTTP request being handled.
29
     * @param callable               $callback A callback which should call Twig to render the root template.
30
     *
31
     * @return mixed The result as returned by the callback (if any).
32
     */
33 10
    public function withRequest(ServerRequestInterface $request, callable $callback)
34
    {
35
        try {
36 10
            $this->request = $request;
37
38 10
            return $callback();
39
        } finally {
40 10
            $this->request = null;
41
        }
42
    }
43
44
    /**
45
     * @param View $view
46
     *
47
     * @return void
48
     */
49 10
    public function process(View $view)
50
    {
51 10
        if ($this->request === null) {
52 1
            throw new MissingRequestException('Cannot process a view without a request set. This method should be called from the callback passed to Pipeline::withRequest');
53
        }
54
55 9
        call_user_func($this->middleware, $view);
56 8
    }
57
58
    /**
59
     * Chains the middleware into a single callable.
60
     *
61
     * @param MiddlewareInterface[] $middleware
62
     *
63
     * @return callable
64
     */
65 13
    private function chainMiddleware(array $middleware): callable
66
    {
67 13
        $middleware = array_reverse($middleware);
68
69
        return array_reduce($middleware, function (callable $next, MiddlewareInterface $middleware) {
70 9
            return function (View $view) use ($middleware, $next): View {
71 8
                return $middleware->process($view, $this->request, $next);
72 9
            };
73
        }, function (View $view): View {
74
            try {
75 6
                $view->render();
76
77 4
                return $view;
78 2
            } catch (SuppressedException $exception) {
79 1
                return $view->withSuppressedException($exception->getPrevious());
80
            }
81 13
        });
82
    }
83
}
84