DateType::serialize()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 2.0625

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 3
c 1
b 0
f 0
nc 2
nop 1
dl 0
loc 7
ccs 3
cts 4
cp 0.75
crap 2.0625
rs 10
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