-
-
Notifications
You must be signed in to change notification settings - Fork 166
Expand file tree
/
Copy pathUriGenerator.php
More file actions
231 lines (189 loc) · 7.61 KB
/
UriGenerator.php
File metadata and controls
231 lines (189 loc) · 7.61 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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
<?php
namespace Tempest\Router;
use BackedEnum;
use RuntimeException;
use Tempest\Container\Container;
use Tempest\Core\AppConfig;
use Tempest\Cryptography\Signing\Signature;
use Tempest\Cryptography\Signing\Signer;
use Tempest\DateTime\DateTime;
use Tempest\DateTime\Duration;
use Tempest\Http\Request;
use Tempest\Reflection\ClassReflector;
use Tempest\Reflection\MethodReflector;
use Tempest\Router\Exceptions\ControllerActionDoesNotExist;
use Tempest\Router\Exceptions\ControllerMethodHadNoRoute;
use Tempest\Router\Routing\Construction\DiscoveredRoute;
use Tempest\Support\Arr;
use Tempest\Support\Regex;
use Tempest\Support\Str;
use function Tempest\Support\str;
final class UriGenerator
{
public function __construct(
private AppConfig $appConfig,
private RouteConfig $routeConfig,
private Signer $signer,
private Container $container,
) {}
/**
* Checks if the request has a valid signature.
*/
public function hasValidSignature(Request $request): bool
{
$signature = $request->get('signature');
$expiresAt = $request->get('expires_at');
if ($signature === null) {
return false;
}
if ($expiresAt !== null && is_numeric($expiresAt) && DateTime::fromTimestamp((int) $expiresAt)->isPast()) {
return false;
}
return $this->signer->verify(
data: $this->createUri($request->path, ...Arr\remove_keys($request->query, 'signature')),
signature: Signature::from($signature),
);
}
/**
* Creates an absolute URI that is signed with a secret key and will expire after the specified duration.
*
* `$action` is one of :
* - Controller FQCN and its method as a tuple
* - Invokable controller FQCN
* - URI string starting with `/`
*
* @param MethodReflector|array{class-string,string}|class-string|string $action
*/
public function createTemporarySignedUri(array|string|MethodReflector $action, DateTime|Duration|int $duration, mixed ...$params): string
{
$uri = $this->normalizeActionToUri($action);
if (array_key_exists('expires_at', $params)) {
throw new RuntimeException('Cannot create a signed URI with an "expires_at" parameter. It will be added automatically.');
}
if (is_int($duration)) {
$duration = Duration::seconds($duration);
}
if ($duration instanceof Duration) {
$duration = DateTime::now()->plusMilliseconds((int) $duration->getTotalMilliseconds());
}
return $this->createSignedUri($uri, ...[
...$params,
'expires_at' => $duration->getTimestamp()->getSeconds(),
]);
}
/**
* Creates an absolute URI that is signed with a secret key, ensuring that it cannot be tampered with.
*
* `$action` is one of :
* - Controller FQCN and its method as a tuple
* - Invokable controller FQCN
* - URI string starting with `/`
*
* @param MethodReflector|array{class-string,string}|class-string|string $action
*/
public function createSignedUri(array|string|MethodReflector $action, mixed ...$params): string
{
$uri = $this->normalizeActionToUri($action);
if (array_key_exists('signature', $params)) {
throw new RuntimeException('Cannot create a signed URI with a "signature" parameter. It will be added automatically.');
}
$this->signer = $this->container->get(Signer::class);
ksort($params);
return $this->createUri($uri, ...[
...$params,
'signature' => $this->signer->sign($this->createUri($action, ...$params))->value,
]);
}
/**
* Creates an absolute URI to the given `$action`.
*
* `$action` is one of :
* - Controller FQCN and its method as a tuple
* - Invokable controller FQCN
* - URI string starting with `/`
*
* @param MethodReflector|array{class-string,string}|class-string|string $action
*/
public function createUri(array|string|MethodReflector $action, mixed ...$params): string
{
$uri = str($this->normalizeActionToUri($action));
$queryParams = [];
foreach ($params as $key => $value) {
if (! $uri->matches(sprintf('/\{%s(\}|:)/', $key))) {
$queryParams[$key] = $value;
continue;
}
if ($value instanceof BackedEnum) {
$value = $value->value;
} elseif ($value instanceof Bindable) {
foreach (new ClassReflector($value)->getPublicProperties() as $property) {
if (! $property->hasAttribute(IsBindingValue::class)) {
continue;
}
$value = $property->getValue($value);
break;
}
}
$uri = $uri->replaceRegex(
regex: '#\{' . $key . DiscoveredRoute::ROUTE_PARAM_CUSTOM_REGEX . '\}#',
replace: (string) $value,
);
}
$uri = $uri->prepend(rtrim($this->appConfig->baseUri, '/'));
if ($queryParams !== []) {
return $uri->append('?' . http_build_query($queryParams))->toString();
}
return $uri->toString();
}
/**
* Checks if the URI to the given `$action` would match the current route.
*
* `$action` is one of :
* - Controller FQCN and its method as a tuple
* - Invokable controller FQCN
* - URI string starting with `/`
*
* @param MethodReflector|array{class-string,string}|class-string|string $action
*/
public function isCurrentUri(array|string|MethodReflector $action, mixed ...$params): bool
{
$action = $this->normalizeActionToUri($action);
if (! $this->container->has(MatchedRoute::class)) {
return false;
}
$matchedRoute = $this->container->get(MatchedRoute::class);
$candidateUri = $this->createUri($action, ...[...$matchedRoute->params, ...$params]);
$currentUri = $this->createUri([$matchedRoute->route->handler->getDeclaringClass()->getName(), $matchedRoute->route->handler->getName()]);
foreach ($matchedRoute->params as $key => $value) {
if ($value instanceof BackedEnum) {
$value = $value->value;
}
$currentUri = Regex\replace($currentUri, '/({' . preg_quote($key, '/') . '(?::.*?)?})/', $value);
}
return $currentUri === $candidateUri;
}
private function normalizeActionToUri(array|string|MethodReflector $action): string
{
if ($action instanceof MethodReflector) {
$action = [
$action->getDeclaringClass()->getName(),
$action->getName(),
];
}
if (is_string($action) && str_starts_with($action, '/')) {
return $action;
}
[$controllerClass, $controllerMethod] = is_array($action) ? $action : [$action, '__invoke'];
$routes = array_unique($this->routeConfig->handlerIndex[$controllerClass . '::' . $controllerMethod] ?? []);
if ($routes === []) {
if (! class_exists($controllerClass)) {
throw ControllerActionDoesNotExist::controllerNotFound($controllerClass);
}
if (! method_exists($controllerClass, $controllerMethod)) {
throw ControllerActionDoesNotExist::actionNotFound($controllerClass, $controllerMethod);
}
throw new ControllerMethodHadNoRoute($controllerClass, $controllerMethod);
}
return Str\ensure_starts_with($routes[0], '/');
}
}