Completed
Pull Request — master (#118)
by Christoffer
03:34
created

isValidNameError()   B

Complexity

Conditions 7
Paths 3

Size

Total Lines 19
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 19
rs 8.2222
c 0
b 0
f 0
cc 7
eloc 10
nc 3
nop 2
1
<?php
2
3
namespace Digia\GraphQL\Util;
4
5
use Digia\GraphQL\Error\InvariantException;
6
use Digia\GraphQL\Error\ValidationException;
7
use Digia\GraphQL\Language\Node\NodeInterface;
8
9
/**
10
 * Upholds the spec rules about naming.
11
 *
12
 * @param string $name
13
 * @return string
14
 * @throws InvariantException
15
 * @throws ValidationException
16
 */
17
function assertInvalidName(string $name): string
18
{
19
    $error = isValidNameError($name);
20
21
    if ($error) {
22
        throw $error;
23
    }
24
25
    return $name;
26
}
27
28
/**
29
 * Returns an Error if a name is invalid.
30
 *
31
 * @param string $name
32
 * @param mixed|null   $node
33
 * @return ValidationException
34
 * @throws InvariantException
35
 */
36
function isValidNameError(string $name, $node = null): ?ValidationException
37
{
38
    invariant(\is_string($name), 'Expected string');
39
40
    if (\strlen($name) > 1 && $name{0} === '_' && $name{1} === '_') {
41
        return new ValidationException(
42
            sprintf('Name "%s" must not begin with "__", which is reserved by GraphQL introspection.', $name),
43
            $node instanceof NodeInterface ? [$node] : null
44
        );
45
    }
46
47
    if (preg_match("/^[_a-zA-Z][_a-zA-Z0-9]*$/", $name) === 0) {
48
        return new ValidationException(
49
            sprintf('Names must match /^[_a-zA-Z][_a-zA-Z0-9]*$/ but "%s" does not.', $name),
50
            $node instanceof NodeInterface ? [$node] : null
51
        );
52
    }
53
54
    return null;
55
}
56