src/EventSubscriber/ECommerce/ClientSubscriber.php line 40

Open in your IDE?
  1. <?php
  2. namespace App\EventSubscriber\ECommerce;
  3. use Doctrine\ORM\Event\LifecycleEventArgs;
  4. use Doctrine\ORM\EntityManagerInterface;
  5. use App\Entity\ECommerce\Currency;
  6. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  7. use App\Entity\ECommerce\Client;
  8. use App\Entity\ECommerce\Firm;
  9. use Doctrine\ORM\Events;
  10. /**
  11. * Class ClientSubscriber
  12. *
  13. * @package App\EventSubscriber\ECommerce
  14. */
  15. class ClientSubscriber implements EventSubscriberInterface
  16. {
  17. /**
  18. * ClientSubscriber constructor.
  19. */
  20. public function __construct(protected \Doctrine\ORM\EntityManagerInterface $entityManager)
  21. {
  22. }
  23. public static function getSubscribedEvents(): array
  24. {
  25. return [
  26. Events::postLoad => 'postLoad',
  27. Events::prePersist => 'prePersist',
  28. ];
  29. }
  30. public function postLoad(LifecycleEventArgs $args): void
  31. {
  32. $this->checkFirm($args);
  33. }
  34. public function prePersist(LifecycleEventArgs $args): void
  35. {
  36. $this->checkFirm($args);
  37. $this->checkCurrency($args);
  38. }
  39. protected function checkCurrency(LifecycleEventArgs $args)
  40. {
  41. $client = $args->getObject();
  42. if (!$client instanceof Client) {
  43. return;
  44. }
  45. $client->setCurrency($this->entityManager->getRepository(Currency::class)->findFirst());
  46. }
  47. protected function checkFirm(LifecycleEventArgs $args)
  48. {
  49. $client = $args->getObject();
  50. if (!$client instanceof Client) {
  51. return;
  52. }
  53. $this->setFirm($client);
  54. }
  55. public function setFirm(Client $client)
  56. {
  57. if ($client->getFirm() instanceof Firm) {
  58. return $client;
  59. }
  60. $firm = $this->entityManager->getRepository(Firm::class)->findOneByCurrency($client->getCurrency());
  61. return $client->setFirm($firm);
  62. }
  63. }