src/EventSubscriber/ClientTypeSubscriber.php line 23

Open in your IDE?
  1. <?php
  2. namespace App\EventSubscriber;
  3. use Exception;
  4. use App\Model\Client;
  5. use App\Model\Phone;
  6. use App\Service\FileService;
  7. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  8. use Symfony\Component\Form\Event\PostSubmitEvent;
  9. use Symfony\Component\Form\FormEvent;
  10. use Symfony\Component\Form\FormEvents;
  11. class ClientTypeSubscriber implements EventSubscriberInterface
  12. {
  13.     private FileService $fileService;
  14.     public function __construct(FileService $fileService)
  15.     {
  16.         $this->fileService $fileService;
  17.     }
  18.     public function onSubmit(FormEvent $event)
  19.     {
  20.         /** @var Client $client */
  21.         $client $event->getData();
  22.         $form $event->getForm();
  23.         if (!$client) {
  24.             return;
  25.         }
  26.         /** @var Phone|null $phone */
  27.         $phone $form->get('phoneNumber')->getData();
  28.         if (is_null($phone) || is_null($phone->getNumber())) {
  29.             $client->setPhoneNumber(null);
  30.         }
  31.         /** @var Phone|null $phone */
  32.         $mobile $form->get('mobileNumber')->getData();
  33.         if (is_null($mobile) || is_null($mobile->getNumber())) {
  34.             $client->setMobileNumber(null);
  35.         }
  36.         $event->setData($client);
  37.     }
  38.     public static function getSubscribedEvents(): array
  39.     {
  40.         return [
  41.             FormEvents::SUBMIT => 'onSubmit',
  42.             FormEvents::POST_SUBMIT => 'onPostSubmit',
  43.         ];
  44.     }
  45.     /**
  46.      * @throws Exception
  47.      */
  48.     public function onPostSubmit(PostSubmitEvent $event)
  49.     {
  50.         /** @var Client $client */
  51.         $client $event->getData();
  52.         $form $event->getForm();
  53.         if (!$client instanceof Client) {
  54.             return;
  55.         }
  56.         $uploadedFile $form->get('driverLicense')->getData();
  57.         $this->fileService->attachFileModel($uploadedFile$client'driverLicense');
  58.         $title $form->get('title')->getData();
  59.         $client->setTitle($title);
  60.         $event->setData($client);
  61.     }
  62. }