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

SchemaValidator::assertValid()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 10
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 6
nc 2
nop 1
1
<?php
2
3
namespace Digia\GraphQL\Schema\Validation;
4
5
use Digia\GraphQL\Error\SchemaValidationException;
6
use Digia\GraphQL\Schema\Validation\Rule\RuleInterface;
7
use Digia\GraphQL\Schema\Validation\Rule\SupportedRules;
8
use Digia\GraphQL\Schema\SchemaInterface;
9
10
class SchemaValidator implements SchemaValidatorInterface
11
{
12
    /**
13
     * @param SchemaInterface      $schema
14
     * @param RuleInterface[]|null $rules
15
     * @return SchemaValidationException[]
16
     */
17
    public function validate(SchemaInterface $schema, ?array $rules = null): array
18
    {
19
        $context = $this->createContext($schema);
20
21
        $rules = $rules ?? SupportedRules::build();
22
23
        foreach ($rules as $rule) {
24
            $rule->setContext($context)->evaluate();
25
        }
26
27
        return $context->getErrors();
28
    }
29
30
    /**
31
     * @param SchemaInterface $schema
32
     * @throws SchemaValidationException
33
     */
34
    public function assertValid(SchemaInterface $schema): void
35
    {
36
        $errors = $this->validate($schema);
37
38
        if (!empty($errors)) {
39
            $message = \implode("\n", \array_map(function (SchemaValidationException $error) {
40
                return $error->getMessage();
41
            }, $errors));
42
43
            throw new SchemaValidationException($message);
44
        }
45
    }
46
47
    /**
48
     * @inheritdoc
49
     */
50
    public function createContext(SchemaInterface $schema): ValidationContextInterface
51
    {
52
        return new ValidationContext($schema);
53
    }
54
}
55