Passed
Push — 1.0.x ( f191a2...77ca84 )
by Koldo
10:16
created

InCollectionMatchingSegment   A

Complexity

Total Complexity 12

Size/Duplication

Total Lines 74
Duplicated Lines 0 %

Test Coverage

Coverage 65.38%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 24
c 1
b 0
f 0
dl 0
loc 74
ccs 17
cts 26
cp 0.6538
rs 10
wmc 12

7 Methods

Rating   Name   Duplication   Size   Complexity  
A id() 0 3 1
A __construct() 0 4 1
A toArray() 0 5 1
A jsonSerialize() 0 3 1
A criteria() 0 3 1
A isAMatch() 0 7 2
A match() 0 18 5
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Pheature\Model\Toggle;
6
7
use Pheature\Core\Toggle\Read\Segment;
8
9
class InCollectionMatchingSegment implements Segment
10
{
11
    public const NAME = 'in_collection_matching_segment';
12
    private string $id;
13
    /** @var array<string, mixed> */
14
    private array $criteria;
15
16
    /**
17
     * InCollectionMatchingSegment constructor.
18
     *
19
     * @param string $id
20
     * @param array<string, mixed> $criteria
21
     */
22 9
    public function __construct(string $id, array $criteria)
23
    {
24 9
        $this->id = $id;
25 9
        $this->criteria = $criteria;
26 9
    }
27
28
    public function id(): string
29
    {
30
        return $this->id;
31
    }
32
33
    public function criteria(): array
34
    {
35
        return $this->criteria;
36
    }
37
38 8
    public function match(array $payload): bool
39
    {
40 8
        if (empty($this->criteria)) {
41 1
            return false;
42
        }
43
44
        /** @var mixed $criterionValue */
45 7
        foreach ($this->criteria as $field => $criterionValue) {
46 7
            if (!array_key_exists($field, $payload)) {
47 1
                return false;
48
            }
49
50 7
            if (!$this->isAMatch($payload[$field], $criterionValue)) {
51 3
                return false;
52
            }
53
        }
54
55 3
        return true;
56
    }
57
58
    /**
59
     * @param mixed $payloadValue
60
     * @param mixed $criterionValue
61
     * @return bool
62
     */
63 7
    private function isAMatch($payloadValue, $criterionValue): bool
64
    {
65 7
        if (is_array($criterionValue)) {
66 5
            return in_array($payloadValue, $criterionValue, true);
67
        }
68
69 4
        return $payloadValue === $criterionValue;
70
    }
71
72
    public function toArray(): array
73
    {
74
        return [
75
            'id' => $this->id,
76
            'criteria' => $this->criteria,
77
        ];
78
    }
79
80
    public function jsonSerialize()
81
    {
82
        return $this->toArray();
83
    }
84
}
85