1 | <?php |
||
2 | |||
3 | declare(strict_types=1); |
||
4 | |||
5 | namespace Cycle\ORM\Collection; |
||
6 | |||
7 | use Cycle\ORM\Collection\Pivoted\PivotedCollection; |
||
8 | use Cycle\ORM\Collection\Pivoted\PivotedStorage; |
||
9 | use Cycle\ORM\Exception\CollectionFactoryException; |
||
10 | use Doctrine\Common\Collections\ArrayCollection; |
||
11 | use Doctrine\Common\Collections\Collection; |
||
12 | |||
13 | /** |
||
14 | * Stores related items doctrine collection. |
||
15 | * Items and Pivots for `Many to Many` relation stores in {@see PivotedCollection}. |
||
16 | * |
||
17 | * @template TCollection of Collection |
||
18 | * |
||
19 | * @template-implements CollectionFactoryInterface<TCollection> |
||
20 | */ |
||
21 | final class DoctrineCollectionFactory implements CollectionFactoryInterface |
||
22 | 7416 | { |
|
23 | public function __construct() |
||
24 | 7416 | { |
|
25 | if (!class_exists(ArrayCollection::class, true)) { |
||
26 | throw new CollectionFactoryException( |
||
27 | sprintf( |
||
28 | 'There is no %s class. To resolve this issue you can install `doctrine/collections` package.', |
||
29 | ArrayCollection::class |
||
30 | ) |
||
31 | ); |
||
32 | } |
||
33 | } |
||
34 | |||
35 | /** @var class-string<TCollection> */ |
||
0 ignored issues
–
show
Documentation
Bug
introduced
by
Loading history...
|
|||
36 | private string $class = ArrayCollection::class; |
||
37 | 194 | ||
38 | public function getInterface(): ?string |
||
39 | 194 | { |
|
40 | return Collection::class; |
||
41 | } |
||
42 | 18 | ||
43 | public function withCollectionClass(string $class): static |
||
44 | 18 | { |
|
45 | 18 | $clone = clone $this; |
|
46 | 18 | $clone->class = $class === Collection::class ? ArrayCollection::class : $class; |
|
47 | return $clone; |
||
48 | } |
||
49 | 1802 | ||
50 | public function collect(iterable $data): Collection |
||
51 | 1802 | { |
|
52 | 604 | if ($data instanceof PivotedStorage) { |
|
53 | 602 | if ($this->class === ArrayCollection::class) { |
|
54 | return new PivotedCollection($data->getElements(), $data->getContext()); |
||
55 | } |
||
56 | 2 | ||
57 | if (is_a($this->class, PivotedCollection::class)) { |
||
58 | return new $this->class($data->getElements(), $data->getContext()); |
||
59 | } |
||
60 | } |
||
61 | 1240 | ||
62 | 1240 | $data = match (true) { |
|
63 | 6 | \is_array($data) => $data, |
|
64 | $data instanceof \Traversable => \iterator_to_array($data), |
||
65 | default => throw new CollectionFactoryException('Unsupported iterable type.'), |
||
66 | }; |
||
67 | 1240 | ||
68 | return new $this->class($data); |
||
69 | } |
||
70 | } |
||
71 |