Failed Conditions
Push — master ( 356b1f...e74f9e )
by Adrien
10:44
created

DateType::parseLiteral()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 3
nc 2
nop 2
dl 0
loc 9
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Application\Api\Scalar;
6
7
use Cake\Chronos\Date;
8
use GraphQL\Error\Error;
9
use GraphQL\Language\AST\Node;
10
use GraphQL\Language\AST\StringValueNode;
11
use GraphQL\Type\Definition\ScalarType;
12
use GraphQL\Utils\Utils;
13
14
class DateType extends ScalarType
15
{
16
    /**
17
     * @var string
18
     */
19
    public $description = 'A date without time, nor timezone.';
20
21
    /**
22
     * Serializes an internal value to include in a response.
23
     *
24
     * @param mixed $value
25
     *
26
     * @return mixed
27
     */
28
    public function serialize($value)
29
    {
30
        if ($value instanceof Date) {
31
            return $value->format('Y-m-d');
32
        }
33
34
        return $value;
35
    }
36
37
    /**
38
     * Parses an externally provided value (query variable) to use as an input
39
     *
40
     * @param mixed $value
41
     *
42
     * @return mixed
43
     */
44
    public function parseValue($value)
45
    {
46
        if (!is_string($value)) { // quite naive, but after all this is example
47
            throw new \UnexpectedValueException('Cannot represent value as Chronos date: ' . Utils::printSafe($value));
48
        }
49
50
        $date = new Date($value);
51
        $date = new Date($date->format('Y-m-d'));
52
53
        return $date;
54
    }
55
56
    /**
57
     * Parses an externally provided literal value to use as an input (e.g. in Query AST)
58
     *
59
     * @param $ast Node
60
     *
61
     * @return null|string
62
     */
63
    public function parseLiteral($ast, array $variables = null)
64
    {
65
        // Note: throwing GraphQL\Error\Error vs \UnexpectedValueException to benefit from GraphQL
66
        // error location in query:
67
        if (!($ast instanceof StringValueNode)) {
68
            throw new Error('Query error: Can only parse strings got: ' . $ast->kind, [$ast]);
69
        }
70
71
        return $ast->value;
72
    }
73
}
74