|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Overblog\GraphQLBundle\Definition\Type; |
|
4
|
|
|
|
|
5
|
|
|
use GraphQL\Type\Definition\CustomScalarType as BaseCustomScalarType; |
|
6
|
|
|
use GraphQL\Type\Definition\ScalarType; |
|
7
|
|
|
use GraphQL\Utils; |
|
8
|
|
|
|
|
9
|
|
|
class CustomScalarType extends BaseCustomScalarType |
|
10
|
|
|
{ |
|
11
|
23 |
|
public function __construct(array $config = []) |
|
12
|
|
|
{ |
|
13
|
23 |
|
parent::__construct($config); |
|
14
|
|
|
|
|
15
|
23 |
|
$this->config['scalarType'] = isset($this->config['scalarType']) ? $this->config['scalarType'] : null; |
|
16
|
23 |
|
$this->initOptionalFunctions(); |
|
17
|
23 |
|
} |
|
18
|
|
|
|
|
19
|
|
|
/** |
|
20
|
|
|
* {@inheritdoc} |
|
21
|
|
|
*/ |
|
22
|
8 |
|
public function serialize($value) |
|
23
|
|
|
{ |
|
24
|
8 |
|
return $this->call('serialize', $value); |
|
25
|
|
|
} |
|
26
|
|
|
|
|
27
|
|
|
/** |
|
28
|
|
|
* {@inheritdoc} |
|
29
|
|
|
*/ |
|
30
|
7 |
|
public function parseValue($value) |
|
31
|
|
|
{ |
|
32
|
7 |
|
return $this->call('parseValue', $value); |
|
33
|
|
|
} |
|
34
|
|
|
|
|
35
|
|
|
/** |
|
36
|
|
|
* {@inheritdoc} |
|
37
|
|
|
*/ |
|
38
|
5 |
|
public function parseLiteral(/* GraphQL\Language\AST\ValueNode */ $valueNode) |
|
39
|
|
|
{ |
|
40
|
5 |
|
return $this->call('parseLiteral', $valueNode); |
|
41
|
|
|
} |
|
42
|
|
|
|
|
43
|
12 |
|
private function call($type, $value) |
|
44
|
|
|
{ |
|
45
|
12 |
|
if (isset($this->config['scalarType'])) { |
|
46
|
9 |
|
$scalarType = $this->config['scalarType']; |
|
47
|
9 |
|
$scalarType = is_callable($scalarType) ? $scalarType() : $scalarType; |
|
48
|
|
|
|
|
49
|
9 |
|
return call_user_func([$scalarType, $type], $value); |
|
50
|
|
|
} else { |
|
51
|
3 |
|
return parent::$type($value); |
|
52
|
|
|
} |
|
53
|
|
|
} |
|
54
|
|
|
|
|
55
|
23 |
|
private function initOptionalFunctions() |
|
56
|
|
|
{ |
|
57
|
23 |
|
foreach (['parseLiteral', 'parseValue'] as $field) { |
|
58
|
23 |
|
if (!isset($this->config[$field])) { |
|
59
|
23 |
|
$this->config[$field] = static function () { |
|
60
|
|
|
return null; |
|
61
|
23 |
|
}; |
|
62
|
|
|
} |
|
63
|
|
|
} |
|
64
|
23 |
|
} |
|
65
|
|
|
|
|
66
|
19 |
|
public function assertValid() |
|
67
|
|
|
{ |
|
68
|
19 |
|
if (isset($this->config['scalarType'])) { |
|
69
|
16 |
|
$scalarType = $this->config['scalarType']; |
|
70
|
16 |
|
if (is_callable($scalarType)) { |
|
71
|
14 |
|
$scalarType = $scalarType(); |
|
72
|
|
|
} |
|
73
|
|
|
|
|
74
|
16 |
|
Utils::invariant( |
|
75
|
16 |
|
$scalarType instanceof ScalarType, |
|
76
|
16 |
|
sprintf( |
|
77
|
16 |
|
'%s must provide a valid "scalarType" instance of %s but got: %s', |
|
78
|
16 |
|
$this->name, |
|
79
|
16 |
|
ScalarType::class, |
|
80
|
16 |
|
Utils::printSafe($scalarType) |
|
81
|
|
|
) |
|
82
|
|
|
); |
|
83
|
|
|
} else { |
|
84
|
3 |
|
parent::assertValid(); |
|
85
|
|
|
} |
|
86
|
14 |
|
} |
|
87
|
|
|
} |
|
88
|
|
|
|