ArrayCollectionFactory   A
last analyzed

Complexity

Total Complexity 3

Size/Duplication

Total Lines 21
Duplicated Lines 0 %

Test Coverage

Coverage 75%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 7
dl 0
loc 21
ccs 6
cts 8
cp 0.75
rs 10
c 1
b 0
f 0
wmc 3

3 Methods

Rating   Name   Duplication   Size   Complexity  
A withCollectionClass() 0 3 1
A getInterface() 0 3 1
A collect() 0 6 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Cycle\ORM\Collection;
6
7
use Cycle\ORM\Exception\CollectionFactoryException;
8
9
/**
10
 * Stores related items to array.
11
 * In the case of a relation loaded lazily in a proxy mapper,
12
 * you should note that writing to such array collection should take place after an overloading:
13
 *
14
 *     // {$user->posts} is not loaded
15
 *
16
 *     // Bad code:
17
 *     // Exception or notice will be thrown
18
 *     // because the {$user->posts} value comes from a __get method.
19
 *     $user->posts[] = new Post;
20
 *
21
 *
22
 *     // Bad code:
23
 *     // Exception or notice will be thrown
24
 *     // because the {$user->posts} value comes from a __get method.
25
 *     $posts = &$user->posts;
26
 *
27
 *
28
 *     // Correct example:
29
 *     $user->post; // Resolve relation. It can be any `reading` code
30
 *     $user->post[] = new Post;
31
 *
32
 * @template TCollection of array
33
 *
34
 * @template-implements CollectionFactoryInterface<TCollection>
35
 */
36
final class ArrayCollectionFactory implements CollectionFactoryInterface
37 7406
{
38
    public function getInterface(): ?string
39 7406
    {
40
        return null;
41
    }
42
43
    /**
44
     * @psalm-param string $class
45
     */
46
    public function withCollectionClass(string $class): static
47
    {
48
        return $this;
49
    }
50 114
51
    public function collect(iterable $data): array
52
    {
53 114
        return match (true) {
54 52
            \is_array($data) => $data,
55 114
            $data instanceof \Traversable => \iterator_to_array($data),
56
            default => throw new CollectionFactoryException('Unsupported iterable type.'),
57
        };
58
    }
59
}
60