UnionType::isPossibleType()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
cc 1
eloc 2
nc 1
nop 1
crap 1
1
<?php
2
3
namespace Fubhy\GraphQL\Type\Definition\Types;
4
5
/**
6
 * Union Type Definition.
7
 *
8
 * When a field can return one of a heterogeneous set of types, a Union type is
9
 * used to describe what types are possible as well as providing a function to
10
 * determine which type is actually used when the field is resolved.
11
 */
12
class UnionType extends AbstractType implements OutputTypeInterface, CompositeTypeInterface, NullableTypeInterface, UnmodifiedTypeInterface
13
{
14
    /**
15
     * @var array
16
     */
17
    protected $types;
18
19
    /**
20
     * @var callable|null
21
     */
22
    protected $typeResolver;
23
24
    /**
25
     * Constructor.
26
     *
27
     * @param string $name
28
     * @param array $types
29
     * @param callable|null $typeResolver
30
     * @param string|null $description
31
     */
32 42
    public function __construct($name, array $types = [], callable $typeResolver = NULL, $description = NULL)
33
    {
34 42
        parent::__construct($name, $description);
35
36
        $nonObjectTypes = array_filter($types, function (TypeInterface $type) {
37 39
            return !($type instanceof ObjectType);
38 42
        });
39
40 42
        if (!empty($nonObjectTypes)) {
41 21
            $nonObjectTypes = implode(', ', array_map(function ($type) {
42 21
                return (string) $type;
43 21
            }, $nonObjectTypes));
44
45 21
            throw new \LogicException(sprintf('Union %s may only contain object types, it cannot contain: %s.', (string) $this, $nonObjectTypes));
46
        }
47
48 21
        $this->types = $types;
49 21
        $this->typeResolver = $typeResolver;
50 21
    }
51
52
    /**
53
     * {@inheritdoc}
54
     */
55 12
    public function getPossibleTypes()
56
    {
57 12
        return $this->types;
58
    }
59
60
    /**
61
     * {@inheritdoc}
62
     */
63
    public function addPossibleType(ObjectType $type)
64
    {
65
        $this->types = array_unique($this->types + [$type]);
66
    }
67
68
    /**
69
     * {@inheritdoc}
70
     */
71 3
    public function isPossibleType(ObjectType $type)
72
    {
73 3
        return in_array($type, $this->types, TRUE);
74
    }
75
76
    /**
77
     * {@inheritdoc}
78
     */
79 9
    public function resolveType($value)
80
    {
81 9
        if (isset($this->typeResolver)) {
82 9
            return call_user_func($this->typeResolver, $value);
83
        }
84
85
        return $this->getTypeOf($value);
86
    }
87
}
88