Completed
Pull Request — master (#259)
by Sam
04:50
created

NameHelper::assertInvalid()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 4
nc 2
nop 1
dl 0
loc 9
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Digia\GraphQL\Util;
4
5
use Digia\GraphQL\Error\ValidationException;
6
use Digia\GraphQL\Language\Node\NodeInterface;
7
8
class NameHelper
9
{
10
11
    /**
12
     * Returns an Error if a name is invalid.
13
     *
14
     * @param string     $name
15
     * @param mixed|null $node
16
     * @return ValidationException
17
     */
18
    public static function isValidError(string $name, $node = null): ?ValidationException
19
    {
20
        if (\strlen($name) > 1 && $name{0} === '_' && $name{1} === '_') {
21
            return new ValidationException(
22
                sprintf('Name "%s" must not begin with "__", which is reserved by GraphQL introspection.', $name),
23
                $node instanceof NodeInterface ? [$node] : null
24
            );
25
        }
26
27
        if (preg_match("/^[_a-zA-Z][_a-zA-Z0-9]*$/", $name) === 0) {
28
            return new ValidationException(
29
                sprintf('Names must match /^[_a-zA-Z][_a-zA-Z0-9]*$/ but "%s" does not.', $name),
30
                $node instanceof NodeInterface ? [$node] : null
31
            );
32
        }
33
34
        return null;
35
    }
36
}
37