| 1 |
<?php |
| 2 |
|
| 3 |
namespace React\Http\Io; |
| 4 |
|
| 5 |
use Psr\Http\Message\ResponseInterface; |
| 6 |
use Psr\Http\Message\ServerRequestInterface; |
| 7 |
use React\Promise\PromiseInterface; |
| 8 |
|
| 9 |
/** |
| 10 |
* [Internal] Middleware runner to expose an array of middleware request handlers as a single request handler callable |
| 11 |
* |
| 12 |
* @internal |
| 13 |
*/ |
| 14 |
final class MiddlewareRunner |
| 15 |
{ |
| 16 |
/** |
| 17 |
* @var callable[] |
| 18 |
*/ |
| 19 |
private $middleware; |
| 20 |
|
| 21 |
/** |
| 22 |
* @param callable[] $middleware |
| 23 |
*/ |
| 24 |
public function __construct(array $middleware) |
| 25 |
{ |
| 26 |
$this->middleware = \array_values($middleware); |
| 27 |
} |
| 28 |
|
| 29 |
/** |
| 30 |
* @param ServerRequestInterface $request |
| 31 |
* @return ResponseInterface|PromiseInterface<ResponseInterface> |
| 32 |
* @throws \Exception |
| 33 |
*/ |
| 34 |
public function __invoke(ServerRequestInterface $request) |
| 35 |
{ |
| 36 |
if (empty($this->middleware)) { |
| 37 |
throw new \RuntimeException('No middleware to run'); |
| 38 |
} |
| 39 |
|
| 40 |
return $this->call($request, 0); |
| 41 |
} |
| 42 |
|
| 43 |
/** @internal */ |
| 44 |
public function call(ServerRequestInterface $request, $position) |
| 45 |
{ |
| 46 |
// final request handler will be invoked without a next handler |
| 47 |
if (!isset($this->middleware[$position + 1])) { |
| 48 |
$handler = $this->middleware[$position]; |
| 49 |
return $handler($request); |
| 50 |
} |
| 51 |
|
| 52 |
$that = $this; |
| 53 |
$next = function (ServerRequestInterface $request) use ($that, $position) { |
| 54 |
return $that->call($request, $position + 1); |
| 55 |
}; |
| 56 |
|
| 57 |
// invoke middleware request handler with next handler |
| 58 |
$handler = $this->middleware[$position]; |
| 59 |
return $handler($request, $next); |
| 60 |
} |
| 61 |
} |