src/EventSubscriber/ECommerce/ClientSubscriber.php line 57

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. * @var EntityManagerInterface
  19. */
  20. protected $entityManager;
  21. /**
  22. * ClientSubscriber constructor.
  23. *
  24. * @param EntityManagerInterface $entityManager
  25. */
  26. public function __construct(EntityManagerInterface $entityManager)
  27. {
  28. $this->entityManager = $entityManager;
  29. }
  30. /**
  31. * @return array
  32. */
  33. public static function getSubscribedEvents(): array
  34. {
  35. return array(
  36. Events::postLoad => 'postLoad',
  37. Events::prePersist => 'prePersist',
  38. );
  39. }
  40. /**
  41. * @param LifecycleEventArgs $args
  42. */
  43. public function postLoad(LifecycleEventArgs $args)
  44. {
  45. $this->checkFirm($args);
  46. }
  47. /**
  48. * @param LifecycleEventArgs $args
  49. */
  50. public function prePersist(LifecycleEventArgs $args)
  51. {
  52. $this->checkFirm($args);
  53. $this->checkCurrency($args);
  54. }
  55. /**
  56. * @param LifecycleEventArgs $args
  57. */
  58. protected function checkCurrency(LifecycleEventArgs $args)
  59. {
  60. $client = $args->getObject();
  61. if (!$client instanceof Client) {
  62. return;
  63. }
  64. $client->setCurrency($this->entityManager->getRepository(Currency::class)->findFirst());
  65. }
  66. /**
  67. * @param LifecycleEventArgs $args
  68. */
  69. protected function checkFirm(LifecycleEventArgs $args)
  70. {
  71. $client = $args->getObject();
  72. if (!$client instanceof Client) {
  73. return;
  74. }
  75. $this->setFirm($client);
  76. }
  77. /**
  78. * @param Client $client
  79. */
  80. public function setFirm(Client $client)
  81. {
  82. if ($client->getFirm() instanceof Firm) {
  83. return $client;
  84. }
  85. $firm = $this->entityManager->getRepository(Firm::class)->findOneByCurrency($client->getCurrency());
  86. return $client->setFirm($firm);
  87. }
  88. }