KeysMatch::matches()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 4
c 1
b 0
f 0
dl 0
loc 8
rs 10
cc 3
nc 3
nop 2
1
<?php declare(strict_types=1);
2
3
namespace Stratadox\Proxy\When;
4
5
use Stratadox\Specification\Contract\Satisfiable;
6
7
/**
8
 * When\KeysMatch. Constraint to check if the known data matches with any set of
9
 * key/value pairs in a list of such sets.
10
 *
11
 * @author Stratadox
12
 */
13
final class KeysMatch implements Satisfiable
14
{
15
    private $canMatchWith;
16
17
    private function __construct(array ...$canMatchWith)
18
    {
19
        $this->canMatchWith = $canMatchWith;
20
    }
21
22
    /**
23
     * Produces a constraint that is satisfied with data that contains all the
24
     * key/value pairs in one of the given key/value pair sets.
25
     *
26
     * @param array ...$canMatchWith The key/value pair sets.
27
     * @return Satisfiable           The constraint.
28
     */
29
    public static function withEitherOf(array ...$canMatchWith): Satisfiable
30
    {
31
        return new self(...$canMatchWith);
32
    }
33
34
    /** @inheritdoc */
35
    public function isSatisfiedBy($knownData): bool
36
    {
37
        foreach ($this->canMatchWith as $set) {
38
            if ($this->matches($knownData, $set)) {
39
                return true;
40
            }
41
        }
42
        return false;
43
    }
44
45
    private function matches(array $knownData, array $set): bool
46
    {
47
        foreach ($set as $key => $value) {
48
            if (($knownData[$key] ?? null) !== $value) {
49
                return false;
50
            }
51
        }
52
        return true;
53
    }
54
}
55