Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
Total | |
45.45% |
5 / 11 |
|
0.00% |
0 / 1 |
CRAP | |
0.00% |
0 / 1 |
DateTimeConverter | |
45.45% |
5 / 11 |
|
0.00% |
0 / 1 |
35.37 | |
0.00% |
0 / 1 |
read | |
45.45% |
5 / 11 |
|
0.00% |
0 / 1 |
35.37 |
1 | <?php |
2 | |
3 | declare(strict_types=1); |
4 | |
5 | namespace PeServer\Core\Serialization\Converter; |
6 | |
7 | use DateTime; |
8 | use DateTimeImmutable; |
9 | use DateTimeInterface; |
10 | use PeServer\Core\Text; |
11 | use PeServer\Core\Throws\InvalidOperationException; |
12 | use PeServer\Core\Utc; |
13 | use ReflectionNamedType; |
14 | |
15 | |
16 | /** |
17 | * @extends TypeConverterBase<DateTimeImmutable|DateTimeInterface|null> |
18 | */ |
19 | class DateTimeConverter extends TypeConverterBase |
20 | { |
21 | #region TypeConverterBase |
22 | |
23 | public function read(string $name, ReflectionNamedType $type, mixed $raw): DateTimeImmutable|DateTimeInterface|null |
24 | { |
25 | $targetClassName = $type->getName(); |
26 | switch ($targetClassName) { |
27 | case DateTimeImmutable::class: |
28 | if (is_string($raw) && !Text::isNullOrWhiteSpace($raw) && Utc::tryParse($raw, $result)) { |
29 | return $result; |
30 | } |
31 | break; |
32 | |
33 | case DateTime::class: |
34 | case DateTimeInterface::class: |
35 | if (is_string($raw) && !Text::isNullOrWhiteSpace($raw) && Utc::tryParseDateTime($raw, $result)) { |
36 | return $result; |
37 | } |
38 | break; |
39 | |
40 | default: |
41 | break; |
42 | } |
43 | |
44 | if ($type->allowsNull()) { |
45 | return null; |
46 | } |
47 | |
48 | throw new InvalidOperationException("$name: $targetClassName"); |
49 | } |
50 | |
51 | #endregion |
52 | } |