<?php
declare(strict_types=1);
namespace App\Platform\EventSubscriber;
use App\Bundles\DiagnosisBundle\Form\Type\Diagnosis\DiagnosisChoiceType;
use App\Bundles\DiagnosisBundle\Form\Type\Diagnosis\DiagnosisTextType;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Validator\Constraints\Regex;
class TextFieldSubscriber implements EventSubscriberInterface
{
public const EXPRESSION_FOR_CHECK_APOSTROPHES = '/[‘’`´]/u';
public static function getSubscribedEvents(): array
{
return [
FormEvents::PRE_SET_DATA => 'addConstraintsToTextFields',
];
}
public function addConstraintsToTextFields(FormEvent $event): void
{
$form = $event->getForm();
$this->addConstraints($form);
}
private function addConstraints(FormInterface $form): void
{
foreach ($form->all() as $field) {
$config = $field->getConfig();
$type = $config->getType()->getInnerType();
if ($type instanceof DiagnosisTextType || $type instanceof DiagnosisChoiceType) {
continue;
}
if (!$type instanceof TextType) {
continue;
}
$options = $config->getOptions();
$constraints = $options['constraints'] ?? [];
$constraints[] = new Regex(pattern: self::EXPRESSION_FOR_CHECK_APOSTROPHES, match: false);
$form->add(
$field->getName(),
TextType::class,
array_merge($options, ['constraints' => $constraints]),
);
}
}
}