Completed
Push — master ( 6c2ef1...d70f56 )
by David
15s queued 10s
created

TypeRegistry   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 46
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 7
eloc 12
dl 0
loc 46
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A getMutableObjectType() 0 7 2
A getType() 0 6 2
A hasType() 0 3 1
A registerType() 0 6 2
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
use TheCodingMachine\GraphQL\Controllers\Types\MutableObjectType;
12
13
/**
14
 * A cache used to store already FULLY COMPUTED types.
15
 */
16
class TypeRegistry
17
{
18
    /**
19
     * @var array<string,NamedType&Type&(MutableObjectType|InterfaceType)>
20
     */
21
    private $outputTypes = [];
22
23
    /**
24
     * Registers a type.
25
     * IMPORTANT: the type MUST be fully computed (so ExtendType annotations must have ALREADY been applied to the tag)
26
     * ONLY THE RecursiveTypeMapper IS ALLOWED TO CALL THIS METHOD.
27
     *
28
     * @param NamedType&Type&(ObjectType|InterfaceType) $type
29
     */
30
    public function registerType(NamedType $type): void
31
    {
32
        if (isset($this->outputTypes[$type->name])) {
0 ignored issues
show
Bug introduced by
Accessing name on the interface GraphQL\Type\Definition\NamedType suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
33
            throw new GraphQLException('Type "'.$type->name.'" is already registered');
34
        }
35
        $this->outputTypes[$type->name] = $type;
36
    }
37
38
    public function hasType(string $typeName): bool
39
    {
40
        return isset($this->outputTypes[$typeName]);
41
    }
42
43
    /**
44
     * @param string $typeName
45
     * @return NamedType&Type&(ObjectType|InterfaceType)
46
     */
47
    public function getType(string $typeName): NamedType
48
    {
49
        if (!isset($this->outputTypes[$typeName])) {
50
            throw new GraphQLException('Could not find type "'.$typeName.'" in registry');
51
        }
52
        return $this->outputTypes[$typeName];
53
    }
54
55
    public function getMutableObjectType(string $typeName): MutableObjectType
56
    {
57
        $type = $this->getType($typeName);
58
        if (!$type instanceof MutableObjectType) {
59
            throw new GraphQLException('Expected GraphQL type "'.$typeName.'" to be an MutableObjectType. Got a '.get_class($type));
60
        }
61
        return $type;
62
    }
63
}
64