<?php declare(strict_types=1);
namespace App\Subscriber;
use App\Entity\Deal;
use App\Entity\DealBid;
use App\Entity\Project;
use App\Entity\ProjectBid;
use App\Entity\ProposalBid;
use App\Event\CreditsEvent;
use Doctrine\Persistence\ManagerRegistry;
use LogicException;
use RuntimeException;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpFoundation\Session\Session;
class ProposalCreditsSubscriber implements EventSubscriberInterface
{
private ManagerRegistry $doctrine;
private RequestStack $requestStack;
public function __construct(ManagerRegistry $doctrine, RequestStack $requestStack)
{
$this->doctrine = $doctrine;
$this->requestStack = $requestStack;
}
public function onCredits(CreditsEvent $event): void
{
if (!in_array($event->getAction(), [CreditsEvent::ACTION_DEAL_BID, CreditsEvent::ACTION_DEAL_BID_REFUND, CreditsEvent::ACTION_PROJECT_BID, CreditsEvent::ACTION_PROJECT_BID_REFUND], true)) {
return;
}
$proposalBid = $event->getRelatedEntity();
if (!($proposalBid instanceof ProposalBid)) {
throw new LogicException('The related entity should be ProposalBid.');
}
if ($proposalBid instanceof DealBid) {
$this->doctrine->getRepository(Deal::class)->addContribution(
$proposalBid->getDeal(),
$event->getCredits() * -1
);
}
if ($proposalBid instanceof ProjectBid) {
$this->doctrine->getRepository(Project::class)->addContribution(
$proposalBid->getProject(),
$event->getCredits() * -1
);
}
if (!in_array($event->getAction(), [CreditsEvent::ACTION_DEAL_BID, CreditsEvent::ACTION_PROJECT_BID], true)) {
return;
}
$session = $this->requestStack->getSession();
if (!$session instanceof Session) {
throw new RuntimeException('The application requires Session.');
}
$session->getFlashBag()->add(
'contribution-success',
$event->getCreditsFloat() * -1
);
}
/**
* @return array<string, array<int|string, array<int|string, int|string>|int|string>|string>
*/
public static function getSubscribedEvents(): array
{
return [
CreditsEvent::class => 'onCredits',
];
}
}