<?php
namespace App\EventSubscriber;
use Exception;
use App\Model\Client;
use App\Model\Phone;
use App\Service\FileService;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Form\Event\PostSubmitEvent;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
class ClientTypeSubscriber implements EventSubscriberInterface
{
private FileService $fileService;
public function __construct(FileService $fileService)
{
$this->fileService = $fileService;
}
public function onSubmit(FormEvent $event)
{
/** @var Client $client */
$client = $event->getData();
$form = $event->getForm();
if (!$client) {
return;
}
/** @var Phone|null $phone */
$phone = $form->get('phoneNumber')->getData();
if (is_null($phone) || is_null($phone->getNumber())) {
$client->setPhoneNumber(null);
}
/** @var Phone|null $phone */
$mobile = $form->get('mobileNumber')->getData();
if (is_null($mobile) || is_null($mobile->getNumber())) {
$client->setMobileNumber(null);
}
$event->setData($client);
}
public static function getSubscribedEvents(): array
{
return [
FormEvents::SUBMIT => 'onSubmit',
FormEvents::POST_SUBMIT => 'onPostSubmit',
];
}
/**
* @throws Exception
*/
public function onPostSubmit(PostSubmitEvent $event)
{
/** @var Client $client */
$client = $event->getData();
$form = $event->getForm();
if (!$client instanceof Client) {
return;
}
$uploadedFile = $form->get('driverLicense')->getData();
$this->fileService->attachFileModel($uploadedFile, $client, 'driverLicense');
$title = $form->get('title')->getData();
$client->setTitle($title);
$event->setData($client);
}
}