1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Malef\Associate\DoctrineOrm\Collector; |
4
|
|
|
|
5
|
|
|
use Doctrine\Common\Collections\ArrayCollection; |
6
|
|
|
use Malef\Associate\DoctrineOrm\Metadata\AssociationMetadataAdapter; |
7
|
|
|
use Malef\Associate\DoctrineOrm\Source\UniqueEntitySet; |
8
|
|
|
use Symfony\Component\PropertyAccess\PropertyAccessor; |
9
|
|
|
|
10
|
|
|
class AssociationCollector |
11
|
|
|
{ |
12
|
|
|
/** |
13
|
|
|
* @var PropertyAccessor |
14
|
|
|
*/ |
15
|
|
|
protected $propertyAccessor; |
16
|
|
|
|
17
|
|
|
public function __construct(PropertyAccessor $propertyAccessor) |
18
|
|
|
{ |
19
|
|
|
$this->propertyAccessor = $propertyAccessor; |
20
|
|
|
} |
21
|
|
|
|
22
|
|
|
public function collect( |
23
|
|
|
ArrayCollection $sourceEntities, |
24
|
|
|
AssociationMetadataAdapter $associationMetadataAdapter |
25
|
|
|
): ArrayCollection { |
26
|
|
|
return $associationMetadataAdapter->isToMany() |
27
|
|
|
? $this->collectToManyAssociation($sourceEntities, $associationMetadataAdapter) |
28
|
|
|
: $this->collectToOneAssociation($sourceEntities, $associationMetadataAdapter); |
29
|
|
|
} |
30
|
|
|
|
31
|
|
|
protected function collectToManyAssociation( |
32
|
|
|
ArrayCollection $sourceEntities, |
33
|
|
|
AssociationMetadataAdapter $associationMetadataAdapter |
34
|
|
|
): ArrayCollection { |
35
|
|
|
$targetEntities = new UniqueEntitySet(); |
36
|
|
|
|
37
|
|
|
foreach ($sourceEntities as $sourceEntity) { |
38
|
|
|
$targetEntities->addMany( |
39
|
|
|
$this->propertyAccessor->getValue($sourceEntity, $associationMetadataAdapter->getName())->getValues() |
40
|
|
|
); |
41
|
|
|
} |
42
|
|
|
|
43
|
|
|
return $targetEntities->getAll(); |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
protected function collectToOneAssociation( |
47
|
|
|
ArrayCollection $sourceEntities, |
48
|
|
|
AssociationMetadataAdapter $associationMetadataAdapter |
49
|
|
|
): ArrayCollection { |
50
|
|
|
$targetEntities = new UniqueEntitySet(); |
51
|
|
|
|
52
|
|
|
foreach ($sourceEntities as $sourceEntity) { |
53
|
|
|
$targetEntity = $this->propertyAccessor->getValue($sourceEntity, $associationMetadataAdapter->getName()); |
54
|
|
|
if ($targetEntity) { |
55
|
|
|
$targetEntities->addOne($targetEntity); |
56
|
|
|
} |
57
|
|
|
} |
58
|
|
|
|
59
|
|
|
return $targetEntities->getAll(); |
60
|
|
|
} |
61
|
|
|
} |
62
|
|
|
|