feat: extend XSS protection to all forms

This commit is contained in:
Björn Fromme
2025-01-08 17:33:29 +01:00
parent e588716046
commit b196825ab3
5 changed files with 56 additions and 0 deletions
+45
View File
@@ -0,0 +1,45 @@
<?php
namespace App\Form\Extension;
use Symfony\Component\Form\AbstractTypeExtension;
use Symfony\Component\Form\Extension\Core\Type\FormType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\OptionsResolver\OptionsResolver;
use voku\helper\AntiXSS;
class AntiXssExtension extends AbstractTypeExtension
{
public function buildForm(FormBuilderInterface $builder, array $options): void
{
if (false === $options['anti_xss']) {
return;
}
$builder->addEventListener(FormEvents::PRE_SUBMIT, function (FormEvent $event) {
$data = $event->getData();
if (null === $data) {
return;
}
$antiXss = new AntiXSS();
foreach ($data as $key => $value) {
$data[$key] = $antiXss->xss_clean($value);
}
$event->setData($data);
});
}
public function configureOptions(OptionsResolver $resolver): void
{
$resolver->setDefaults([
'anti_xss' => false,
]);
}
public static function getExtendedTypes(): iterable
{
return [FormType::class];
}
}