1
|
|
|
<?php declare(strict_types=1); |
2
|
|
|
|
3
|
|
|
namespace WyriHaximus\React\Http\Middleware; |
4
|
|
|
|
5
|
|
|
use Psr\Http\Message\ServerRequestInterface; |
6
|
|
|
use React\Promise\PromiseInterface; |
7
|
|
|
use function React\Promise\resolve; |
8
|
|
|
|
9
|
|
|
final class MiddlewareRunner |
10
|
|
|
{ |
11
|
|
|
/** |
12
|
|
|
* @var MiddlewareRunner |
13
|
|
|
*/ |
14
|
|
|
private $middleware; |
15
|
|
|
|
16
|
|
|
/** |
17
|
|
|
* @param callable[] $middleware |
18
|
|
|
*/ |
19
|
3 |
|
public function __construct(callable ...$middleware) |
20
|
|
|
{ |
21
|
3 |
|
$this->middleware = $middleware; |
|
|
|
|
22
|
3 |
|
} |
23
|
|
|
|
24
|
3 |
|
public function __invoke(ServerRequestInterface $request, $next) |
25
|
|
|
{ |
26
|
3 |
|
$response = $this->call($request, 0, $next); |
27
|
|
|
|
28
|
3 |
|
if ($response instanceof PromiseInterface) { |
29
|
|
|
return $response; |
30
|
|
|
} |
31
|
|
|
|
32
|
3 |
|
return resolve($response); |
33
|
|
|
} |
34
|
|
|
|
35
|
3 |
|
private function call(ServerRequestInterface $request, $position, $last) |
36
|
|
|
{ |
37
|
3 |
|
if (!isset($this->middleware[$position])) { |
38
|
1 |
|
return $last($request); |
39
|
|
|
} |
40
|
|
|
|
41
|
|
|
// final request handler will be invoked without a next handler |
42
|
2 |
|
if (!isset($this->middleware[$position + 1])) { |
43
|
2 |
|
$handler = $this->middleware[$position]; |
44
|
|
|
|
45
|
2 |
|
return $handler($request, $last); |
46
|
|
|
} |
47
|
|
|
|
48
|
|
|
$next = function (ServerRequestInterface $request) use ($position, $last) { |
49
|
1 |
|
return $this->call($request, $position + 1, $last); |
50
|
1 |
|
}; |
51
|
|
|
|
52
|
|
|
// invoke middleware request handler with next handler |
53
|
1 |
|
$handler = $this->middleware[$position]; |
54
|
|
|
|
55
|
1 |
|
return $handler($request, $next); |
56
|
|
|
} |
57
|
|
|
} |
58
|
|
|
|
Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.
Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..