Failed Conditions
Push — master ( b8d841...bc596e )
by Florent
28:20
created

Pipe   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 62
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Importance

Changes 0
Metric Value
wmc 5
lcom 1
cbo 3
dl 0
loc 62
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A process() 0 12 1
A dispatch() 0 6 1
A resolve() 0 14 2
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * The MIT License (MIT)
7
 *
8
 * Copyright (c) 2014-2018 Spomky-Labs
9
 *
10
 * This software may be modified and distributed under the terms
11
 * of the MIT license.  See the LICENSE file for details.
12
 */
13
14
namespace OAuth2Framework\WebFingerBundle\Middleware;
15
16
use Psr\Http\Message\ResponseInterface;
17
use Psr\Http\Message\ServerRequestInterface;
18
use Psr\Http\Server\MiddlewareInterface;
19
use Psr\Http\Server\RequestHandlerInterface;
20
21
class Pipe implements MiddlewareInterface
22
{
23
    /**
24
     * @var MiddlewareInterface[]
25
     */
26
    private $middlewares;
27
28
    /**
29
     * Dispatcher constructor.
30
     *
31
     * @param MiddlewareInterface[] $middlewares
32
     */
33
    public function __construct(array $middlewares = [])
34
    {
35
        $this->middlewares = $middlewares;
36
    }
37
38
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
39
    {
40
        $this->middlewares[] = new RequestHandler(function (ServerRequestInterface $request) use ($handler) {
41
            return $handler->handle($request);
42
        });
43
44
        $response = $this->dispatch($request);
45
46
        \array_pop($this->middlewares);
47
48
        return $response;
49
    }
50
51
    /**
52
     * Dispatches the middleware and returns the resulting `ResponseInterface`.
53
     *
54
     * @throws \LogicException on unexpected result from any middleware on the middlewares
55
     *
56
     * @return ResponseInterface
57
     */
58
    public function dispatch(ServerRequestInterface $request)
59
    {
60
        $resolved = $this->resolve(0);
61
62
        return $resolved->handle($request);
63
    }
64
65
    /**
66
     * @param int $index Middleware index
67
     */
68
    private function resolve(int $index): RequestHandlerInterface
69
    {
70
        if (isset($this->middlewares[$index])) {
71
            $middleware = $this->middlewares[$index];
72
73
            return new RequestHandler(function (ServerRequestInterface $request) use ($middleware, $index) {
74
                return $middleware->process($request, $this->resolve($index + 1));
75
            });
76
        }
77
78
        return new RequestHandler(function () {
79
            throw new \LogicException('Unresolved request: middleware exhausted with no result.');
80
        });
81
    }
82
}
83