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

InCollectionMatchingSegment::criteria()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
c 1
b 0
f 0
nc 1
nop 0
dl 0
loc 3
ccs 0
cts 2
cp 0
crap 2
rs 10
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