-
Notifications
You must be signed in to change notification settings - Fork 611
/
Number.php
109 lines (94 loc) · 2.6 KB
/
Number.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
106
107
108
109
<?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\GqlEntityRegistry;
use GraphQL\Language\AST\FloatValueNode;
use GraphQL\Language\AST\IntValueNode;
use GraphQL\Language\AST\NullValueNode;
use GraphQL\Language\AST\StringValueNode;
use GraphQL\Type\Definition\ScalarType;
/**
* Class Number implements the Number scalar type for GraphQL.
*
* @author Pixel & Tonic, Inc. <support@pixelandtonic.com>
* @since 3.4.0
*/
class Number extends ScalarType implements SingularTypeInterface
{
/**
* @var string
*/
public $name = 'Number';
/**
* @var string
*/
public $description = 'The `Number` scalar type represents a number that can be a float, an integer or a null value.';
/**
* Returns a singleton instance to ensure one type per schema.
*
* @return Number
*/
public static function getType(): Number
{
return GqlEntityRegistry::getOrCreate(static::getName(), fn() => new self());
}
/**
* @return string
*/
public static function getName(): string
{
return 'Number';
}
/**
* @inheritdoc
*/
public function serialize($value)
{
if (is_numeric($value)) {
if ((int)$value == $value) {
return (int)$value;
}
if ((float)$value == $value) {
return (float)$value;
}
}
if (empty($value)) {
return null;
}
return $value;
}
/**
* @inheritdoc
*/
public function parseValue($value)
{
if (!is_int($value) && !is_float($value) && !is_null($value)) {
throw new GqlException('Number must be either a float, an integer, or null.');
}
return $value;
}
/**
* @inheritdoc
*/
public function parseLiteral($valueNode, ?array $variables = null)
{
// Treat strings as floats
if ($valueNode instanceof StringValueNode || $valueNode instanceof FloatValueNode) {
return (float)$valueNode->value;
}
if ($valueNode instanceof IntValueNode) {
return (int)$valueNode->value;
}
if ($valueNode instanceof NullValueNode) {
return null;
}
// This message will be lost by the wrapping exception, but it feels good to provide one.
throw new GqlException("Number must be either a float or an integer.");
}
}