|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Thruster\Component\HttpRouter; |
|
4
|
|
|
|
|
5
|
|
|
use Psr\Http\Message\ResponseInterface; |
|
6
|
|
|
use Psr\Http\Message\ServerRequestInterface; |
|
7
|
|
|
use Thruster\Component\HttpRouter\Exception\RouteMethodNotAllowedException; |
|
8
|
|
|
use Thruster\Component\HttpRouter\Exception\RouteNotFoundException; |
|
9
|
|
|
use Thruster\Component\Promise\ExtendedPromiseInterface; |
|
10
|
|
|
use Thruster\Component\Promise\FulfilledPromise; |
|
11
|
|
|
|
|
12
|
|
|
/** |
|
13
|
|
|
* Class AsyncRouter |
|
14
|
|
|
* |
|
15
|
|
|
* @package Thruster\Component\HttpRouter |
|
16
|
|
|
* @author Aurimas Niekis <[email protected]> |
|
17
|
|
|
*/ |
|
18
|
|
|
class AsyncRouter extends Router |
|
19
|
|
|
{ |
|
20
|
|
|
/** |
|
21
|
|
|
* @var AsyncRouteHandlerInterface |
|
22
|
|
|
*/ |
|
23
|
|
|
protected $routeHandler; |
|
24
|
|
|
|
|
25
|
4 |
|
public function __construct( |
|
26
|
|
|
RouteProviderInterface $provider, |
|
27
|
|
|
AsyncRouteHandlerInterface $handler = null, |
|
28
|
|
|
array $options = [] |
|
29
|
|
|
) { |
|
30
|
4 |
|
parent::__construct($provider, null, $options); |
|
31
|
|
|
|
|
32
|
4 |
|
$this->routeHandler = $handler; |
|
33
|
4 |
|
} |
|
34
|
|
|
|
|
35
|
4 |
|
public function __invoke( |
|
36
|
|
|
ServerRequestInterface $request, |
|
37
|
|
|
ResponseInterface $response, |
|
38
|
|
|
callable $next = null |
|
39
|
|
|
) : ExtendedPromiseInterface { |
|
40
|
|
|
try { |
|
41
|
4 |
|
list($callback, $request) = $this->internalRequestHandle($request); |
|
42
|
|
|
|
|
43
|
2 |
|
$promise = $this->routeHandler->handleRoute($request, $response, $callback); |
|
44
|
2 |
|
} catch (RouteMethodNotAllowedException $e) { |
|
45
|
1 |
|
$promise = $this->routeHandler->handleRouteMethodNotAllowed($request, $response, $e->getAllowedMethods()); |
|
46
|
1 |
|
} catch (RouteNotFoundException $e) { |
|
47
|
1 |
|
$promise = $this->routeHandler->handleRouteNotFound($request, $response); |
|
48
|
|
|
} |
|
49
|
|
|
|
|
50
|
4 |
|
if (null !== $next) { |
|
51
|
1 |
|
return $promise->then(function (ResponseInterface $response) use ($request, $next) { |
|
52
|
1 |
|
$response = $next($request, $response); |
|
53
|
|
|
|
|
54
|
1 |
|
return new FulfilledPromise($response); |
|
55
|
1 |
|
}); |
|
56
|
|
|
} |
|
57
|
|
|
|
|
58
|
3 |
|
return $promise; |
|
59
|
|
|
} |
|
60
|
|
|
|
|
61
|
|
|
} |
|
62
|
|
|
|