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