src/Aqarmap/Bundle/UserBundle/EventListener/UserUpdateListener.php line 31

  1. <?php
  2. namespace Aqarmap\Bundle\UserBundle\EventListener;
  3. use Aqarmap\Bundle\ListingBundle\Contracts\PhoneManagerInterface;
  4. use Aqarmap\Bundle\UserBundle\Entity\User;
  5. use Aqarmap\Bundle\UserBundle\Services\Contracts\UserPhoneManagerInterface;
  6. use Doctrine\ORM\EntityManagerInterface;
  7. use FOS\UserBundle\Event\FormEvent;
  8. use FOS\UserBundle\FOSUserEvents;
  9. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  10. class UserUpdateListener implements EventSubscriberInterface
  11. {
  12. public function __construct(private readonly PhoneManagerInterface $phoneManager, private readonly EntityManagerInterface $entityManager, private readonly UserPhoneManagerInterface $userPhoneManager)
  13. {
  14. }
  15. public function onProfileEditSuccess(FormEvent $event): void
  16. {
  17. $mainPhones = [
  18. $event->getForm()->get('firstPhone')->getData(),
  19. $event->getForm()->get('secondPhone')->getData(),
  20. ];
  21. $countryCodes = [
  22. $event->getForm()->get('firstCountryCode')->getData(),
  23. $event->getForm()->get('secondCountryCode')->getData(),
  24. ];
  25. $hasWhatsApp = $event->getRequest()->request->get('hasWhatsApp');
  26. $phones = $this->preparePhones($mainPhones, $countryCodes);
  27. /** @var User $user */
  28. $user = $event->getForm()->getData();
  29. $this->userPhoneManager->addMainPhoneNumbers($user, $phones, $countryCodes, $hasWhatsApp);
  30. $user->setMigratedPhone(true);
  31. $user->setPhoneNumber($user->getPhoneNumber());
  32. $this->entityManager->persist($user);
  33. $this->entityManager->flush();
  34. try {
  35. $this->checkPhoneDuplications($mainPhones, $countryCodes);
  36. } catch (\Exception) {
  37. }
  38. }
  39. private function checkPhoneDuplications(array $mainPhones, array $countryCodes): void
  40. {
  41. foreach ($mainPhones as $index => $mainPhone) {
  42. if (!$mainPhone) {
  43. continue;
  44. }
  45. $mainPhone = $countryCodes[$index].$mainPhone;
  46. $mainPhone = $this->phoneManager->trimZero($mainPhone, $countryCodes[$index]);
  47. $phones[] = $mainPhone;
  48. }
  49. }
  50. /**
  51. * @return array
  52. */
  53. private function preparePhones(array $mainPhones, array $countryCodes)
  54. {
  55. $preparedPhones = [];
  56. foreach ($mainPhones as $index => $mainPhone) {
  57. if (!$mainPhone) {
  58. continue; // Skip empty phone numbers
  59. }
  60. // Trim leading zeros
  61. $mainPhone = $this->phoneManager->trimZero($mainPhone, $countryCodes[$index]);
  62. // Add prepared phone to the list
  63. $preparedPhones[] = $mainPhone;
  64. }
  65. return $preparedPhones;
  66. }
  67. public static function getSubscribedEvents(): array
  68. {
  69. return [
  70. FOSUserEvents::PROFILE_EDIT_SUCCESS => [
  71. ['onProfileEditSuccess'],
  72. ],
  73. ];
  74. }
  75. }