DateTimeType::serialize()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 3
c 1
b 0
f 0
dl 0
loc 7
rs 10
cc 2
nc 2
nop 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace GraphQLTests\Doctrine\Blog\Types;
6
7
use DateTimeImmutable;
8
use GraphQL\Error\Error;
9
use GraphQL\Language\AST\StringValueNode;
10
use GraphQL\Type\Definition\ScalarType;
11
use GraphQL\Utils\Utils;
12
use UnexpectedValueException;
13
14
final class DateTimeType extends ScalarType
15
{
16
    public function parseLiteral($valueNode, ?array $variables = null)
17
    {
18
        // Note: throwing GraphQL\Error\Error vs \UnexpectedValueException to benefit from GraphQL
19
        // error location in query:
20
        if (!($valueNode instanceof StringValueNode)) {
21
            throw new Error('Query error: Can only parse strings got: ' . $valueNode->kind, $valueNode);
22
        }
23
24
        return $valueNode->value;
25
    }
26
27
    public function parseValue(mixed $value): DateTimeImmutable
28
    {
29
        if (!is_string($value)) {
30
            throw new UnexpectedValueException('Cannot represent value as DateTime date: ' . Utils::printSafe($value));
31
        }
32
33
        return new DateTimeImmutable($value);
34
    }
35
36
    public function serialize(mixed $value): mixed
37
    {
38
        if ($value instanceof DateTimeImmutable) {
39
            return $value->format('c');
40
        }
41
42
        return $value;
43
    }
44
}
45