/
DateTime.php
105 lines (92 loc) · 2.65 KB
/
DateTime.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
<?php
/**
* @link https://craftcms.com/
* @copyright Copyright (c) Pixel & Tonic, Inc.
* @license https://craftcms.github.io/license/
*/
namespace craft\gql\types;
use craft\errors\GqlException;
use craft\gql\base\SingularTypeInterface;
use craft\gql\directives\FormatDateTime;
use craft\gql\GqlEntityRegistry;
use craft\helpers\DateTimeHelper;
use craft\helpers\Json;
use GraphQL\Language\AST\StringValueNode;
use GraphQL\Type\Definition\ScalarType;
/**
* Class DateTime implements the Datetime scalar type for GraphQL.
*
* @author Pixel & Tonic, Inc. <support@pixelandtonic.com>
* @since 3.3.0
*/
class DateTime extends ScalarType implements SingularTypeInterface
{
/**
* @var string
*/
public $name = 'DateTime';
/**
* @var string
*/
public $description = 'The `DateTime` scalar type represents a point in time.';
/**
* @var bool Whether parsed dates should be set to the system time zone
* @since 4.5.11
*/
public bool $setToSystemTimeZone = true;
/**
* Returns a singleton instance to ensure one type per schema.
*
* @return DateTime
*/
public static function getType(): DateTime
{
return GqlEntityRegistry::getOrCreate(self::getName(), fn() => new self());
}
/**
* @return string
*/
public static function getName(): string
{
return 'DateTime';
}
/**
* @inheritdoc
*/
public function serialize($value)
{
// The value not being a datetime would indicate an already formatted date.
if ($value instanceof \DateTime) {
$value = $value->format(FormatDateTime::DEFAULT_FORMAT);
}
return $value;
}
/**
* @inheritdoc
*/
public function parseValue($value)
{
if (is_string($value)) {
return DateTimeHelper::toDateTime(
Json::decodeIfJson($value),
setToSystemTimeZone: $this->setToSystemTimeZone,
);
}
// This message will be lost by the wrapping exception, but it feels good to provide one.
throw new GqlException('DateTime must be a string.');
}
/**
* @inheritdoc
*/
public function parseLiteral($valueNode, ?array $variables = null)
{
if ($valueNode instanceof StringValueNode) {
return DateTimeHelper::toDateTime(
Json::decodeIfJson($valueNode->value),
setToSystemTimeZone: $this->setToSystemTimeZone,
);
}
// This message will be lost by the wrapping exception, but it feels good to provide one.
throw new GqlException('DateTime must be a string.');
}
}