Passed
Pull Request — master (#78)
by David
01:57
created

TypeRegistry::getObjectType()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 4
dl 0
loc 7
rs 10
c 0
b 0
f 0
cc 2
nc 2
nop 1
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])) {
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...
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