Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
45.45% covered (danger)
45.45%
5 / 11
0.00% covered (danger)
0.00%
0 / 1
CRAP
0.00% covered (danger)
0.00%
0 / 1
DateTimeConverter
45.45% covered (danger)
45.45%
5 / 11
0.00% covered (danger)
0.00%
0 / 1
35.37
0.00% covered (danger)
0.00%
0 / 1
 read
45.45% covered (danger)
45.45%
5 / 11
0.00% covered (danger)
0.00%
0 / 1
35.37
1<?php
2
3declare(strict_types=1);
4
5namespace PeServer\Core\Serialization\Converter;
6
7use DateTime;
8use DateTimeImmutable;
9use DateTimeInterface;
10use PeServer\Core\Text;
11use PeServer\Core\Throws\InvalidOperationException;
12use PeServer\Core\Utc;
13use ReflectionNamedType;
14
15
16/**
17 * @extends TypeConverterBase<DateTimeImmutable|DateTimeInterface|null>
18 */
19class 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}