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

ChronosType   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 62
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 15
dl 0
loc 62
rs 10
c 0
b 0
f 0
wmc 7

3 Methods

Rating   Name   Duplication   Size   Complexity  
A parseLiteral() 0 9 2
A serialize() 0 7 2
A parseValue() 0 14 3
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Application\Api\Scalar;
6
7
use Cake\Chronos\Chronos;
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 ChronosType extends ScalarType
15
{
16
    /**
17
     * @var string
18
     */
19
    public $description = 'A date with time and 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 Chronos) {
31
            return $value->format('c');
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
        if ($value === '') {
51
            return null;
52
        }
53
54
        $date = new Chronos($value);
55
        $date = $date->setTimezone(new \DateTimeZone(date_default_timezone_get()));
56
57
        return $date;
58
    }
59
60
    /**
61
     * Parses an externally provided literal value to use as an input (e.g. in Query AST)
62
     *
63
     * @param $ast Node
64
     *
65
     * @return null|string
66
     */
67
    public function parseLiteral($ast, array $variables = null)
68
    {
69
        // Note: throwing GraphQL\Error\Error vs \UnexpectedValueException to benefit from GraphQL
70
        // error location in query:
71
        if (!($ast instanceof StringValueNode)) {
72
            throw new Error('Query error: Can only parse strings got: ' . $ast->kind, [$ast]);
73
        }
74
75
        return $ast->value;
76
    }
77
}
78