1
|
|
|
<?php |
2
|
|
|
/** |
3
|
|
|
* Copyright (c) 2020. |
4
|
|
|
* @author Paweł Antosiak <[email protected]> |
5
|
|
|
*/ |
6
|
|
|
|
7
|
|
|
declare(strict_types=1); |
8
|
|
|
|
9
|
|
|
namespace Gorynych\Testing\Constraint; |
10
|
|
|
|
11
|
|
|
use PHPUnit\Framework\Constraint\Constraint; |
12
|
|
|
use SebastianBergmann\Comparator\ComparisonFailure; |
13
|
|
|
|
14
|
|
|
final class ContainsSubset extends Constraint |
15
|
|
|
{ |
16
|
|
|
/** @var mixed */ |
17
|
|
|
private $subset; |
18
|
|
|
private bool $strict; |
19
|
|
|
|
20
|
|
|
/** |
21
|
|
|
* @param mixed $subset |
22
|
|
|
*/ |
23
|
|
|
public function __construct($subset, bool $strict = false) |
24
|
|
|
{ |
25
|
|
|
$this->strict = $strict; |
26
|
|
|
$this->subset = $subset; |
27
|
|
|
} |
28
|
|
|
|
29
|
|
|
/** |
30
|
|
|
* {@inheritdoc} |
31
|
|
|
* @param mixed $other |
32
|
|
|
*/ |
33
|
|
|
public function evaluate($other, string $description = '', bool $returnResult = false): ?bool |
34
|
|
|
{ |
35
|
|
|
$other = $this->toArray($other); |
36
|
|
|
$this->subset = $this->toArray($this->subset); |
37
|
|
|
$patched = array_replace_recursive($other, $this->subset); |
38
|
|
|
|
39
|
|
|
if (true === $this->strict) { |
40
|
|
|
$result = $other === $patched; |
41
|
|
|
} else { |
42
|
|
|
$result = $other == $patched; |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
if (true === $returnResult) { |
46
|
|
|
return $result; |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
if (true === $result) { |
50
|
|
|
return null; |
51
|
|
|
} |
52
|
|
|
|
53
|
|
|
$failure = new ComparisonFailure( |
54
|
|
|
$patched, |
55
|
|
|
$other, |
56
|
|
|
var_export($patched, true), |
57
|
|
|
var_export($other, true) |
58
|
|
|
); |
59
|
|
|
|
60
|
|
|
$this->fail($other, $description, $failure); |
61
|
|
|
|
62
|
|
|
return null; |
63
|
|
|
} |
64
|
|
|
|
65
|
|
|
/** |
66
|
|
|
* {@inheritdoc} |
67
|
|
|
*/ |
68
|
|
|
public function toString(): string |
69
|
|
|
{ |
70
|
|
|
return 'has the subset ' . $this->exporter()->export($this->subset); |
71
|
|
|
} |
72
|
|
|
|
73
|
|
|
/** |
74
|
|
|
* {@inheritdoc} |
75
|
|
|
*/ |
76
|
|
|
protected function failureDescription($other): string |
77
|
|
|
{ |
78
|
|
|
return 'an array ' . $this->toString(); |
79
|
|
|
} |
80
|
|
|
|
81
|
|
|
/** |
82
|
|
|
* @param mixed $other |
83
|
|
|
* @return mixed[] |
84
|
|
|
*/ |
85
|
|
|
private function toArray($other): array |
86
|
|
|
{ |
87
|
|
|
if (is_array($other)) { |
88
|
|
|
return $other; |
89
|
|
|
} |
90
|
|
|
|
91
|
|
|
if ($other instanceof \ArrayObject) { |
92
|
|
|
return $other->getArrayCopy(); |
93
|
|
|
} |
94
|
|
|
|
95
|
|
|
if ($other instanceof \Traversable) { |
96
|
|
|
return iterator_to_array($other); |
97
|
|
|
} |
98
|
|
|
|
99
|
|
|
// Keep BC even if we know that array would not be the expected one |
100
|
|
|
return (array) $other; |
101
|
|
|
} |
102
|
|
|
} |
103
|
|
|
|