forked from mll-lab/graphql-php-scalars
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathStringScalar.php
101 lines (82 loc) · 2.79 KB
/
StringScalar.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
<?php
declare(strict_types=1);
namespace MLL\GraphQLScalars;
use GraphQL\Error\Error;
use GraphQL\Error\InvariantViolation;
use GraphQL\Type\Definition\ScalarType;
use GraphQL\Utils\Utils as GraphQLUtils;
abstract class StringScalar extends ScalarType
{
/**
* Instantiate an anonymous subclass that can be used in a schema.
*
* @param string $name The name that the scalar type will have in the schema.
* @param string|null $description A description for the type.
* @param callable $isValid A function that returns a boolean whether a given string is valid.
*
* @return StringScalar
*/
public static function make(string $name, ?string $description, callable $isValid): self
{
$concreteStringScalar = new class() extends StringScalar {
/**
* @var callable
*/
public $isValid;
/**
* Check if the given string is a valid email.
*/
protected function isValid(string $stringValue): bool
{
return call_user_func($this->isValid, $stringValue);
}
};
$concreteStringScalar->name = $name;
$concreteStringScalar->description = $description;
$concreteStringScalar->isValid = $isValid;
return $concreteStringScalar;
}
/**
* Check if the given string is valid.
*/
abstract protected function isValid(string $stringValue): bool;
public function serialize($value): string
{
$stringValue = Utils::coerceToString($value, InvariantViolation::class);
if (!$this->isValid($stringValue)) {
throw new InvariantViolation(
$this->invalidStringMessage($stringValue)
);
}
return $stringValue;
}
/**
* Construct an error message that occurs when an invalid string is passed.
*/
public function invalidStringMessage(string $stringValue): string
{
$safeValue = GraphQLUtils::printSafeJson($stringValue);
return "The given string {$safeValue} is not a valid {$this->tryInferName()}.";
}
public function parseValue($value): string
{
$stringValue = Utils::coerceToString($value, Error::class);
if (!$this->isValid($stringValue)) {
throw new Error(
$this->invalidStringMessage($stringValue)
);
}
return $stringValue;
}
public function parseLiteral($valueNode, ?array $variables = null): string
{
$stringValue = Utils::extractStringFromLiteral($valueNode);
if (!$this->isValid($stringValue)) {
throw new Error(
$this->invalidStringMessage($stringValue),
$valueNode
);
}
return $stringValue;
}
}