ChronosType   A
last analyzed

Complexity

Total Complexity 7

Size/Duplication

Total Lines 47
Duplicated Lines 0 %

Test Coverage

Coverage 93.75%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 7
eloc 15
c 1
b 0
f 0
dl 0
loc 47
rs 10
ccs 15
cts 16
cp 0.9375

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 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