forked from patchlevel/hydrator
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDateIntervalNormalizer.php
More file actions
53 lines (40 loc) · 1.26 KB
/
Copy pathDateIntervalNormalizer.php
File metadata and controls
53 lines (40 loc) · 1.26 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
<?php
declare(strict_types=1);
namespace Patchlevel\Hydrator\Normalizer;
use Attribute;
use DateInterval;
use Throwable;
use function is_string;
#[Attribute(Attribute::TARGET_PROPERTY)]
final readonly class DateIntervalNormalizer implements Normalizer
{
private const DEFAULT_FORMAT = 'P%YY%MM%DDT%HH%IM%SS';
public function __construct(private string $format = self::DEFAULT_FORMAT)
{
}
public function normalize(mixed $value): string|null
{
if ($value === null) {
return null;
}
if (!$value instanceof DateInterval) {
throw InvalidArgument::withWrongType('DateInterval|null', $value);
}
return $value->format($this->format);
}
public function denormalize(mixed $value): DateInterval|null
{
if ($value === null) {
return null;
}
if (!is_string($value)) {
throw InvalidArgument::withWrongType('string|null', $value);
}
try {
$interval = new DateInterval($value);
} catch (Throwable $e) { // Exception in PHP <= 8.2 or DateMalformedIntervalStringException in 8.3+
throw new InvalidArgument('Invalid serialized date interval string', 0, $e);
}
return $interval;
}
}