forked from patchlevel/hydrator
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDateTimeImmutableNormalizer.php
More file actions
51 lines (38 loc) · 1.11 KB
/
Copy pathDateTimeImmutableNormalizer.php
File metadata and controls
51 lines (38 loc) · 1.11 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
<?php
declare(strict_types=1);
namespace Patchlevel\Hydrator\Normalizer;
use Attribute;
use DateTimeImmutable;
use function is_string;
#[Attribute(Attribute::TARGET_PROPERTY)]
final readonly class DateTimeImmutableNormalizer implements Normalizer
{
public function __construct(
private string $format = DateTimeImmutable::ATOM,
) {
}
public function normalize(mixed $value): string|null
{
if ($value === null) {
return null;
}
if (!$value instanceof DateTimeImmutable) {
throw InvalidArgument::withWrongType('DateTimeImmutable|null', $value);
}
return $value->format($this->format);
}
public function denormalize(mixed $value): DateTimeImmutable|null
{
if ($value === null) {
return null;
}
if (!is_string($value)) {
throw InvalidArgument::withWrongType('string|null', $value);
}
$date = DateTimeImmutable::createFromFormat($this->format, $value);
if ($date === false) {
throw new InvalidArgument();
}
return $date;
}
}