DateTimeTz::parseLiteral()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

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