CollectionTrait   A
last analyzed

Complexity

Total Complexity 6

Size/Duplication

Total Lines 69
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 6
eloc 13
dl 0
loc 69
ccs 17
cts 17
cp 1
rs 10
c 0
b 0
f 0

5 Methods

Rating   Name   Duplication   Size   Complexity  
A getAll() 0 3 1
A get() 0 4 1
A has() 0 3 1
A getFilteredItem() 0 14 2
A count() 0 3 1
1
<?php
2
declare(strict_types = 1);
3
/**
4
 * /src/Collection/CollectionTrait.php
5
 *
6
 * @author TLe, Tarmo Leppänen <[email protected]>
7
 */
8
9
namespace App\Collection;
10
11
use CallbackFilterIterator;
12
use Closure;
13
use InvalidArgumentException;
14
use IteratorAggregate;
15
use IteratorIterator;
16
use Throwable;
17
use function iterator_count;
18
19
/**
20
 * Trait CollectionTrait
21
 *
22
 * @package App\Collection
23
 * @author TLe, Tarmo Leppänen <[email protected]>
24
 */
25
trait CollectionTrait
26
{
27
    /**
28
     * Method to filter current collection.
29
     *
30
     * @psalm-var class-string $className
31
     */
32
    abstract public function filter(string $className): Closure;
33
34
    /**
35
     * Method to process error message for current collection.
36
     *
37
     * @psalm-var class-string $className
38
     *
39
     * @throws InvalidArgumentException
40
     */
41
    abstract public function getErrorMessage(string $className): string;
42
43
    /**
44
     * Getter method for given class for current collection.
45
     *
46
     * @throws InvalidArgumentException
47
     */
48 92
    public function get(string $className): mixed
49
    {
50 92
        return $this->getFilteredItem($className)
51 92
            ?? throw new InvalidArgumentException($this->getErrorMessage($className));
52
    }
53
54
    /**
55
     * Method to get all items from current collection.
56
     *
57
     * @return IteratorAggregate<mixed>
58
     */
59 2
    public function getAll(): IteratorAggregate
60
    {
61 2
        return $this->items;
62
    }
63
64
    /**
65
     * Method to check if specified class exists or not in current collection.
66
     */
67 95
    public function has(?string $className = null): bool
68
    {
69 95
        return $this->getFilteredItem($className ?? '') !== null;
70
    }
71
72
    /**
73
     * Count elements of an object.
74
     */
75 1
    public function count(): int
76
    {
77 1
        return iterator_count($this->items);
78
    }
79
80 113
    private function getFilteredItem(string $className): mixed
81
    {
82
        try {
83 113
            $iterator = $this->items->getIterator();
84 1
        } catch (Throwable $throwable) {
85 1
            $this->logger->error($throwable->getMessage());
86
87 1
            return null;
88
        }
89
90 112
        $filteredIterator = new CallbackFilterIterator(new IteratorIterator($iterator), $this->filter($className));
91 112
        $filteredIterator->rewind();
92
93 112
        return $filteredIterator->current();
94
    }
95
}
96