-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAbsoluteDateNormalizer.php
More file actions
87 lines (75 loc) · 2.46 KB
/
AbsoluteDateNormalizer.php
File metadata and controls
87 lines (75 loc) · 2.46 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
<?php
declare(strict_types=1);
namespace AssoConnect\PHPDateBundle\Normalizer;
use AssoConnect\PHPDate\AbsoluteDate;
use Symfony\Component\Serializer\Exception\InvalidArgumentException;
use Symfony\Component\Serializer\Exception\NotNormalizableValueException;
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
/**
* Normalizes an instance of {@see AbsoluteDate} to a date string.
* Denormalizes a date string to an instance of {@see AbsoluteDate}.
*/
class AbsoluteDateNormalizer implements NormalizerInterface, DenormalizerInterface
{
public const FORMAT_KEY = 'datetime_format';
/**
* {@inheritdoc}
*
* @param mixed[] $context
* @throws InvalidArgumentException
*/
public function normalize(mixed $data, ?string $format = null, array $context = []): string
{
if (!$data instanceof AbsoluteDate) {
throw new InvalidArgumentException(sprintf(
'The object must be an instance of "%s".',
AbsoluteDate::class
));
}
$dateTimeFormat = $context[self::FORMAT_KEY] ?? AbsoluteDate::DEFAULT_DATE_FORMAT;
return $data->format($dateTimeFormat);
}
/**
* {@inheritdoc}
* @param mixed[] $context
*/
public function supportsNormalization(mixed $data, ?string $format = null, array $context = []): bool
{
return $data instanceof AbsoluteDate;
}
/**
* {@inheritdoc}
*
* @param mixed[] $context
* @throws NotNormalizableValueException
*/
public function denormalize($data, string $type, ?string $format = null, array $context = []): ?AbsoluteDate
{
$dateTimeFormat = $context[self::FORMAT_KEY] ?? AbsoluteDate::DEFAULT_DATE_FORMAT;
try {
return '' === $data || null === $data ? null : new AbsoluteDate($data, $dateTimeFormat);
} catch (\Exception $e) {
throw new NotNormalizableValueException($e->getMessage(), $e->getCode(), $e);
}
}
/**
* {@inheritdoc}
* @param mixed[] $context
*/
public function supportsDenormalization(
mixed $data,
string $type,
?string $format = null,
array $context = []
): bool {
return AbsoluteDate::class === $type;
}
/**
* @return array<'*', bool>
*/
public function getSupportedTypes(?string $format): array
{
return ['*' => false];
}
}