|
1
|
|
|
<?php |
|
2
|
|
|
namespace GraphQL\Examples\Blog\Type\Scalar; |
|
3
|
|
|
|
|
4
|
|
|
use GraphQL\Error\Error; |
|
5
|
|
|
use GraphQL\Language\AST\StringValueNode; |
|
6
|
|
|
use GraphQL\Type\Definition\CustomScalarType; |
|
7
|
|
|
use GraphQL\Utils\Utils; |
|
8
|
|
|
|
|
9
|
|
|
class EmailType |
|
10
|
|
|
{ |
|
11
|
|
|
public static function create() |
|
12
|
|
|
{ |
|
13
|
|
|
return new CustomScalarType([ |
|
14
|
|
|
'name' => 'Email', |
|
15
|
|
|
'serialize' => [__CLASS__, 'serialize'], |
|
16
|
|
|
'parseValue' => [__CLASS__, 'parseValue'], |
|
17
|
|
|
'parseLiteral' => [__CLASS__, 'parseLiteral'], |
|
18
|
|
|
]); |
|
19
|
|
|
} |
|
20
|
|
|
|
|
21
|
|
|
/** |
|
22
|
|
|
* Serializes an internal value to include in a response. |
|
23
|
|
|
* |
|
24
|
|
|
* @param string $value |
|
25
|
|
|
* @return string |
|
26
|
|
|
*/ |
|
27
|
|
|
public static function serialize($value) |
|
28
|
|
|
{ |
|
29
|
|
|
// Assuming internal representation of email is always correct: |
|
30
|
|
|
return $value; |
|
31
|
|
|
|
|
32
|
|
|
// If it might be incorrect and you want to make sure that only correct values are included in response - |
|
33
|
|
|
// use following line instead: |
|
34
|
|
|
// return $this->parseValue($value); |
|
35
|
|
|
} |
|
36
|
|
|
|
|
37
|
|
|
/** |
|
38
|
|
|
* Parses an externally provided value (query variable) to use as an input |
|
39
|
|
|
* |
|
40
|
|
|
* @param mixed $value |
|
41
|
|
|
* @return mixed |
|
42
|
|
|
*/ |
|
43
|
|
|
public static function parseValue($value) |
|
44
|
|
|
{ |
|
45
|
|
|
if (!filter_var($value, FILTER_VALIDATE_EMAIL)) { |
|
46
|
|
|
throw new \UnexpectedValueException("Cannot represent value as email: " . Utils::printSafe($value)); |
|
47
|
|
|
} |
|
48
|
|
|
return $value; |
|
49
|
|
|
} |
|
50
|
|
|
|
|
51
|
|
|
/** |
|
52
|
|
|
* Parses an externally provided literal value (hardcoded in GraphQL query) to use as an input |
|
53
|
|
|
* |
|
54
|
|
|
* @param \GraphQL\Language\AST\Node $valueNode |
|
55
|
|
|
* @return string |
|
56
|
|
|
* @throws Error |
|
57
|
|
|
*/ |
|
58
|
|
|
public static function parseLiteral($valueNode) |
|
59
|
|
|
{ |
|
60
|
|
|
// Note: throwing GraphQL\Error\Error vs \UnexpectedValueException to benefit from GraphQL |
|
61
|
|
|
// error location in query: |
|
62
|
|
|
if (!$valueNode instanceof StringValueNode) { |
|
63
|
|
|
throw new Error('Query error: Can only parse strings got: ' . $valueNode->kind, [$valueNode]); |
|
64
|
|
|
} |
|
65
|
|
|
if (!filter_var($valueNode->value, FILTER_VALIDATE_EMAIL)) { |
|
66
|
|
|
throw new Error("Not a valid email", [$valueNode]); |
|
67
|
|
|
} |
|
68
|
|
|
return $valueNode->value; |
|
69
|
|
|
} |
|
70
|
|
|
} |
|
71
|
|
|
|