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

ContainsAtLeastOneConstraint   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 59
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
eloc 13
dl 0
loc 59
ccs 16
cts 16
cp 1
rs 10
c 0
b 0
f 0
wmc 7

4 Methods

Rating   Name   Duplication   Size   Complexity  
A check() 0 3 1
A matches() 0 13 4
A toString() 0 5 1
A __construct() 0 3 1
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