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