Completed
Push — 1.x ( 5fff12...5978a4 )
by David
07:15 queued 04:01
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
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