Passed
Pull Request — master (#2887)
by Kévin
03:48
created

MatchesJsonSchema::matches()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 12
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 6
c 1
b 0
f 0
nc 2
nop 1
dl 0
loc 12
rs 10
1
<?php
2
3
/*
4
 * This file is part of the API Platform project.
5
 *
6
 * (c) Kévin Dunglas <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
declare(strict_types=1);
13
14
namespace ApiPlatform\Core\Bridge\Symfony\Bundle\Test\Constraint;
15
16
use JsonSchema\Validator;
17
use PHPUnit\Framework\Constraint\Constraint;
18
19
/**
20
 * Asserts that a JSON document matches a given JSON Schema.
21
 *
22
 * @author Kévin Dunglas <[email protected]>
23
 *
24
 * @experimental
25
 */
26
final class MatchesJsonSchema extends Constraint
27
{
28
    private $schema;
29
    private $checkMode;
30
31
    /**
32
     * @param array|string $schema
33
     */
34
    public function __construct($schema, ?int $checkMode = null)
35
    {
36
        $this->checkMode = $checkMode;
37
        $this->schema = \is_array($schema) ? (object) $schema : json_decode($schema);
38
    }
39
40
    /**
41
     * {@inheritdoc}
42
     */
43
    public function toString(): string
44
    {
45
        return 'matches the provided JSON Schema';
46
    }
47
48
    /**
49
     * @param array $other
50
     */
51
    protected function matches($other): bool
52
    {
53
        if (!class_exists(Validator::class)) {
54
            throw new \RuntimeException('The "justinrainbow/json-schema" library must be installed to use "assertMatchesJsonSchema()". Try running "composer require --dev justinrainbow/json-schema".');
55
        }
56
57
        $other = (object) $other;
58
59
        $validator = new Validator();
60
        $validator->validate($other, $this->schema, $this->checkMode);
61
62
        return $validator->isValid();
63
    }
64
65
    /**
66
     * @param object $other
67
     */
68
    protected function additionalFailureDescription($other): string
69
    {
70
        $other = (object) $other;
71
72
        $validator = new Validator();
73
        $validator->check($other, $this->schema);
74
75
        $errors = [];
76
        foreach ($validator->getErrors() as $error) {
77
            $property = $error['property'] ? $error['property'].': ' : '';
78
            $errors[] = $property.$error['message'];
79
        }
80
81
        return implode("\n", $errors);
82
    }
83
}
84