1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace VGirol\JsonApiAssert\Constraint; |
6
|
|
|
|
7
|
|
|
use PHPUnit\Framework\Constraint\Constraint; |
8
|
|
|
|
9
|
|
|
/** |
10
|
|
|
* A constraint class to assert that a link object equals an expected value. |
11
|
|
|
*/ |
12
|
|
|
class LinkEqualsConstraint extends Constraint |
13
|
|
|
{ |
14
|
|
|
/** |
15
|
|
|
* @var string|null |
16
|
|
|
*/ |
17
|
|
|
private $expected; |
18
|
|
|
|
19
|
|
|
/** |
20
|
|
|
* Class constructor. |
21
|
|
|
* |
22
|
|
|
* @param string|null $expected |
23
|
|
|
*/ |
24
|
|
|
public function __construct($expected) |
25
|
|
|
{ |
26
|
|
|
$this->expected = $expected; |
27
|
|
|
} |
28
|
|
|
|
29
|
|
|
/** |
30
|
|
|
* Returns a string representation of the constraint. |
31
|
|
|
*/ |
32
|
|
|
public function toString(): string |
33
|
|
|
{ |
34
|
|
|
return \sprintf( |
35
|
|
|
'equals %s', |
36
|
|
|
$this->exporter()->export($this->expected) |
37
|
|
|
); |
38
|
|
|
} |
39
|
|
|
|
40
|
|
|
/** |
41
|
|
|
* Evaluates the constraint for parameter $other. Returns true if the |
42
|
|
|
* constraint is met, false otherwise. |
43
|
|
|
* |
44
|
|
|
* @param mixed $other value or object to evaluate |
45
|
|
|
*/ |
46
|
|
|
protected function matches($other): bool |
47
|
|
|
{ |
48
|
|
|
if (is_null($this->expected)) { |
49
|
|
|
return \is_null($other); |
50
|
|
|
} |
51
|
|
|
|
52
|
|
|
if (is_null($other)) { |
53
|
|
|
return false; |
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
$linkElms = explode('?', $other); |
57
|
|
|
$expectedElms = explode('?', $this->expected); |
58
|
|
|
|
59
|
|
|
if (count($expectedElms) != count($linkElms)) { |
60
|
|
|
return false; |
61
|
|
|
} |
62
|
|
|
|
63
|
|
|
if ($expectedElms[0] != $linkElms[0]) { |
64
|
|
|
return false; |
65
|
|
|
} |
66
|
|
|
|
67
|
|
|
if (count($linkElms) == 1) { |
68
|
|
|
return true; |
69
|
|
|
} |
70
|
|
|
|
71
|
|
|
$expectedQuery = explode('&', $expectedElms[1]); |
72
|
|
|
$linkQuery = explode('&', $linkElms[1]); |
73
|
|
|
|
74
|
|
|
if (count($expectedQuery) != count($linkQuery)) { |
75
|
|
|
return false; |
76
|
|
|
} |
77
|
|
|
|
78
|
|
|
$diff = array_diff($expectedQuery, $linkQuery); |
79
|
|
|
|
80
|
|
|
return count($diff) === 0; |
81
|
|
|
} |
82
|
|
|
|
83
|
|
|
/** |
84
|
|
|
* Evaluates the constraint for parameter $other. Returns true if the |
85
|
|
|
* constraint is met, false otherwise. |
86
|
|
|
* |
87
|
|
|
* @param mixed $other value or object to evaluate |
88
|
|
|
* @return boolean |
89
|
|
|
*/ |
90
|
|
|
public function check($other): bool |
91
|
|
|
{ |
92
|
|
|
return $this->matches($other); |
93
|
|
|
} |
94
|
|
|
} |
95
|
|
|
|