-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathViewModelError.php
More file actions
59 lines (52 loc) · 2.24 KB
/
ViewModelError.php
File metadata and controls
59 lines (52 loc) · 2.24 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
<?php
declare(strict_types=1);
namespace Toppy\TwigViewModel;
/**
* Template-facing error representation for ViewModel resolution failures.
*
* Provides structured error information with codes for template-level handling.
*/
// @mago-ignore analysis:mixed-assignment - Symfony HttpException::getHeaders() returns array<string, mixed>; vendor limitation
final class ViewModelError implements \JsonSerializable
{
public function __construct(
public readonly string $code,
public readonly string $message,
public readonly ?array $context = null,
) {}
/**
* Create error from an exception, mapping to appropriate error code.
*/
public static function fromException(\Throwable $e): self
{
$code = match (true) {
$e instanceof \Symfony\Component\HttpKernel\Exception\NotFoundHttpException => 'NOT_FOUND',
$e instanceof \Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException => 'FORBIDDEN',
$e instanceof \Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException => 'UNAUTHORIZED',
$e instanceof \Symfony\Component\HttpKernel\Exception\ServiceUnavailableHttpException
=> 'SERVICE_UNAVAILABLE',
$e instanceof \Symfony\Component\HttpKernel\Exception\TooManyRequestsHttpException => 'RATE_LIMITED',
$e instanceof \Symfony\Component\HttpClient\Exception\TimeoutException => 'TIMEOUT',
$e instanceof \Toppy\AsyncViewModel\Exception\ViewModelResolutionException => 'RESOLUTION_FAILED',
default => 'UNKNOWN',
};
$context = null;
if ($e instanceof \Symfony\Component\HttpKernel\Exception\TooManyRequestsHttpException) {
$headers = $e->getHeaders();
$retryAfter = $headers['Retry-After'] ?? null;
if (is_string($retryAfter) || is_int($retryAfter)) {
$context = ['retryAfter' => (int) $retryAfter];
}
}
return new self(code: $code, message: $e->getMessage(), context: $context);
}
#[\Override]
public function jsonSerialize(): array
{
return [
'code' => $this->code,
'message' => $this->message,
'context' => $this->context,
];
}
}