Passed
Pull Request — master (#171)
by Christoffer
02:11
created

Validator   A

Complexity

Total Complexity 3

Size/Duplication

Total Lines 58
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 3
dl 0
loc 58
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A createContext() 0 6 1
B validate() 0 25 1
A __construct() 0 3 1
1
<?php
2
3
namespace Digia\GraphQL\Validation;
4
5
use Digia\GraphQL\Language\Node\DocumentNode;
6
use Digia\GraphQL\Language\Visitor\ParallelVisitor;
7
use Digia\GraphQL\Language\Visitor\TypeInfoVisitor;
8
use Digia\GraphQL\Schema\SchemaInterface;
9
use Digia\GraphQL\Schema\Validation\SchemaValidatorInterface;
10
use Digia\GraphQL\Util\TypeInfo;
11
use Digia\GraphQL\Validation\Rule\RuleInterface;
12
use Digia\GraphQL\Validation\Rule\SupportedRules;
13
use function Digia\GraphQL\Util\invariant;
14
15
class Validator implements ValidatorInterface
16
{
17
    /**
18
     * @var SchemaValidatorInterface
19
     */
20
    protected $schemaValidator;
21
22
    /**
23
     * Validator constructor.
24
     * @param SchemaValidatorInterface $schemaValidator
25
     */
26
    public function __construct(SchemaValidatorInterface $schemaValidator)
27
    {
28
        $this->schemaValidator = $schemaValidator;
29
    }
30
31
    /**
32
     * @inheritdoc
33
     */
34
    public function validate(
35
        SchemaInterface $schema,
36
        DocumentNode $document,
37
        ?array $rules = null,
38
        ?TypeInfo $typeInfo = null
39
    ): array {
40
        invariant(null !== $document, 'Must provided document');
41
42
        $this->schemaValidator->assertValid($schema);
43
44
        $typeInfo = $typeInfo ?? new TypeInfo($schema);
45
        $rules    = $rules ?? SupportedRules::build();
46
47
        $context = $this->createContext($schema, $document, $typeInfo);
48
49
        $visitors = \array_map(function (RuleInterface $rule) use ($context) {
50
            return $rule->setContext($context);
51
        }, $rules);
52
53
        $visitor = new TypeInfoVisitor($typeInfo, new ParallelVisitor($visitors));
54
55
        // Visit the whole document with each instance of all provided rules.
56
        $document->acceptVisitor($visitor);
57
58
        return $context->getErrors();
59
    }
60
61
    /**
62
     * @param SchemaInterface $schema
63
     * @param DocumentNode    $document
64
     * @param TypeInfo        $typeInfo
65
     * @return ValidationContextInterface
66
     */
67
    public function createContext(
68
        SchemaInterface $schema,
69
        DocumentNode $document,
70
        TypeInfo $typeInfo
71
    ): ValidationContextInterface {
72
        return new ValidationContext($schema, $document, $typeInfo);
73
    }
74
}
75