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

ContainsOnlyAllowedMembersConstraint::toString()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 3
nc 1
nop 0
dl 0
loc 5
ccs 4
cts 4
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 only members from the provided list.
10
 */
11
class ContainsOnlyAllowedMembersConstraint 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 107
    public function __construct(array $members)
24
    {
25 107
        $this->members = $members;
26 107
    }
27
28
    /**
29
     * Returns a string representation of the constraint.
30
     */
31 26
    public function toString(): string
32
    {
33 26
        return \sprintf(
34 26
            'contains only elements of "%s"',
35 26
            \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 107
    protected function matches($other): bool
46
    {
47 107
        if (!is_array($other)) {
48 1
            return false;
49
        }
50
51 106
        foreach (array_keys($other) as $key) {
52 106
            if (!in_array($key, $this->members)) {
53 27
                return false;
54
            }
55
        }
56
57 84
        return true;
58
    }
59
}
60