Passed
Pull Request — 1.x (#8)
by David
11:53
created

AbstractTdbmGraphQLTypeMapper   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 57
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 4

Importance

Changes 0
Metric Value
wmc 5
lcom 0
cbo 4
dl 0
loc 57
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
getMap() 0 1 ?
A __construct() 0 4 1
A mapClassToType() 0 8 2
A mapClassToInputType() 0 14 2
1
<?php
2
3
4
namespace TheCodingMachine\Tdbm\GraphQL;
5
6
7
use Psr\Container\ContainerInterface;
8
use Youshido\GraphQL\Type\InputObject\InputObjectType;
9
use Youshido\GraphQL\Type\Object\AbstractObjectType;
10
use Youshido\GraphQL\Type\TypeInterface;
11
12
abstract class AbstractTdbmGraphQLTypeMapper
13
{
14
    /**
15
     * @var ContainerInterface
16
     */
17
    private $container;
18
19
    /**
20
     * Returns an array mapping PHP classes to GraphQL types.
21
     *
22
     * @return array
23
     */
24
    abstract protected function getMap(): array;
25
26
    public function __construct(ContainerInterface $container)
27
    {
28
        $this->container = $container;
29
    }
30
31
    /**
32
     * Maps a PHP fully qualified class name to a GraphQL type.
33
     *
34
     * @param string $className
35
     * @return TypeInterface
36
     * @throws GraphQLException
37
     */
38
    public function mapClassToType(string $className): TypeInterface
39
    {
40
        $map = $this->getMap();
41
        if (!isset($map[$className])) {
42
            throw new GraphQLException("Unable to map class $className to any known GraphQL type.");
43
        }
44
        return $this->container->get($map[$className]);
45
    }
46
47
    /**
48
     * Maps a PHP fully qualified class name to a GraphQL input type.
49
     *
50
     * @param string $className
51
     * @return InputTypeInterface
52
     * @throws GraphQLException
53
     */
54
    public function mapClassToInputType(string $className): InputTypeInterface
55
    {
56
        // Let's create the input type "on the fly"!
57
        $type = $this->mapClassToType($className);
58
59
        if ($type instanceof AbstractObjectType) {
60
            throw new GraphQLException('Cannot map a type to input type if it does not extend the AbstractObjectType class');
61
        }
62
63
        return new InputObjectType([
64
            'name' => $type->getName().'Input',
65
            'fields' => $type->getFields()
66
        ]);
67
    }
68
}
69