Completed
Pull Request — master (#328)
by Sam
05:43
created

Validator::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 3
rs 10
c 0
b 0
f 0
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\Language\Visitor\VisitorInfo;
9
use Digia\GraphQL\Schema\Schema;
10
use Digia\GraphQL\Util\TypeInfo;
11
use Digia\GraphQL\Validation\Rule\RuleInterface;
12
use Digia\GraphQL\Validation\Rule\SupportedRules;
13
14
class Validator implements ValidatorInterface
15
{
16
    /**
17
     * @inheritdoc
18
     */
19
    public function validate(
20
        Schema $schema,
21
        DocumentNode $document,
22
        ?array $rules = null,
23
        ?TypeInfo $typeInfo = null
24
    ): array {
25
        $typeInfo = $typeInfo ?? new TypeInfo($schema);
26
        $rules    = $rules ?? SupportedRules::build();
27
28
        $context = $this->createContext($schema, $document, $typeInfo);
29
30
        $visitors = \array_map(function (RuleInterface $rule) use ($context) {
31
            return $rule->setContext($context);
32
        }, $rules);
33
34
        $visitor = new TypeInfoVisitor($typeInfo, new ParallelVisitor($visitors));
35
36
        // Visit the whole document with each instance of all provided rules.
37
        /** @noinspection PhpUnhandledExceptionInspection */
38
        $document->acceptVisitor(new VisitorInfo($visitor));
39
40
        return $context->getErrors();
41
    }
42
43
    /**
44
     * @param Schema       $schema
45
     * @param DocumentNode $document
46
     * @param TypeInfo     $typeInfo
47
     * @return ValidationContextInterface
48
     */
49
    public function createContext(
50
        Schema $schema,
51
        DocumentNode $document,
52
        TypeInfo $typeInfo
53
    ): ValidationContextInterface {
54
        return new ValidationContext($schema, $document, $typeInfo);
55
    }
56
}
57