I need suggestion how would you handle this situation:
I have two entities:
Customers and Reservations. Customers have unique phone number.
Then I have a form where user can choose date and has to provide info like name, phone number, email.
If phone number exists in DB it should find that record and use it instead of trying to create new record and throw the UniqueConstraintViolationException
.
Now I'm handling that inside an EventListener:
public function prePersist(LifecycleEventArgs $args): void
{
$this->em = $args->getEntityManager();
$this->reserve($args);
}
private function reserve(LifecycleEventArgs $args): void
{
$reservation = $args->getEntity();
if ($reservation instanceof Reservation) {
$this->reservation = $reservation;
$this->email = $this->getEmail();
$this->phoneNumber = $this->getInternationalNumber();
//check if customer is new
$this->setCustomer();
}
}
private function setCustomer(): void
{
$customerRepository = $this->em->getRepository(Customer::class);
if ($customer = $customerRepository->findOneBy(['phoneNumber' => $reservation->getCustomer()->getPhoneNumber()])) {
$this->reservation->setCustomer($customer);
}
}
How would you handle this? I think there should be a better way to do this(maybe?).