<?php
declare(strict_types=1);
namespace App\EventsSubscriber\User;
use App\Entity\Referral;
use App\Event\Payment\PaymentHistoryCreatedEvent;
use App\Event\User\CreatedEvent;
use App\Services\Creator\Event\CreatorCreatedEvent;
use App\Services\Sponsor\Event\SponsorCreatedEvent;
use App\Services\User\ReferralService;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class ReferralSubscriber implements EventSubscriberInterface
{
public static function getSubscribedEvents(): array
{
return [
CreatedEvent::class => 'onUserCreated',
CreatorCreatedEvent::class => 'onCreatorCreated',
SponsorCreatedEvent::class => 'onSponsorCreated',
PaymentHistoryCreatedEvent::class => 'onPaymentHistoryCreated',
];
}
public function __construct(
private readonly ReferralService $referralService,
) {
}
public function onSponsorCreated(SponsorCreatedEvent $event): void
{
$this->referralService->getOrCreateAccountReferral(
user: $event->getSponsor(),
durationDays: Referral::DURATION_365_DAYS_PER_REFERRED_USER,
);
if ($event->getReferredBy()) {
$this->referralService->linkReferral($event->getSponsor(), $event->getReferredBy());
}
}
public function onCreatorCreated(CreatorCreatedEvent $event): void
{
$this->referralService->getOrCreateAccountReferral($event->getCreator());
}
public function onUserCreated(CreatedEvent $event): void
{
$this->referralService->getOrCreateAccountReferral($event->getUser());
}
public function onPaymentHistoryCreated(PaymentHistoryCreatedEvent $event): void
{
$this->referralService->processReferralReward($event->getPaymentHistory());
}
}