Passed
Pull Request — master (#159)
by Christoffer
02:37
created

SchemaValidator   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 48
Duplicated Lines 0 %

Importance

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

3 Methods

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