-
Notifications
You must be signed in to change notification settings - Fork 821
/
SSListContainsOnlyMatchingItems.php
90 lines (77 loc) · 2.29 KB
/
SSListContainsOnlyMatchingItems.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
79
80
81
82
83
84
85
86
87
88
89
90
<?php
namespace SilverStripe\Dev\Constraint;
// use PHPUnit_Framework_Constraint;
use PHPUnit\Framework\Constraint\Constraint;
// use PHPUnit_Framework_ExpectationFailedException;
use PHPUnit\Framework\ExpectationFailedException;
use SilverStripe\Dev\SSListExporter;
use SilverStripe\Dev\TestOnly;
use SilverStripe\ORM\SS_List;
if (!class_exists(Constraint::class)) {
return;
}
/**
* Constraint for checking if every item in a SS_List matches a given match,
* e.g. every Member has isActive set to true
*/
class SSListContainsOnlyMatchingItems extends Constraint implements TestOnly
{
/**
* @var array
*/
private $match;
/**
* @var ViewableDataContains
*/
private $constraint;
public function __construct($match)
{
$this->exporter = new SSListExporter();
$this->constraint = new ViewableDataContains($match);
$this->match = $match;
}
/**
* Evaluates the constraint for parameter $other
*
* If $returnResult is set to false (the default), an exception is thrown
* in case of a failure. null is returned otherwise.
*
* If $returnResult is true, the result of the evaluation is returned as
* a boolean value instead: true in case of success, false in case of a
* failure.
*
* @param SS_List $other Value or object to evaluate.
* @param string $description Additional information about the test
* @param bool $returnResult Whether to return a result or throw an exception
*
* @return null|bool
*
* @throws ExpectationFailedException
*/
public function evaluate($other, $description = '', $returnResult = false): ?bool
{
$success = true;
foreach ($other as $item) {
if (!$this->constraint->evaluate($item, '', true)) {
$success = false;
break;
}
}
if ($returnResult) {
return $success;
}
if (!$success) {
$this->fail($other, $description);
}
return null;
}
/**
* Returns a string representation of the object.
*
* @return string
*/
public function toString(): string
{
return 'contains only Objects where "' . key($this->match) . '" is "' . current($this->match) . '"';
}
}