Completed
Pull Request — master (#34)
by David
02:32 queued 55s
created

DateTimeType::parseLiteral()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 3
dl 0
loc 7
rs 10
c 0
b 0
f 0
cc 2
nc 2
nop 2
1
<?php
2
declare(strict_types = 1);
3
4
namespace TheCodingMachine\GraphQL\Controllers\Types;
5
6
7
use DateTime;
8
use DateTimeImmutable;
9
use GraphQL\Error\InvariantViolation;
10
use GraphQL\Language\AST\Node;
11
use GraphQL\Language\AST\StringValueNode;
12
use GraphQL\Language\AST\ValueNode;
13
use GraphQL\Type\Definition\ScalarType;
14
use GraphQL\Utils\Utils;
15
16
class DateTimeType extends ScalarType
17
{
18
    private static $instance;
19
20
    public static function getInstance(): self
21
    {
22
        if (self::$instance === null) {
23
            self::$instance = new self();
24
        }
25
        return self::$instance;
26
    }
27
28
29
    /**
30
     * @var string
31
     */
32
    public $name = 'DateTime';
33
34
    /**
35
     * @var string
36
     */
37
    public $description = 'The `DateTime` scalar type represents time data, represented as an ISO-8601 encoded UTC date string.';
38
39
    /**
40
     * @param mixed $value
41
     */
42
    public function serialize($value): string
43
    {
44
        if (! $value instanceof DateTimeImmutable) {
45
            throw new InvariantViolation('DateTime is not an instance of DateTimeImmutable: ' . Utils::printSafe($value));
46
        }
47
48
        return $value->format(DateTime::ATOM);
49
    }
50
51
    /**
52
     * @param mixed $value
53
     */
54
    public function parseValue($value): ?DateTimeImmutable
55
    {
56
        return DateTimeImmutable::createFromFormat(DateTime::ATOM, $value) ?: null;
57
    }
58
59
    /**
60
     * Parses an externally provided literal value (hardcoded in GraphQL query) to use as an input
61
     *
62
     * In the case of an invalid node or value this method must throw an Exception
63
     *
64
     * @param Node $valueNode
65
     * @param array|null $variables
66
     * @return mixed
67
     * @throws \Exception
68
     */
69
    public function parseLiteral($valueNode, array $variables = null)
70
    {
71
        if ($valueNode instanceof StringValueNode) {
72
            return $valueNode->value;
73
        }
74
75
        return null;
76
    }
77
}