Passed
Pull Request — master (#158)
by Christoffer
04:56 queued 02:10
created

NameHelper::isValidError()   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
class NameHelper
10
{
11
    /**
12
     * Upholds the spec rules about naming.
13
     *
14
     * @param string $name
15
     * @return string
16
     * @throws InvariantException
17
     * @throws ValidationException
18
     */
19
    function assertInvalid(string $name): string
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
20
    {
21
        $error = $this->isValidError($name);
22
23
        if ($error) {
24
            throw $error;
25
        }
26
27
        return $name;
28
    }
29
30
    /**
31
     * Returns an Error if a name is invalid.
32
     *
33
     * @param string     $name
34
     * @param mixed|null $node
35
     * @return ValidationException
36
     * @throws InvariantException
37
     */
38
    function isValidError(string $name, $node = null): ?ValidationException
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
39
    {
40
        invariant(\is_string($name), 'Expected string');
41
42
        if (\strlen($name) > 1 && $name{0} === '_' && $name{1} === '_') {
43
            return new ValidationException(
44
                sprintf('Name "%s" must not begin with "__", which is reserved by GraphQL introspection.', $name),
45
                $node instanceof NodeInterface ? [$node] : null
46
            );
47
        }
48
49
        if (preg_match("/^[_a-zA-Z][_a-zA-Z0-9]*$/", $name) === 0) {
50
            return new ValidationException(
51
                sprintf('Names must match /^[_a-zA-Z][_a-zA-Z0-9]*$/ but "%s" does not.', $name),
52
                $node instanceof NodeInterface ? [$node] : null
53
            );
54
        }
55
56
        return null;
57
    }
58
}
59