DateTimeType   A
last analyzed

Complexity

Total Complexity 6

Size/Duplication

Total Lines 29
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 6
eloc 10
c 1
b 0
f 0
dl 0
loc 29
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A parseLiteral() 0 9 2
A serialize() 0 7 2
A parseValue() 0 7 2
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