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