Passed
Pull Request — master (#118)
by Christoffer
02:40
created

isValidNameError()   B

Complexity

Conditions 5
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.8571
c 0
b 0
f 0
cc 5
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 = $this->isValidNameError($name);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $this seems to be never defined.
Loading history...
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
 * @return ValidationException
33
 * @throws InvariantException
34
 */
35
function isValidNameError(string $name, ?NodeInterface $node = null): ?ValidationException
36
{
37
    invariant(\is_string($name), 'Expected string');
38
39
    if (\strlen($name) > 1 && $name{0} === '_' && $name{1} === '_') {
40
        return new ValidationException(
41
            sprintf('Name "%s" must not begin with "__", which is reserved by GraphQL introspection.', $name),
42
            [$node]
43
        );
44
    }
45
46
    if (preg_match("/^[_a-zA-Z][_a-zA-Z0-9]*$/", $name) === 0) {
47
        return new ValidationException(
48
            sprintf('Names must match /^[_a-zA-Z][_a-zA-Z0-9]*$/ but "%s" does not.', $name),
49
            [$node]
50
        );
51
    }
52
53
    return null;
54
}
55