ItemBagTrait::count()   A
last analyzed

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 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 2
cts 2
cp 1
crap 1
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace RedRat\Presenthor\Bag;
6
7
use RedRat\Presenthor\Item\ItemInterface;
8
9
/**
10
 * Item Bag Trait
11
 *
12
 * @package RedRat\Bag
13
 */
14
trait ItemBagTrait
15
{
16
    /**
17
     * @var ItemInterface[]
18
     */
19
    private $items;
20
21
    /**
22
     * Item Bag Trait constructor
23
     */
24 13
    public function __construct()
25
    {
26 13
        $this->items = [];
27 13
    }
28
29
    /**
30
     * {@inheritDoc}
31
     */
32 12
    public function addItem(ItemInterface $item, bool $acceptDuplicate = false): bool
33
    {
34 12
        if ($this->hasItem($item) && !$acceptDuplicate) {
35 3
            return false;
36
        }
37
38 12
        $this->items[] = $item;
39 12
        return true;
40
    }
41
42
    /**
43
     * {@inheritDoc}
44
     */
45 13
    public function hasItem(ItemInterface $item): bool
46
    {
47 13
        return \in_array($item, $this->items);
48
    }
49
50
    /**
51
     * {@inheritDoc}
52
     */
53 2
    public function removeItem(ItemInterface $item): bool
54
    {
55 2
        if (!$this->hasItem($item)) {
56 1
            return false;
57
        }
58
59 1
        $itemKey = \array_search($item, $this->items);
60 1
        unset($this->items[$itemKey]);
61
        
62 1
        return true;
63
    }
64
65
    /**
66
     * {@inheritDoc}
67
     */
68 1
    public function getItemsList(): array
69
    {
70 1
        return $this->items;
71
    }
72
73
    /**
74
     * {@inheritDoc}
75
     */
76 1
    public function clearItems(): void
77
    {
78 1
        $this->items = [];
79 1
    }
80
81
    /**
82
     * {@inheritDoc}
83
     */
84 9
    public function countItems(): int
85
    {
86 9
        return \count($this->items);
87
    }
88
89
    /**
90
     * {@inheritDoc}
91
     */
92 9
    public function count(): int
93
    {
94 9
        return $this->countItems();
95
    }
96
97
    /**
98
     * {@inheritDoc}
99
     */
100 1
    public function toArray(): array
101
    {
102 1
        $returnData = [];
103
104 1
        foreach ($this->items as $item) {
105 1
            $returnData[] = $item->toArray();
106
        }
107
108 1
        return $returnData;
109
    }
110
111
    /**
112
     * {@inheritDoc}
113
     */
114 1
    public function toJson(): string
115
    {
116 1
        return \json_encode($this->toArray());
117
    }
118
}
119