Passed
Pull Request — 2.x (#344)
by Pol
15:43
created

LoophpCollectionFactory::withCollectionClass()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 3
c 1
b 0
f 0
nc 2
nop 1
dl 0
loc 5
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Cycle\ORM\Collection;
6
7
use Cycle\ORM\Exception\CollectionFactoryException;
8
use loophp\collection\Collection;
9
use loophp\collection\Contract\Collection as CollectionInterface;
10
11
/**
12
 * @template TCollection of Collection
13
 * @template-implements CollectionFactoryInterface<TCollection>
14
 */
15
final class LoophpCollectionFactory implements CollectionFactoryInterface
16
{
17
    /** @var class-string<TCollection> */
0 ignored issues
show
Documentation Bug introduced by
The doc comment class-string<TCollection> at position 0 could not be parsed: Unknown type name 'class-string' at position 0 in class-string<TCollection>.
Loading history...
18
    private string $class = Collection::class;
19
20
    public function __construct()
21
    {
22
        if (!class_exists(Collection::class, true)) {
23
            throw new CollectionFactoryException(
24
                sprintf(
25
                    'There is no %s class. To resolve this issue you can install `loophp/collection` package.',
26
                    Collection::class
27
                )
28
            );
29
        }
30
    }
31
32
    public function getInterface(): ?string
33
    {
34
        return CollectionInterface::class;
35
    }
36
37
    public function withCollectionClass(string $class): static
38
    {
39
        $clone = clone $this;
40
        $clone->class = $class === Collection::class ? Collection::class : $class;
41
        return $clone;
42
    }
43
44
    public function collect(iterable $data): iterable
45
    {
46
        return ($this->class === Collection::class)
47
            ? Collection::fromIterable($data)
48
            : new $this->class($data);
49
    }
50
}
51