-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRouter.php
More file actions
78 lines (72 loc) · 2.06 KB
/
Copy pathRouter.php
File metadata and controls
78 lines (72 loc) · 2.06 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
<?php
declare(strict_types = 1);
namespace Innmind\Framework\Http;
use Innmind\Http\{
ServerRequest,
Response,
};
use Innmind\Router\{
Component,
Router as Route,
Any,
Handle,
Respond,
Exception\NotFound,
Exception\NoRouteProvided,
};
use Innmind\Immutable\{
Maybe,
Sequence,
Attempt,
SideEffect,
};
/**
* @internal
*/
final class Router
{
/**
* @param \Closure(Component<SideEffect, Response>): Component<SideEffect, Response> $mapRoutes
* @param Sequence<Component<SideEffect, Response>> $routes
* @param Maybe<\Closure(ServerRequest): Attempt<Response>> $notFound
* @param \Closure(ServerRequest, \Throwable): Attempt<Response> $recover
*/
public function __construct(
private \Closure $mapRoutes,
private Sequence $routes,
private Maybe $notFound,
private \Closure $recover,
) {
}
/**
* @return Attempt<Response>
*/
public function __invoke(ServerRequest $request): Attempt
{
$recover = $this->recover;
$notFound = $this->notFound;
/**
* @psalm-suppress MixedArgumentTypeCoercion
*/
$route = Route::of(
($this->mapRoutes)(Any::from($this->routes))
->mapError(static fn($e) => match (true) {
$e instanceof NoRouteProvided => new NotFound,
default => $e,
})
->otherwise(static fn(\Throwable $e) => Component::of(
static fn($request) => $notFound
->filter(static fn() => $e instanceof NotFound)
->match(
static fn($handle) => $handle($request),
static fn() => Attempt::error($e),
),
))
->otherwise(Respond::withHttpErrors())
->otherwise(static fn($e) => Handle::via(
static fn($request) => $recover($request, $e),
)),
);
return $route($request);
}
}