Date::serialize()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 1
dl 0
loc 3
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
1
<?php
2
3
namespace DeInternetJongens\LighthouseUtils\Schema\Scalars;
4
5
use Carbon\Carbon;
6
use GraphQL\Error\Error;
7
use GraphQL\Language\AST\Node;
8
use GraphQL\Language\AST\StringValueNode;
9
use GraphQL\Type\Definition\LeafType;
10
use GraphQL\Type\Definition\ScalarType;
11
use GraphQL\Utils\Utils;
12
use InvalidArgumentException;
13
14
class Date extends ScalarType
15
{
16
    private const FORMAT = 'Y-m-d';
17
18
    /** @var string */
19
    public $name = 'Date';
20
21
    /** @var string */
22
    public $description = 'A date string with format Y-m-d. Example: "2018-01-01"';
23
24
    /**
25
     * @inheritdoc
26
     */
27
    public function serialize($value)
28
    {
29
        return $value->format(self::FORMAT);
30
    }
31
32
    /**
33
     * @inheritdoc
34
     */
35
    public function parseValue($value)
36
    {
37
        try {
38
            return Carbon::createFromFormat('' . self::FORMAT, $value);
39
        } catch (InvalidArgumentException $exception) {
40
            throw new Error(Utils::printSafeJson($exception->getMessage()));
41
        }
42
    }
43
44
    /**
45
     * @inheritdoc
46
     */
47
    public function parseLiteral($valueNode, array $variables = null)
48
    {
49
        if (! $valueNode instanceof StringValueNode) {
50
            throw new Error('Query error: Can only parse strings got: ' . $valueNode->kind, [$valueNode]);
51
        }
52
53
        return $this->parseValue($valueNode->value);
54
    }
55
}
56