src/Form/EventListener/AddLocationLabelFieldSubscriber.php line 24

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. namespace Harmonizely\Form\EventListener;
  4. use Harmonizely\Model\EventTypeInterface;
  5. use Harmonizely\Model\EventTypeUser;
  6. use Symfony\Component\Form\Extension\Core\Type\TextType;
  7. use Symfony\Component\Form\FormEvent;
  8. use Symfony\Component\Form\FormEvents;
  9. use Symfony\Component\Form\FormInterface;
  10. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  11. use Symfony\Component\Validator\Constraints\Length;
  12. use Symfony\Component\Validator\Constraints\NotBlank;
  13. class AddLocationLabelFieldSubscriber implements EventSubscriberInterface
  14. {
  15.     public static function getSubscribedEvents(): array
  16.     {
  17.         return [
  18.             FormEvents::PRE_SUBMIT => 'preSubmit',
  19.         ];
  20.     }
  21.     public function preSubmit(FormEvent $event): void
  22.     {
  23.         $data $event->getData();
  24.         if (empty($data) || !array_key_exists('locationType'$data)) {
  25.             return;
  26.         }
  27.         if (EventTypeInterface::LOCATION_TYPE_REQUEST === $data['locationType']) {
  28.             $form $event->getForm();
  29.             $isFirst $this->isFirstWithRequestLocationType($form);
  30.             $constraints = [new Length(['max' => 255])];
  31.             if ($isFirst) {
  32.                 $constraints[] = new NotBlank();
  33.             }
  34.             $form->add('locationLabel'TextType::class, [
  35.                 'constraints' => $constraints,
  36.             ]);
  37.         }
  38.     }
  39.     private function isFirstWithRequestLocationType(FormInterface $form): bool
  40.     {
  41.         $parent $form->getParent();
  42.         if ($parent === null) {
  43.             return true;
  44.         }
  45.         foreach ($parent->all() as $siblingForm) {
  46.             if ($siblingForm === $form) {
  47.                 return true;
  48.             }
  49.             $siblingData $siblingForm->getData();
  50.             if ($siblingData instanceof EventTypeUser
  51.                 && $siblingData->getLocationType() === EventTypeInterface::LOCATION_TYPE_REQUEST) {
  52.                 return false;
  53.             }
  54.         }
  55.         return true;
  56.     }
  57. }