src/EventSubscriber/Tournament/TournamentCreatedEventSubscriber.php line 19

Open in your IDE?
  1. <?php
  2. namespace App\EventSubscriber\Tournament;
  3. use App\Entity\Config;
  4. use App\Entity\Prize;
  5. use App\Entity\Tournament;
  6. use App\Repository\ConfigRepository;
  7. use DomainException;
  8. use EasyCorp\Bundle\EasyAdminBundle\Event\BeforeEntityPersistedEvent;
  9. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  10. class TournamentCreatedEventSubscriber implements EventSubscriberInterface
  11. {
  12.     public function __construct(private ConfigRepository $configRepository)
  13.     {
  14.     }
  15.     public function onBeforeEntityPersistedEvent(BeforeEntityPersistedEvent $beforeEntityPersistedEvent): void
  16.     {
  17.         $entity $beforeEntityPersistedEvent->getEntityInstance();
  18.         if (!($entity instanceof Tournament)) {
  19.             return;
  20.         }
  21.         $tournamentTax $this->configRepository->findOneBy([
  22.             'name' => Config::TOURNAMENT_TAX_AMOUNT,
  23.         ]);
  24.         if (!$tournamentTax) {
  25.             throw new DomainException('The tax must be configured.');
  26.         }
  27.         $tax = (int) $tournamentTax->getValue();
  28.         $entity->setTax($tax);
  29.         if (!$entity->getPrizeBundle()) {
  30.             return;
  31.         }
  32.         foreach ($entity->getPrizeBundle()->getPrizeConfigs() as $prizeConfig) {
  33.             $entity->addPrize(
  34.                 (new Prize())
  35.                     ->setRank($prizeConfig->getRank())
  36.                     ->setValue($prizeConfig->getValue())
  37.                     ->setDescription($prizeConfig->getDescription())
  38.             );
  39.         }
  40.     }
  41.     public static function getSubscribedEvents(): array
  42.     {
  43.         return [
  44.             BeforeEntityPersistedEvent::class => 'onBeforeEntityPersistedEvent',
  45.         ];
  46.     }
  47. }