Passed
Push — 1.0.x ( 582123...077e14 )
by Koldo
02:53
created

InCollectionMatchingSegment::type()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 0
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
rs 10
c 0
b 0
f 0
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 8
    public function id(): string
29
    {
30 8
        return $this->id;
31
    }
32
33 8
    public function type(): string
34
    {
35 8
        return self::NAME;
36
    }
37
38 8
    public function criteria(): array
39
    {
40 8
        return $this->criteria;
41
    }
42
43 8
    public function match(array $payload): bool
44
    {
45 8
        if (empty($this->criteria)) {
46 1
            return false;
47
        }
48
49
        /** @var mixed $criterionValue */
50 7
        foreach ($this->criteria as $field => $criterionValue) {
51 7
            if (!array_key_exists($field, $payload)) {
52 1
                return false;
53
            }
54
55 7
            if (!$this->isAMatch($payload[$field], $criterionValue)) {
56 3
                return false;
57
            }
58
        }
59
60 3
        return true;
61
    }
62
63
    /**
64
     * @param mixed $payloadValue
65
     * @param mixed $criterionValue
66
     * @return bool
67
     */
68 7
    private function isAMatch($payloadValue, $criterionValue): bool
69
    {
70 7
        if (is_array($criterionValue)) {
71 5
            return in_array($payloadValue, $criterionValue, true);
72
        }
73
74 4
        return $payloadValue === $criterionValue;
75
    }
76
77 8
    public function toArray(): array
78
    {
79
        return [
80 8
            'id' => $this->id,
81 8
            'type' => self::NAME,
82 8
            'criteria' => $this->criteria,
83
        ];
84
    }
85
86 8
    public function jsonSerialize()
87
    {
88 8
        return $this->toArray();
89
    }
90
}
91