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

DictionarySet   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 57
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
dl 0
loc 57
rs 10
c 0
b 0
f 0
wmc 10

8 Methods

Rating   Name   Duplication   Size   Complexity  
A add() 0 4 1
A remove() 0 4 1
A contains() 0 4 1
A toArray() 0 3 1
A computeKey() 0 6 2
A count() 0 3 1
A generateItems() 0 4 2
A clear() 0 3 1
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