-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathRegex.php
101 lines (82 loc) · 2.97 KB
/
Regex.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;
use Spatie\Regex\Regex as RegexValidator;
abstract class Regex extends ScalarType
{
/**
* This factory method allows you to create a Regex scalar in a one-liner.
*
* @param string $name the name that the scalar type will have in the schema
* @param string|null $description a description for the type
* @param string $regex the regular expression that is validated against
*/
public static function make(string $name, ?string $description, string $regex): self
{
$concreteRegex = new class() extends Regex {
/**
* The regex that values are validated against.
*
* Is set dynamically during this class's creation.
*/
public static string $regex;
public static function regex(): string
{
return static::$regex;
}
};
$concreteRegex->name = $name;
$concreteRegex->description = $description;
$concreteRegex::$regex = $regex;
return $concreteRegex;
}
/** Return the Regex that the values are validated against. */
abstract public static function regex(): string;
public function serialize($value): string
{
$stringValue = Utils::coerceToString($value, InvariantViolation::class);
if (! static::matchesRegex($stringValue)) {
throw new InvariantViolation(
static::unmatchedRegexMessage($stringValue)
);
}
return $stringValue;
}
/** Determine if the given string matches the regex defined in this class. */
protected static function matchesRegex(string $value): bool
{
return RegexValidator::match(static::regex(), $value)
->hasMatch();
}
public function parseValue($value): string
{
$stringValue = Utils::coerceToString($value, Error::class);
if (! static::matchesRegex($stringValue)) {
throw new Error(
static::unmatchedRegexMessage($stringValue)
);
}
return $stringValue;
}
public function parseLiteral($valueNode, ?array $variables = null): string
{
$value = Utils::extractStringFromLiteral($valueNode);
if (! static::matchesRegex($value)) {
throw new Error(
static::unmatchedRegexMessage($value),
$valueNode
);
}
return $value;
}
/** Construct the error message that occurs when the given string does not match the regex. */
public static function unmatchedRegexMessage(string $value): string
{
$safeValue = GraphQLUtils::printSafeJson($value);
$regex = static::regex();
return "The given value {$safeValue} did not match the regex {$regex}.";
}
}