DateType   A
last analyzed

Complexity

Total Complexity 6

Size/Duplication

Total Lines 42
Duplicated Lines 0 %

Test Coverage

Coverage 84.62%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 6
eloc 12
c 1
b 0
f 0
dl 0
loc 42
ccs 11
cts 13
cp 0.8462
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A serialize() 0 7 2
A parseLiteral() 0 9 2
A parseValue() 0 9 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Ecodev\Felix\Api\Scalar;
6
7
use Cake\Chronos\ChronosDate;
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
final class DateType extends ScalarType
15
{
16
    public ?string $description = 'A date without time, nor timezone.';
17
18
    /**
19
     * Serializes an internal value to include in a response.
20
     */
21 1
    public function serialize(mixed $value): mixed
22
    {
23 1
        if ($value instanceof ChronosDate) {
24 1
            return $value->format('Y-m-d');
25
        }
26
27
        return $value;
28
    }
29
30
    /**
31
     * Parses an externally provided value (query variable) to use as an input.
32
     */
33 8
    public function parseValue(mixed $value): ChronosDate
34
    {
35 8
        if (!is_string($value)) {
36
            throw new Error('Cannot represent value as Chronos date: ' . Utils::printSafe($value));
37
        }
38
39 8
        $date = ChronosDate::createFromFormat('Y-m-d+', $value);
40
41 8
        return $date;
42
    }
43
44
    /**
45
     * Parses an externally provided literal value to use as an input (e.g. in Query AST).
46
     */
47 5
    public function parseLiteral(Node $valueNode, ?array $variables = null): ChronosDate
48
    {
49
        // Note: throwing GraphQL\Error\Error vs \UnexpectedValueException to benefit from GraphQL
50
        // error location in query:
51 5
        if (!($valueNode instanceof StringValueNode)) {
52 1
            throw new Error('Query error: Can only parse strings got: ' . $valueNode->kind, $valueNode);
53
        }
54
55 4
        return $this->parseValue($valueNode->value);
56
    }
57
}
58