Test Setup Failed
Push — master ( aeb8b5...c4a9e3 )
by Alexpts
07:44
created

Collection::getItems()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 10
ccs 5
cts 5
cp 1
rs 9.9332
c 0
b 0
f 0
cc 2
nc 2
nop 1
crap 2
1
<?php
2
declare(strict_types = 1);
3
4
namespace PTS\Tools;
5
6
class Collection implements CollectionInterface
7
{
8
    protected array $items = [];
0 ignored issues
show
Bug introduced by
This code did not parse for me. Apparently, there is an error somewhere around this line:

Syntax error, unexpected T_ARRAY, expecting T_FUNCTION or T_CONST
Loading history...
9
10
    public function addItem(string $name, mixed $item, int $priority = 50): static
11
    {
12
        if ($this->has($name)) {
13
            throw new DuplicateKeyException('Item with name '.$name.' already defined');
14
        }
15
16
        $this->items[$priority][$name] = $item;
17
        return $this;
18
    }
19
20 8
    public function removeItem(string $name, int $priority = null): static
21
    {
22 8
        if ($priority === null) {
23 1
            return $this->removeItemWithoutPriority($name);
24
        }
25
26 8
        if ($this->items[$priority][$name] ?? false) {
27 8
            unset($this->items[$priority][$name]);
28
        }
29
30
        return $this;
31
    }
32
33
    protected function removeItemWithoutPriority(string $name): static
34
    {
35
        foreach ($this->items as $priority => $items) {
36 2
            if ($items[$name] ?? false) {
37
                unset($this->items[$priority][$name]);
38 2
            }
39 1
        }
40 1
41
        return $this;
42
    }
43 1
44
    public function has(string $name): bool
45
    {
46 1
        foreach ($this->items as $items) {
47
            if ($items[$name] ?? false) {
48
                return true;
49
            }
50
        }
51
52
        return false;
53
    }
54 1
55
    /**
56 1
     * @param bool $sort
57 1
     * @return array[]
58 1
     */
59
    public function getItems(bool $sort = true): array
60
    {
61
        $items = $this->items;
62 1
63
        if ($sort) {
64
            krsort($items, SORT_NUMERIC);
65 8
        }
66
67 8
        return $items;
68 3
    }
69 3
70
    public function getFlatItems(bool $sort = true): array
71
    {
72
        $flatItems = [];
73 8
74
        foreach ($this->getItems($sort) as $items) {
75
            foreach ($items as $name => $item) {
76
                $flatItems[$name] = $item;
77
            }
78
        }
79
80 7
        return $flatItems;
81
    }
82 7
83
    /**
84 7
     * @return $this
85 7
     */
86
    public function flush(): static
87
    {
88 7
        $this->items = [];
89
        return $this;
90
    }
91
}
92