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