src/Platform/EventSubscriber/TextFieldSubscriber.php line 27

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\Platform\EventSubscriber;
  4. use App\Bundles\DiagnosisBundle\Form\Type\Diagnosis\DiagnosisChoiceType;
  5. use App\Bundles\DiagnosisBundle\Form\Type\Diagnosis\DiagnosisTextType;
  6. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  7. use Symfony\Component\Form\Extension\Core\Type\TextType;
  8. use Symfony\Component\Form\FormEvent;
  9. use Symfony\Component\Form\FormEvents;
  10. use Symfony\Component\Form\FormInterface;
  11. use Symfony\Component\Validator\Constraints\Regex;
  12. class TextFieldSubscriber implements EventSubscriberInterface
  13. {
  14.     public const EXPRESSION_FOR_CHECK_APOSTROPHES '/[‘’`´]/u';
  15.     public static function getSubscribedEvents(): array
  16.     {
  17.         return [
  18.             FormEvents::PRE_SET_DATA => 'addConstraintsToTextFields',
  19.         ];
  20.     }
  21.     public function addConstraintsToTextFields(FormEvent $event): void
  22.     {
  23.         $form $event->getForm();
  24.         $this->addConstraints($form);
  25.     }
  26.     private function addConstraints(FormInterface $form): void
  27.     {
  28.         foreach ($form->all() as $field) {
  29.             $config $field->getConfig();
  30.             $type $config->getType()->getInnerType();
  31.             if ($type instanceof DiagnosisTextType || $type instanceof DiagnosisChoiceType) {
  32.                 continue;
  33.             }
  34.             if (!$type instanceof TextType) {
  35.                 continue;
  36.             }
  37.             $options $config->getOptions();
  38.             $constraints $options['constraints'] ?? [];
  39.             $constraints[] = new Regex(patternself::EXPRESSION_FOR_CHECK_APOSTROPHES, match: false);
  40.             $form->add(
  41.                 $field->getName(),
  42.                 TextType::class,
  43.                 array_merge($options, ['constraints' => $constraints]),
  44.             );
  45.         }
  46.     }
  47. }