Completed
Push — master ( 8e6ca0...1e6eb5 )
by David
17s queued 11s
created

UnionType   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 26
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 4
eloc 14
dl 0
loc 26
rs 10
c 0
b 0
f 0

1 Method

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 20 4
1
<?php
2
3
4
namespace TheCodingMachine\GraphQL\Controllers\Types;
5
6
7
use GraphQL\Type\Definition\ObjectType;
8
use TheCodingMachine\GraphQL\Controllers\Mappers\RecursiveTypeMapperInterface;
9
10
class UnionType extends \GraphQL\Type\Definition\UnionType
11
{
12
    /**
13
     * @param ObjectType[] $types
14
     * @param RecursiveTypeMapperInterface $typeMapper
15
     */
16
    public function __construct(array $types, RecursiveTypeMapperInterface $typeMapper)
17
    {
18
        $name = 'Union';
19
        foreach ($types as $type) {
20
            $name .= $type->name;
21
            if (!$type instanceof ObjectType) {
22
                throw new \InvalidArgumentException('A Union type can only contain objects. Scalars, lists, etc... are not allowed.');
23
            }
24
        }
25
        parent::__construct([
26
            'name' => $name,
27
            'types' => $types,
28
            'resolveType' => function($value) use ($typeMapper) {
29
                if (!is_object($value)) {
30
                    throw new \InvalidArgumentException('Expected object for resolveType. Got: "'.gettype($value).'"');
31
                }
32
33
                $className = get_class($value);
34
                // TODO: check that if the class does not match, a parent class can match.
35
                return $typeMapper->mapClassToType($className);
36
            }
37
        ]);
38
    }
39
}
40