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