Completed
Push — master ( 316e9b...dc2c25 )
by Vincent
02:47
created

ContainsAtLeastOneConstraint::check()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
<?php
2
declare (strict_types = 1);
3
4
namespace VGirol\JsonApiAssert\Constraint;
5
6
use PHPUnit\Framework\Constraint\Constraint;
7
8
/**
9
 * A constraint class to assert that a json object contains at least one member from the provided list.
10
 */
11
class ContainsAtLeastOneConstraint extends Constraint
12
{
13
    /**
14
     * @var array<string>
15
     */
16
    private $members;
17
18
    /**
19
     * Class constructor.
20
     *
21
     * @param array<string> $members
22
     */
23 59
    public function __construct(array $members)
24
    {
25 59
        $this->members = $members;
26 59
    }
27
28
    /**
29
     * Returns a string representation of the constraint.
30
     */
31 9
    public function toString(): string
32
    {
33 9
        return \sprintf(
34 9
            'contains at least one element of "%s"',
35 9
            \implode(', ', $this->members)
36
        );
37
    }
38
39
    /**
40
     * Evaluates the constraint for parameter $other. Returns true if the
41
     * constraint is met, false otherwise.
42
     *
43
     * @param mixed $other value or object to evaluate
44
     */
45 59
    protected function matches($other): bool
46
    {
47 59
        if (!is_array($other)) {
48 1
            return false;
49
        }
50
51 58
        foreach ($this->members as $member) {
52 58
            if (array_key_exists($member, $other)) {
53 45
                return true;
54
            }
55
        }
56
57 14
        return false;
58
    }
59
60
    /**
61
     * Evaluates the constraint for parameter $other. Returns true if the
62
     * constraint is met, false otherwise.
63
     *
64
     * @param mixed $other value or object to evaluate
65
     * @return boolean
66
     */
67 13
    public function check($other): bool
68
    {
69 13
        return $this->matches($other);
70
    }
71
}
72