CollectionTrait   A
last analyzed

Complexity

Total Complexity 5

Size/Duplication

Total Lines 24
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 7
dl 0
loc 24
ccs 9
cts 9
cp 1
rs 10
c 1
b 0
f 0
wmc 5

4 Methods

Rating   Name   Duplication   Size   Complexity  
A toArray() 0 3 1
A isEmpty() 0 3 1
A count() 0 3 1
A getIterator() 0 4 2
1
<?php declare(strict_types=1);
2
3
namespace jschreuder\MiddleAuth\Util;
4
5
use Iterator;
6
7
/**
8
 * Trait for creating type-safe collections of entities.
9
 *
10
 * Implementing classes must:
11
 * 1. Store entities in a private array property named $collection
12
 * 2. Implement a constructor that accepts variadic entities and assigns them to $this->collection
13
 *
14
 * Example implementation:
15
 * ```
16
 * final class UserCollection implements IteratorAggregate
17
 * {
18
 *     use CollectionTrait;
19
 *
20
 *     public function __construct(
21
 *         private array $collection = [],
22
 *     ) {}
23
 * }
24
 * ```
25
 */
26
trait CollectionTrait
27
{
28
    private array $collection;
29
30 34
    public function getIterator(): Iterator
31
    {
32 34
        foreach ($this->collection as $item) {
33 25
            yield $item;
34
        }
35
    }
36
37 39
    public function count(): int
38
    {
39 39
        return count($this->collection);
40
    }
41
42 11
    public function isEmpty(): bool
43
    {
44 11
        return empty($this->collection);
45
    }
46
47 3
    public function toArray(): array
48
    {
49 3
        return $this->collection;
50
    }
51
}
52