Completed
Pull Request — master (#45)
by Christoffer
02:13
created

compareTypes()   C

Complexity

Conditions 9
Paths 8

Size

Total Lines 22
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 9
eloc 15
nc 8
nop 2
dl 0
loc 22
rs 6.412
c 0
b 0
f 0
1
<?php
2
3
namespace Digia\GraphQL\Validation;
4
5
use Digia\GraphQL\Language\AST\Node\ArgumentNode;
6
use Digia\GraphQL\Type\Definition\LeafTypeInterface;
7
use Digia\GraphQL\Type\Definition\ListType;
8
use Digia\GraphQL\Type\Definition\NonNullType;
9
use Digia\GraphQL\Type\Definition\TypeInterface;
10
use function Digia\GraphQL\Util\arrayEvery;
11
use function Digia\GraphQL\Util\find;
12
13
function compareArguments($argumentsA, $argumentsB): bool
14
{
15
    if (\count($argumentsA) !== \count($argumentsB)) {
16
        return false;
17
    }
18
19
    return arrayEvery($argumentsA, function (ArgumentNode $argumentA) use ($argumentsB) {
20
        $argumentB = find($argumentsB, function (ArgumentNode $argument) use ($argumentA) {
21
            return $argument->getNameValue() === $argumentA->getNameValue();
22
        });
23
24
        if (null === $argumentB) {
25
            return false;
26
        }
27
28
        return compareValues($argumentA->getValue(), $argumentB->getValue());
29
    });
30
}
31
32
/**
33
 * @param $valueA
34
 * @param $valueB
35
 * @return bool
36
 */
37
function compareValues($valueA, $valueB): bool
38
{
39
    return $valueA == $valueB;
40
}
41
42
/**
43
 * Two types conflict if both types could not apply to a value simultaneously.
44
 * Composite types are ignored as their individual field types will be compared
45
 * later recursively. However List and Non-Null types must match.
46
 *
47
 * @param TypeInterface $typeA
48
 * @param TypeInterface $typeB
49
 * @return bool
50
 */
51
function compareTypes(TypeInterface $typeA, TypeInterface $typeB): bool
52
{
53
    if ($typeA instanceof ListType) {
54
        return $typeB instanceof ListType
55
            ? compareTypes($typeA->getOfType(), $typeB->getOfType())
56
            : true;
57
    }
58
    if ($typeB instanceof ListType) {
59
        return true;
60
    }
61
    if ($typeA instanceof NonNullType) {
62
        return $typeB instanceof NonNullType
63
            ? compareTypes($typeA->getOfType(), $typeB->getOfType())
64
            : true;
65
    }
66
    if ($typeB instanceof NonNullType) {
67
        return true;
68
    }
69
    if ($typeA instanceof LeafTypeInterface || $typeB instanceof LeafTypeInterface) {
70
        return $typeA !== $typeB;
71
    }
72
    return false;
73
}
74