Passed
Push — master ( 8bc3a9...d5f8d6 )
by Christoffer
02:14
created

SchemaValidator   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 50
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 5
dl 0
loc 50
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
A validate() 0 13 2
A assertValid() 0 10 2
1
<?php
2
3
namespace Digia\GraphQL\SchemaValidator;
4
5
use Digia\GraphQL\Error\ValidationException;
6
use Digia\GraphQL\SchemaValidator\Rule\RuleInterface;
7
use Digia\GraphQL\SchemaValidator\Rule\SupportedRules;
8
use Digia\GraphQL\Type\SchemaInterface;
9
10
class SchemaValidator implements SchemaValidatorInterface
11
{
12
    /**
13
     * @var ContextBuilderInterface
14
     */
15
    protected $contextBuilder;
16
17
    /**
18
     * SchemaValidator constructor.
19
     * @param ContextBuilderInterface $contextBuilder
20
     */
21
    public function __construct(ContextBuilderInterface $contextBuilder)
22
    {
23
        $this->contextBuilder = $contextBuilder;
24
    }
25
26
    /**
27
     * @param SchemaInterface      $schema
28
     * @param RuleInterface[]|null $rules
29
     * @return ValidationException[]
30
     */
31
    public function validate(SchemaInterface $schema, ?array $rules = null): array
32
    {
33
        $context = $this->contextBuilder->build($schema);
34
35
        $rules = $rules ?? SupportedRules::build();
36
37
        foreach ($rules as $rule) {
38
            $rule
39
                ->setContext($context)
40
                ->evaluate();
41
        }
42
43
        return $context->getErrors();
44
    }
45
46
    /**
47
     * @param SchemaInterface $schema
48
     * @throws ValidationException
49
     */
50
    public function assertValid(SchemaInterface $schema): void
51
    {
52
        $errors = $this->validate($schema);
53
54
        if (!empty($errors)) {
55
            $message = \implode("\n", \array_map(function (ValidationException $error) {
56
                return $error->getMessage();
57
            }, $errors));
58
59
            throw new ValidationException($message);
60
        }
61
    }
62
}
63