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

mapClassToInputType()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 14
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 14
rs 9.4285
c 0
b 0
f 0
nc 2
cc 2
eloc 7
nop 1
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