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\Service; |
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
|
|
|
* @param MiddlewareInterface[] $middlewares |
30
|
|
|
*/ |
31
|
|
|
public function __construct(array $middlewares = []) |
32
|
|
|
{ |
33
|
|
|
$this->middlewares = $middlewares; |
34
|
|
|
} |
35
|
|
|
|
36
|
|
|
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface |
37
|
|
|
{ |
38
|
|
|
$this->middlewares[] = new RequestHandler(function (ServerRequestInterface $request) use ($handler) { |
39
|
|
|
return $handler->handle($request); |
40
|
|
|
}); |
41
|
|
|
|
42
|
|
|
$response = $this->dispatch($request); |
43
|
|
|
|
44
|
|
|
\array_pop($this->middlewares); |
45
|
|
|
|
46
|
|
|
return $response; |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
/** |
50
|
|
|
* Dispatches the middleware and returns the resulting `ResponseInterface`. |
51
|
|
|
* |
52
|
|
|
* @throws \LogicException on unexpected result from any middleware on the middlewares |
53
|
|
|
*/ |
54
|
|
|
public function dispatch(ServerRequestInterface $request): ResponseInterface |
55
|
|
|
{ |
56
|
|
|
$resolved = $this->resolve(0); |
57
|
|
|
|
58
|
|
|
return $resolved->handle($request); |
59
|
|
|
} |
60
|
|
|
|
61
|
|
|
private function resolve(int $index): RequestHandlerInterface |
62
|
|
|
{ |
63
|
|
|
if (isset($this->middlewares[$index])) { |
64
|
|
|
$middleware = $this->middlewares[$index]; |
65
|
|
|
|
66
|
|
|
return new RequestHandler(function (ServerRequestInterface $request) use ($middleware, $index) { |
67
|
|
|
return $middleware->process($request, $this->resolve($index + 1)); |
68
|
|
|
}); |
69
|
|
|
} |
70
|
|
|
|
71
|
|
|
return new RequestHandler(function () { |
72
|
|
|
throw new \LogicException('Unresolved request: middleware exhausted with no result.'); |
73
|
|
|
}); |
74
|
|
|
} |
75
|
|
|
} |
76
|
|
|
|