TypeResolver::mapNameToType()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 12
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 6
dl 0
loc 12
rs 10
c 0
b 0
f 0
cc 3
nc 3
nop 1
1
<?php
2
3
4
namespace TheCodingMachine\GraphQL\Controllers\Types;
5
6
use GraphQL\Type\Definition\Type;
7
use GraphQL\Type\Schema;
8
use RuntimeException;
9
use TheCodingMachine\GraphQL\Controllers\Mappers\CannotMapTypeException;
10
use TheCodingMachine\GraphQL\Controllers\Mappers\CannotMapTypeExceptionInterface;
11
12
/**
13
 * Resolves a type by its GraphQL name.
14
 *
15
 * Unlike the TypeMappers, this class can resolve standard GraphQL types (like String, ID, etc...)
16
 */
17
class TypeResolver
18
{
19
    /**
20
     * @var Schema
21
     */
22
    private $schema;
23
24
    public function registerSchema(Schema $schema)
25
    {
26
        $this->schema = $schema;
27
    }
28
29
    /**
30
     * @param string $typeName
31
     * @return Type
32
     * @throws CannotMapTypeExceptionInterface
33
     */
34
    public function mapNameToType(string $typeName): Type
35
    {
36
        if ($this->schema === null) {
37
            throw new RuntimeException('You must register a schema first before resolving types.');
38
        }
39
        
40
        $type = $this->schema->getType($typeName);
41
        if ($type === null) {
42
            throw CannotMapTypeException::createForName($typeName);
43
        }
44
45
        return $type;
46
    }
47
}
48