MatchesSchema   A
last analyzed

Complexity

Total Complexity 6

Size/Duplication

Total Lines 63
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 2
Bugs 1 Features 1
Metric Value
wmc 6
eloc 17
c 2
b 1
f 1
dl 0
loc 63
ccs 21
cts 21
cp 1
rs 10

5 Methods

Rating   Name   Duplication   Size   Complexity  
A matches() 0 8 1
A toString() 0 3 1
A convertToObject() 0 7 2
A __construct() 0 3 1
A additionalFailureDescription() 0 10 1
1
<?php declare(strict_types=1);
2
3
4
namespace Pitchart\Phlunit\Constraint\Json;
5
6
use JsonSchema\Validator;
7
use PHPUnit\Framework\Constraint\Constraint;
8
9
class MatchesSchema extends Constraint
10
{
11
    /**
12
     * @var \stdClass
13
     */
14
    private $schema;
15
16
    /**
17
     * MatchesSchema constructor.
18
     *
19
     * @param string|array|object $schema
20
     */
21 11
    public function __construct($schema)
22
    {
23 11
        $this->schema = $this->convertToObject($schema);
24 11
    }
25
26
27 1
    public function toString(): string
28
    {
29 1
        return \sprintf('matches Json Schema %s', \json_encode($this->schema));
30
    }
31
32
    /**
33
     * @inheritdoc
34
     */
35 9
    protected function matches($other): bool
36
    {
37 9
        $other = $this->convertToObject($other);
38
39 9
        $validator = new Validator();
40 9
        $validator->check($other, $this->schema);
41
42 9
        return $validator->isValid();
43
    }
44
45
    /**
46
     * @inheritdoc
47
     */
48 1
    protected function additionalFailureDescription($other): string
49
    {
50 1
        $other = $this->convertToObject($other);
51
52 1
        $validator = new Validator();
53 1
        $validator->check($other, $this->schema);
54
55 1
        return \implode("\n", \array_map(function(array $error) {
56 1
            return \sprintf("[%s] %s", $error['property'], $error['message']);
57 1
        }, $validator->getErrors()));
58
    }
59
60
    /**
61
     * @param mixed $value
62
     *
63
     * @return \stdClass
64
     */
65 11
    private function convertToObject($value): \stdClass
66
    {
67 11
        if (\is_string($value)) {
68 4
            return \json_decode($value);
69
        }
70
71 11
        return \json_decode(\json_encode($value));
72
    }
73
}
74