-
-
Notifications
You must be signed in to change notification settings - Fork 71
/
Typecast.php
113 lines (97 loc) · 3.38 KB
/
Typecast.php
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
<?php
declare(strict_types=1);
namespace Cycle\ORM\Parser;
use BackedEnum;
use Cycle\ORM\Exception\TypecastException;
use DateTimeImmutable;
use Cycle\Database\DatabaseInterface;
use ReflectionEnum;
use Throwable;
/**
* @internal
*/
final class Typecast implements CastableInterface
{
private const RULES = ['int', 'bool', 'float', 'datetime'];
/** @var array<non-empty-string, bool> */
private array $callableRules = [];
/** @var array<string, class-string<BackedEnum>> */
private array $enumClasses = [];
/** @var array<non-empty-string, callable|class-string<BackedEnum>|string> */
private array $rules = [];
public function __construct(
private DatabaseInterface $database
) {
}
public function setRules(array $rules): array
{
foreach ($rules as $key => $rule) {
if (\in_array($rule, self::RULES, true)) {
$this->rules[$key] = $rule;
unset($rules[$key]);
} elseif (\is_string($rule) && \is_subclass_of($rule, BackedEnum::class, true)) {
$reflection = new ReflectionEnum($rule);
$this->enumClasses[$key] = (string)$reflection->getBackingType();
$this->rules[$key] = $rule;
unset($rules[$key]);
} elseif (\is_callable($rule)) {
$this->callableRules[$key] = true;
$this->rules[$key] = $rule;
unset($rules[$key]);
}
}
return $rules;
}
public function cast(array $data): array
{
try {
foreach ($this->rules as $key => $rule) {
if (!isset($data[$key])) {
continue;
}
if (isset($this->callableRules[$key])) {
$data[$key] = $rule($data[$key], $this->database);
continue;
}
if (isset($this->enumClasses[$key])) {
/** @var class-string<BackedEnum> $rule */
$type = $this->enumClasses[$key];
$value = $data[$key];
$data[$key] = match (true) {
!\is_scalar($value) => null,
$type === 'string' && (\is_string($type) || \is_numeric($value))
=> $rule::tryFrom((string)$value),
$type === 'int' && (\is_int($value) || \preg_match('/^\\d++$/', $value) === 1)
=> $rule::tryFrom((int)$value),
default => null,
};
continue;
}
$data[$key] = $this->castPrimitive($rule, $data[$key]);
}
} catch (Throwable $e) {
throw new TypecastException(
\sprintf('Unable to typecast the `%s` field. %s', $key, $e->getMessage()),
$e->getCode(),
$e
);
}
return $data;
}
/**
* @throws \Exception
*/
private function castPrimitive(mixed $rule, mixed $value): mixed
{
return match ($rule) {
'int' => (int)$value,
'bool' => (bool)$value,
'float' => (float)$value,
'datetime' => new DateTimeImmutable(
$value,
$this->database->getDriver()->getTimezone()
),
default => $value,
};
}
}