forked from martin-helmich/phpunit-json-assert
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJsonValueMatches.php
More file actions
103 lines (88 loc) · 2.93 KB
/
JsonValueMatches.php
File metadata and controls
103 lines (88 loc) · 2.93 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
<?php
namespace Sid\JsonAssert\Constraint;
use Flow\JSONPath\JSONPath;
use PHPUnit\Framework\Constraint\Constraint;
/**
* A simple constraints that asserts that a single value of a JSON document
* matches a given constraint.
*
* @package Sid\JsonAssert
* @subpackage Constraint
*/
class JsonValueMatches extends Constraint
{
/** @var string */
private $jsonPath;
/** @var Constraint */
private $constraint;
/** @var bool */
private $matchAll;
/**
* JsonValueMatches constructor.
*
* @param string $jsonPath The JSON path that identifies the value(s)
* in the JSON document that the constraint
* should match
* @param Constraint $constraint The actual constraint that the selected
* value(s) must match
* @param bool $matchAll This flag controls how this constraint
* handles multiple values. Usually, this
* constraint will match successfully, when
* (at least) one found value matches the
* given constraint. When this flag is set,
* _all_ found values must match the
* constraint.
*/
public function __construct(string $jsonPath, Constraint $constraint, bool $matchAll = false)
{
$this->jsonPath = $jsonPath;
$this->constraint = $constraint;
$this->matchAll = $matchAll;
}
/**
* Returns a string representation of the object.
*
* @return string
*/
public function toString(): string
{
return "matches " . $this->constraint->toString() . " at JSON path '{$this->jsonPath}'";
}
/**
* @inheritdoc
*/
protected function matches($other): bool
{
if (is_string($other)) {
$other = json_decode($other, true);
}
$result = (new JSONPath($other))->find($this->jsonPath);
if (!isset($result[0])) {
return false;
}
$combineFunc = $this->buildCombinationFunction();
$matches = null;
foreach ($result as $v) {
if ($v instanceof JSONPath) {
$v = $v->getData();
}
$singleMatchResult = $this->constraint->evaluate($v, '', true);
$matches = $combineFunc($matches, $singleMatchResult);
}
return $matches;
}
/**
* @return callable
*/
protected function buildCombinationFunction(): callable
{
if ($this->matchAll) {
return function ($first, $second) {
return ($first === null) ? $second : $first && $second;
};
}
return function ($first, $second) {
return ($first === null) ? $second : $first || $second;
};
}
}