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

ContainsOnlyAllowedMembersConstraint   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 47
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 6
eloc 12
c 1
b 0
f 0
dl 0
loc 47
rs 10
ccs 14
cts 14
cp 1

3 Methods

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