-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathEnumNormalizer.php
More file actions
88 lines (69 loc) · 2.07 KB
/
Copy pathEnumNormalizer.php
File metadata and controls
88 lines (69 loc) · 2.07 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
<?php
declare(strict_types=1);
namespace Patchlevel\Hydrator\Normalizer;
use Attribute;
use BackedEnum;
use Symfony\Component\TypeInfo\Type;
use Symfony\Component\TypeInfo\Type\BackedEnumType;
use Symfony\Component\TypeInfo\Type\NullableType;
use Throwable;
use function is_int;
use function is_string;
#[Attribute(Attribute::TARGET_PROPERTY | Attribute::TARGET_CLASS)]
final class EnumNormalizer implements Normalizer, TypeAwareNormalizer
{
/** @param class-string<BackedEnum>|null $enum */
public function __construct(
private string|null $enum = null,
) {
}
/** @param array<string, mixed> $context */
public function normalize(mixed $value, array $context): mixed
{
if ($value === null) {
return null;
}
$enum = $this->className();
if (!$value instanceof $enum) {
throw InvalidArgument::withWrongType($enum . '|null', $value);
}
return $value->value;
}
/** @param array<string, mixed> $context */
public function denormalize(mixed $value, array $context): BackedEnum|null
{
if ($value === null) {
return null;
}
if (!is_string($value) && !is_int($value)) {
throw InvalidArgument::withWrongType('string|int|null', $value);
}
$enum = $this->className();
try {
return $enum::from($value);
} catch (Throwable $error) {
throw InvalidArgument::fromThrowable($error);
}
}
public function handleType(Type|null $type): void
{
if ($this->enum !== null || $type === null) {
return;
}
if ($type instanceof NullableType) {
$type = $type->getWrappedType();
}
if (!$type instanceof BackedEnumType) {
return;
}
$this->enum = $type->getClassName();
}
/** @return class-string<BackedEnum> */
public function className(): string
{
if ($this->enum === null) {
throw InvalidType::missingType();
}
return $this->enum;
}
}