Passed
Pull Request — 5.x (#26)
by Enjoys
04:01 queued 01:55
created

AttributeCollection::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 2
Code Lines 0

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 1
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 1
Metric Value
eloc 0
c 1
b 0
f 1
dl 0
loc 2
ccs 1
cts 1
cp 1
rs 10
cc 1
nc 1
nop 0
crap 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Enjoys\Forms;
6
7
use Enjoys\Forms\Interfaces\AttributeInterface;
8
9
/**
10
 * @psalm-suppress MissingTemplateParam
11
 */
12
final class AttributeCollection implements \Countable, \IteratorAggregate
13
{
14
    /**
15
     * @var AttributeInterface[]
16
     */
17
    private array $collection = [];
18
19 339
    public function __construct()
20
    {
21 339
    }
22
23 6
    public function count(): int
24
    {
25 6
        return count($this->collection);
26
    }
27
28 339
    public function has(AttributeInterface $attribute): bool
29
    {
30 339
        foreach ($this->collection as $item) {
31 328
            if ($item->getName() === $attribute->getName()) {
32 5
                return true;
33
            }
34
        }
35 339
        return false;
36
    }
37
38 339
    public function add(AttributeInterface $attribute): AttributeCollection
39
    {
40 339
        if (!$this->has($attribute)) {
41 339
            $this->collection[] = $attribute;
42
        }
43 339
        return $this;
44
    }
45
46 175
    public function get(string $name): AttributeInterface|null
47
    {
48 175
        foreach ($this->collection as $item) {
49 173
            if ($item->getName() === $name) {
50 141
                return $item;
51
            }
52
        }
53 105
        return null;
54
    }
55
56 2
    public function clear(): void
57
    {
58 2
        $this->collection = [];
59
    }
60
61 325
    public function remove(string|AttributeInterface $element): AttributeCollection
62
    {
63 325
        $attributeName = ($element instanceof AttributeInterface) ? $element->getName() : $element;
64
65 325
        foreach ($this->collection as $key => $item) {
66 319
            if ($item->getName() === $attributeName) {
67 217
                unset($this->collection[$key]);
68 217
                return $this;
69
            }
70
        }
71
72 322
        return $this;
73
    }
74
75 1
    public function replace(AttributeInterface $attribute): AttributeCollection
76
    {
77 1
        $this->remove($attribute->getName());
78
79 1
        return $this->add($attribute);
80
    }
81
82 58
    public function __toString(): string
83
    {
84 58
        return implode(' ', array_filter($this->collection, fn($item) => !empty($item->__toString())));
85
    }
86
87
88 67
    public function getIterator(): \ArrayIterator
89
    {
90 67
        return new \ArrayIterator($this->collection);
91
    }
92
}
93