ChronosType::parseValue()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 14
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 3

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 7
c 1
b 0
f 0
dl 0
loc 14
rs 10
ccs 8
cts 8
cp 1
cc 3
nc 3
nop 1
crap 3
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Ecodev\Felix\Api\Scalar;
6
7
use Cake\Chronos\Chronos;
8
use DateTimeZone;
9
use GraphQL\Error\Error;
10
use GraphQL\Language\AST\Node;
11
use GraphQL\Language\AST\StringValueNode;
12
use GraphQL\Type\Definition\ScalarType;
13
use GraphQL\Utils\Utils;
14
15
final class ChronosType extends ScalarType
16
{
17
    public ?string $description = 'A date with time and timezone.';
18
19
    /**
20
     * Serializes an internal value to include in a response.
21
     */
22 1
    public function serialize(mixed $value): mixed
23
    {
24 1
        if ($value instanceof Chronos) {
25 1
            return $value->format('c');
26
        }
27
28
        return $value;
29
    }
30
31
    /**
32
     * Parses an externally provided value (query variable) to use as an input.
33
     */
34 9
    public function parseValue(mixed $value): ?Chronos
35
    {
36 9
        if (!is_string($value)) {
37 1
            throw new Error('Cannot represent value as Chronos date: ' . Utils::printSafe($value));
38
        }
39
40 8
        if ($value === '') {
41 2
            return null;
42
        }
43
44 6
        $date = new Chronos($value);
45 6
        $date = $date->setTimezone(new DateTimeZone(date_default_timezone_get()));
46
47 6
        return $date;
48
    }
49
50
    /**
51
     * Parses an externally provided literal value to use as an input (e.g. in Query AST).
52
     */
53 5
    public function parseLiteral(Node $valueNode, ?array $variables = null): ?Chronos
54
    {
55
        // Note: throwing GraphQL\Error\Error vs \UnexpectedValueException to benefit from GraphQL
56
        // error location in query:
57 5
        if (!($valueNode instanceof StringValueNode)) {
58 1
            throw new Error('Query error: Can only parse strings got: ' . $valueNode->kind, $valueNode);
59
        }
60
61 4
        return $this->parseValue($valueNode->value);
62
    }
63
}
64