1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
|
4
|
|
|
namespace TheCodingMachine\GraphQL\Controllers; |
5
|
|
|
|
6
|
|
|
use function get_class; |
7
|
|
|
use GraphQL\Type\Definition\NamedType; |
8
|
|
|
use GraphQL\Type\Definition\ObjectType; |
9
|
|
|
use GraphQL\Type\Definition\InterfaceType; |
10
|
|
|
use GraphQL\Type\Definition\Type; |
11
|
|
|
|
12
|
|
|
/** |
13
|
|
|
* A cache used to store already FULLY COMPUTED types. |
14
|
|
|
*/ |
15
|
|
|
class TypeRegistry |
16
|
|
|
{ |
17
|
|
|
/** |
18
|
|
|
* @var array<string,NamedType&Type&(ObjectType|InterfaceType)> |
19
|
|
|
*/ |
20
|
|
|
private $outputTypes = []; |
21
|
|
|
|
22
|
|
|
/** |
23
|
|
|
* Registers a type. |
24
|
|
|
* IMPORTANT: the type MUST be fully computed (so ExtendType annotations must have ALREADY been applied to the tag) |
25
|
|
|
* ONLY THE RecursiveTypeMapper IS ALLOWED TO CALL THIS METHOD. |
26
|
|
|
* |
27
|
|
|
* @param NamedType&Type&(ObjectType|InterfaceType) $type |
28
|
|
|
*/ |
29
|
|
|
public function registerType(NamedType $type): void |
30
|
|
|
{ |
31
|
|
|
if (isset($this->outputTypes[$type->name])) { |
|
|
|
|
32
|
|
|
throw new GraphQLException('Type "'.$type->name.'" is already registered'); |
33
|
|
|
} |
34
|
|
|
$this->outputTypes[$type->name] = $type; |
35
|
|
|
} |
36
|
|
|
|
37
|
|
|
public function hasType(string $typeName): bool |
38
|
|
|
{ |
39
|
|
|
return isset($this->outputTypes[$typeName]); |
40
|
|
|
} |
41
|
|
|
|
42
|
|
|
/** |
43
|
|
|
* @param string $typeName |
44
|
|
|
* @return NamedType&Type&(ObjectType|InterfaceType) |
45
|
|
|
*/ |
46
|
|
|
public function getType(string $typeName): NamedType |
47
|
|
|
{ |
48
|
|
|
if (!isset($this->outputTypes[$typeName])) { |
49
|
|
|
throw new GraphQLException('Could not find type "'.$typeName.'" in registry'); |
50
|
|
|
} |
51
|
|
|
return $this->outputTypes[$typeName]; |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
public function getObjectType(string $typeName): ObjectType |
55
|
|
|
{ |
56
|
|
|
$type = $this->getType($typeName); |
57
|
|
|
if (!$type instanceof ObjectType) { |
58
|
|
|
throw new GraphQLException('Expected GraphQL type "'.$typeName.'" to be an ObjectType. Got a '.get_class($type)); |
59
|
|
|
} |
60
|
|
|
return $type; |
61
|
|
|
} |
62
|
|
|
} |
63
|
|
|
|