-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathIntRange.php
65 lines (52 loc) · 1.8 KB
/
IntRange.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
<?php declare(strict_types=1);
namespace MLL\GraphQLScalars;
use GraphQL\Error\Error;
use GraphQL\Language\AST\IntValueNode;
use GraphQL\Language\AST\Node;
use GraphQL\Language\Printer;
use GraphQL\Type\Definition\ScalarType;
use GraphQL\Utils\Utils;
abstract class IntRange extends ScalarType
{
/** The minimum allowed value. */
abstract protected static function min(): int;
/** The maximum allowed value. */
abstract protected static function max(): int;
public function serialize($value)
{
if (is_int($value) && $this->isValueInExpectedRange($value)) {
return $value;
}
$notInRange = Utils::printSafe($value);
throw new \InvalidArgumentException("Value not in range {$this->rangeDescription()}: {$notInRange}.");
}
public function parseValue($value)
{
if (is_int($value) && $this->isValueInExpectedRange($value)) {
return $value;
}
$notInRange = Utils::printSafe($value);
throw new Error("Value not in range {$this->rangeDescription()}: {$notInRange}.");
}
public function parseLiteral(Node $valueNode, ?array $variables = null)
{
if ($valueNode instanceof IntValueNode) {
$value = (int) $valueNode->value;
if ($this->isValueInExpectedRange($value)) {
return $value;
}
}
$notInRange = Printer::doPrint($valueNode);
throw new Error("Value not in range {$this->rangeDescription()}: {$notInRange}.", $valueNode);
}
private function isValueInExpectedRange(int $value): bool
{
return $value <= static::max() && $value >= static::min();
}
private function rangeDescription(): string
{
$min = static::min();
$max = static::max();
return "{$min}-{$max}";
}
}