1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Odiseo\SyliusReferralsPlugin\Mapping; |
6
|
|
|
|
7
|
|
|
use Doctrine\Common\EventSubscriber; |
8
|
|
|
use Doctrine\ORM\Event\LoadClassMetadataEventArgs; |
9
|
|
|
use Doctrine\ORM\Events; |
10
|
|
|
use Doctrine\ORM\Mapping\ClassMetadata; |
11
|
|
|
use Odiseo\SyliusReferralsPlugin\Entity\AffiliateReferralAwareInterface; |
12
|
|
|
use Sylius\Component\Order\Model\OrderInterface; |
13
|
|
|
use Sylius\Component\Resource\Metadata\RegistryInterface; |
14
|
|
|
|
15
|
|
|
final class AffiliateReferralAwareListener implements EventSubscriber |
16
|
|
|
{ |
17
|
|
|
public function __construct( |
18
|
|
|
private RegistryInterface $resourceMetadataRegistry, |
19
|
|
|
private string $affiliateReferralClass, |
20
|
|
|
) { |
21
|
|
|
} |
22
|
|
|
|
23
|
|
|
public function getSubscribedEvents(): array |
24
|
|
|
{ |
25
|
|
|
return [ |
26
|
|
|
Events::loadClassMetadata, |
27
|
|
|
]; |
28
|
|
|
} |
29
|
|
|
|
30
|
|
|
public function loadClassMetadata(LoadClassMetadataEventArgs $eventArgs): void |
31
|
|
|
{ |
32
|
|
|
$classMetadata = $eventArgs->getClassMetadata(); |
33
|
|
|
$reflection = $classMetadata->reflClass; |
|
|
|
|
34
|
|
|
|
35
|
|
|
/** |
36
|
|
|
* @phpstan-ignore-next-line |
37
|
|
|
*/ |
38
|
|
|
if ($reflection === null || $reflection->isAbstract()) { |
39
|
|
|
return; |
40
|
|
|
} |
41
|
|
|
|
42
|
|
|
if ( |
43
|
|
|
$reflection->implementsInterface(OrderInterface::class) && |
44
|
|
|
$reflection->implementsInterface(AffiliateReferralAwareInterface::class) |
45
|
|
|
) { |
46
|
|
|
$this->mapAffiliateReferralAware($classMetadata, 'affiliate_referral_id'); |
47
|
|
|
} |
48
|
|
|
} |
49
|
|
|
|
50
|
|
|
private function mapAffiliateReferralAware( |
51
|
|
|
ClassMetadata $metadata, |
52
|
|
|
string $joinColumn, |
53
|
|
|
?string $inversedBy = null, |
54
|
|
|
): void { |
55
|
|
|
try { |
56
|
|
|
$affiliateReferralMetadata = $this->resourceMetadataRegistry->getByClass($this->affiliateReferralClass); |
57
|
|
|
} catch (\InvalidArgumentException $exception) { |
58
|
|
|
return; |
59
|
|
|
} |
60
|
|
|
|
61
|
|
|
if (!$metadata->hasAssociation('affiliateReferral')) { |
62
|
|
|
$mapping = [ |
63
|
|
|
'fieldName' => 'affiliateReferral', |
64
|
|
|
'targetEntity' => $affiliateReferralMetadata->getClass('model'), |
65
|
|
|
'joinColumns' => [ |
66
|
|
|
[ |
67
|
|
|
'name' => $joinColumn, |
68
|
|
|
'referencedColumnName' => 'id', |
69
|
|
|
], |
70
|
|
|
], |
71
|
|
|
'cascade' => ['persist'], |
72
|
|
|
]; |
73
|
|
|
|
74
|
|
|
if (null !== $inversedBy) { |
75
|
|
|
$mapping['inversedBy'] = $inversedBy; |
76
|
|
|
} |
77
|
|
|
|
78
|
|
|
$metadata->mapManyToOne($mapping); |
79
|
|
|
} |
80
|
|
|
} |
81
|
|
|
} |
82
|
|
|
|