|
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
|
|
|
* @template-implements CollectionFactoryInterface<TCollection> |
|
19
|
|
|
*/ |
|
20
|
|
|
final class DoctrineCollectionFactory implements CollectionFactoryInterface |
|
21
|
|
|
{ |
|
22
|
7416 |
|
public function __construct() |
|
23
|
|
|
{ |
|
24
|
7416 |
|
if (!class_exists(ArrayCollection::class, true)) { |
|
25
|
|
|
throw new CollectionFactoryException( |
|
26
|
|
|
sprintf( |
|
27
|
|
|
'There is no %s class. To resolve this issue you can install `doctrine/collections` package.', |
|
28
|
|
|
ArrayCollection::class |
|
29
|
|
|
) |
|
30
|
|
|
); |
|
31
|
|
|
} |
|
32
|
|
|
} |
|
33
|
|
|
|
|
34
|
|
|
/** @var class-string<TCollection> */ |
|
|
|
|
|
|
35
|
|
|
private string $class = ArrayCollection::class; |
|
36
|
|
|
|
|
37
|
194 |
|
public function getInterface(): ?string |
|
38
|
|
|
{ |
|
39
|
194 |
|
return Collection::class; |
|
40
|
|
|
} |
|
41
|
|
|
|
|
42
|
18 |
|
public function withCollectionClass(string $class): static |
|
43
|
|
|
{ |
|
44
|
18 |
|
$clone = clone $this; |
|
45
|
18 |
|
$clone->class = $class === Collection::class ? ArrayCollection::class : $class; |
|
46
|
18 |
|
return $clone; |
|
47
|
|
|
} |
|
48
|
|
|
|
|
49
|
1802 |
|
public function collect(iterable $data): Collection |
|
50
|
|
|
{ |
|
51
|
1802 |
|
if ($data instanceof PivotedStorage) { |
|
52
|
604 |
|
if ($this->class === ArrayCollection::class) { |
|
53
|
602 |
|
return new PivotedCollection($data->getElements(), $data->getContext()); |
|
54
|
|
|
} |
|
55
|
|
|
|
|
56
|
2 |
|
if (is_a($this->class, PivotedCollection::class)) { |
|
57
|
|
|
return new $this->class($data->getElements(), $data->getContext()); |
|
58
|
|
|
} |
|
59
|
|
|
} |
|
60
|
|
|
|
|
61
|
1240 |
|
$data = match (true) { |
|
62
|
1240 |
|
\is_array($data) => $data, |
|
63
|
6 |
|
$data instanceof \Traversable => \iterator_to_array($data), |
|
64
|
|
|
default => throw new CollectionFactoryException('Unsupported iterable type.'), |
|
65
|
|
|
}; |
|
66
|
|
|
|
|
67
|
1240 |
|
return new $this->class($data); |
|
68
|
|
|
} |
|
69
|
|
|
} |
|
70
|
|
|
|