<?php
namespace Aqarmap\Bundle\UserBundle\EventListener;
use Aqarmap\Bundle\ListingBundle\Contracts\PhoneManagerInterface;
use Aqarmap\Bundle\UserBundle\Entity\User;
use Aqarmap\Bundle\UserBundle\Services\Contracts\UserPhoneManagerInterface;
use Doctrine\ORM\EntityManagerInterface;
use FOS\UserBundle\Event\FormEvent;
use FOS\UserBundle\FOSUserEvents;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class UserUpdateListener implements EventSubscriberInterface
{
private EntityManagerInterface $entityManager;
private PhoneManagerInterface $phoneManager;
private UserPhoneManagerInterface $userPhoneManager;
public function __construct(
PhoneManagerInterface $phoneManager,
EntityManagerInterface $entityManager,
UserPhoneManagerInterface $userPhoneManager
) {
$this->phoneManager = $phoneManager;
$this->entityManager = $entityManager;
$this->userPhoneManager = $userPhoneManager;
}
public function onProfileEditSuccess(FormEvent $event): void
{
$mainPhones = [
$event->getForm()->get('firstPhone')->getData(),
$event->getForm()->get('secondPhone')->getData(),
];
$countryCodes = [
$event->getForm()->get('firstCountryCode')->getData(),
$event->getForm()->get('secondCountryCode')->getData(),
];
$hasWhatsApp = $event->getRequest()->request->get('hasWhatsApp');
$phones = $this->preparePhones($mainPhones, $countryCodes);
/** @var User $user */
$user = $event->getForm()->getData();
$this->userPhoneManager->addMainPhoneNumbers($user, $phones, $countryCodes, $hasWhatsApp);
$user->setMigratedPhone(true);
$user->setPhoneNumber($user->getPhoneNumber());
$this->entityManager->persist($user);
$this->entityManager->flush();
try {
$this->checkPhoneDuplications($mainPhones, $countryCodes);
} catch (\Exception $exception) {
}
}
private function checkPhoneDuplications(array $mainPhones, array $countryCodes): void
{
foreach ($mainPhones as $index => $mainPhone) {
if (!$mainPhone) {
continue;
}
$mainPhone = $countryCodes[$index].$mainPhone;
$mainPhone = $this->phoneManager->trimZero($mainPhone, $countryCodes[$index]);
$phones[] = $mainPhone;
}
}
/**
* @return array
*/
private function preparePhones(array $mainPhones, array $countryCodes)
{
$preparedPhones = [];
foreach ($mainPhones as $index => $mainPhone) {
if (!$mainPhone) {
continue; // Skip empty phone numbers
}
// Trim leading zeros
$mainPhone = $this->phoneManager->trimZero($mainPhone, $countryCodes[$index]);
// Add prepared phone to the list
$preparedPhones[] = $mainPhone;
}
return $preparedPhones;
}
public static function getSubscribedEvents()
{
return [
FOSUserEvents::PROFILE_EDIT_SUCCESS => [
['onProfileEditSuccess'],
],
];
}
}