1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Conia\Chuck\Http; |
6
|
|
|
|
7
|
|
|
use Conia\Chuck\Factory; |
8
|
|
|
use Conia\Chuck\Middleware; |
9
|
|
|
use Conia\Chuck\Registry; |
10
|
|
|
use Conia\Chuck\Request; |
11
|
|
|
use Conia\Chuck\Response; |
12
|
|
|
use Psr\Http\Message\ResponseInterface as PsrResponse; |
13
|
|
|
use Psr\Http\Message\ServerRequestInterface as PsrServerRequest; |
14
|
|
|
use Psr\Http\Server\MiddlewareInterface as PsrMiddleware; |
15
|
|
|
use Psr\Http\Server\RequestHandlerInterface as PsrRequestHandler; |
16
|
|
|
|
17
|
|
|
class Dispatcher |
18
|
|
|
{ |
19
|
|
|
protected Factory $factory; |
20
|
|
|
|
21
|
24 |
|
public function __construct( |
22
|
|
|
protected readonly array $queue, |
23
|
|
|
Registry $registry |
24
|
|
|
) { |
25
|
24 |
|
$factory = $registry->get(Factory::class); |
26
|
24 |
|
assert($factory instanceof Factory); |
27
|
24 |
|
$this->factory = $factory; |
28
|
|
|
} |
29
|
|
|
|
30
|
|
|
/** |
31
|
|
|
* Recursively calls the callables in the middleware/view handler queue |
32
|
|
|
* and then the view callable. |
33
|
|
|
*/ |
34
|
24 |
|
public function handle(array $queue, Request $request): PsrResponse |
35
|
|
|
{ |
36
|
|
|
/** @psalm-var non-empty-list<Middleware|PsrMiddleware|ViewHandler> $queue */ |
37
|
24 |
|
$handler = $queue[0]; |
38
|
|
|
|
39
|
24 |
|
if ($handler instanceof Middleware) { |
40
|
9 |
|
return $handler( |
41
|
9 |
|
$request, |
42
|
9 |
|
function (Request $req) use ($queue): Response { |
43
|
9 |
|
return new Response($this->handle(array_slice($queue, 1), $req), $this->factory); |
44
|
9 |
|
} |
45
|
9 |
|
)->psr(); |
46
|
23 |
|
} elseif ($handler instanceof PsrMiddleware) { |
47
|
1 |
|
return $handler->process( |
48
|
1 |
|
$request->psr(), |
49
|
|
|
// Create an anonymous PSR-15 RequestHandler |
50
|
1 |
|
new class ($this, array_slice($queue, 1)) implements PsrRequestHandler { |
51
|
|
|
public function __construct( |
52
|
|
|
protected readonly Dispatcher $dispatcher, |
53
|
|
|
protected readonly array $queue |
54
|
|
|
) { |
55
|
1 |
|
} |
56
|
|
|
|
57
|
|
|
public function handle(PsrServerRequest $request): PsrResponse |
58
|
|
|
{ |
59
|
1 |
|
return $this->dispatcher->handle($this->queue, new Request($request)); |
60
|
|
|
} |
61
|
1 |
|
} |
62
|
1 |
|
); |
63
|
|
|
} |
64
|
|
|
|
65
|
23 |
|
return $handler(); |
66
|
|
|
} |
67
|
|
|
|
68
|
24 |
|
public function dispatch( |
69
|
|
|
Request $request, |
70
|
|
|
): PsrResponse { |
71
|
24 |
|
return $this->handle($this->queue, $request); |
72
|
|
|
} |
73
|
|
|
} |
74
|
|
|
|