Passed
Push — master ( 60c378...33ffe1 )
by Ondřej
02:20
created

DictionarySet::computeKey()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 4
nc 2
nop 1
dl 0
loc 6
rs 9.4285
c 0
b 0
f 0
1
<?php
2
declare(strict_types=1);
3
namespace Ivory\Data\Set;
4
5
/**
6
 * {@inheritdoc}
7
 *
8
 * This implementation:
9
 * - uses the PHP array type to store the data;
10
 * - stores `int`s as is, `serialize`()-ing other types of data.
11
 */
12
class DictionarySet implements ISet
13
{
14
    private $data = [];
15
16
    protected function computeKey($value)
17
    {
18
        if (is_int($value)) {
19
            return $value;
20
        } else {
21
            return serialize($value);
22
        }
23
    }
24
25
    //region ISet
26
27
    public function contains($value): bool
28
    {
29
        $key = $this->computeKey($value);
30
        return isset($this->data[$key]);
31
    }
32
33
    public function add($value): void
34
    {
35
        $key = $this->computeKey($value);
36
        $this->data[$key] = $value;
37
    }
38
39
    public function remove($value): void
40
    {
41
        $key = $this->computeKey($value);
42
        unset($this->data[$key]);
43
    }
44
45
    public function clear(): void
46
    {
47
        $this->data = [];
48
    }
49
50
    public function toArray(): array
51
    {
52
        return array_values($this->data);
53
    }
54
55
    public function generateItems(): \Generator
56
    {
57
        foreach ($this->data as $item) {
58
            yield $item;
59
        }
60
    }
61
62
    //endregion
63
64
    //region \Countable
65
66
    public function count()
67
    {
68
        return count($this->data);
69
    }
70
71
    //endregion
72
}
73