-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathIsList.php
78 lines (65 loc) · 1.76 KB
/
IsList.php
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
<?php
declare(strict_types=1);
namespace PHPUnitExtraConstraints\Constraint;
use Generator;
use PHPUnit\Framework\Constraint\Constraint;
use SebastianBergmann\Diff\Differ;
use SebastianBergmann\Diff\Output\UnifiedDiffOutputBuilder;
use function is_iterable;
/**
* Constraint that asserts that the value is a sequential list
*/
final class IsList extends Constraint
{
/** @var bool */
private $acceptsGenerator;
public function __construct(bool $acceptsGenerator = false)
{
$this->acceptsGenerator = $acceptsGenerator;
}
/**
* @inheritDoc
*/
protected function matches($other): bool
{
if (!is_iterable($other) || (!$this->acceptsGenerator && $other instanceof Generator)) {
return false;
}
$expectedIndex = 0;
foreach ($other as $k => $_) {
if ($k !== $expectedIndex) {
return false;
}
$expectedIndex++;
}
return true;
}
/**
* @inheritDoc
*/
protected function additionalFailureDescription($other): string
{
if (!is_iterable($other) || (!$this->acceptsGenerator && $other instanceof Generator)) {
return '';
}
$expectedIndex = 0;
foreach ($other as $k => $_) {
if ($k !== $expectedIndex) {
return (new Differ(new UnifiedDiffOutputBuilder("--- Expected\n+++ Actual\n")))
->diff("index: $expectedIndex", "index: $k");
}
$expectedIndex++;
}
// Cannot happen
// @codeCoverageIgnoreStart
return '';
// @codeCoverageIgnoreEnd
}
/**
* @inheritDoc
*/
public function toString(): string
{
return 'is a list';
}
}