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
|
|
|
|