vendor/exercise/htmlpurifier-bundle/src/Form/TypeExtension/HTMLPurifierTextTypeExtension.php line 72

Open in your IDE?
  1. <?php
  2. namespace Exercise\HTMLPurifierBundle\Form\TypeExtension;
  3. use Exercise\HTMLPurifierBundle\Form\Listener\HTMLPurifierListener;
  4. use Exercise\HTMLPurifierBundle\HTMLPurifiersRegistryInterface;
  5. use Symfony\Component\Form\AbstractTypeExtension;
  6. use Symfony\Component\Form\Extension\Core\Type\TextType;
  7. use Symfony\Component\Form\FormBuilderInterface;
  8. use Symfony\Component\OptionsResolver\Exception\InvalidOptionsException;
  9. use Symfony\Component\OptionsResolver\Options;
  10. use Symfony\Component\OptionsResolver\OptionsResolver;
  11. class HTMLPurifierTextTypeExtension extends AbstractTypeExtension
  12. {
  13.     private $purifiersRegistry;
  14.     public function __construct(HTMLPurifiersRegistryInterface $registry)
  15.     {
  16.         $this->purifiersRegistry $registry;
  17.     }
  18.     /**
  19.      * {@inheritdoc}
  20.      */
  21.     public function getExtendedType()
  22.     {
  23.         return TextType::class;
  24.     }
  25.     /**
  26.      * {@inheritdoc}
  27.      */
  28.     public static function getExtendedTypes(): iterable
  29.     {
  30.         return [TextType::class];
  31.     }
  32.     /**
  33.      * {@inheritdoc}
  34.      */
  35.     public function configureOptions(OptionsResolver $resolver)
  36.     {
  37.         $resolver
  38.             ->setDefaults([
  39.                 'purify_html' => false,
  40.                 'purify_html_profile' => 'default',
  41.             ])
  42.             ->setAllowedTypes('purify_html''bool')
  43.             ->setAllowedTypes('purify_html_profile', ['string''null'])
  44.             ->setNormalizer('purify_html_profile', function (Options $options$profile) {
  45.                 if (!$options['purify_html']) {
  46.                     return null;
  47.                 }
  48.                 if ($this->purifiersRegistry->has($profile)) {
  49.                     return $profile;
  50.                 }
  51.                 throw new InvalidOptionsException(sprintf('The profile "%s" is not registered.'$profile));
  52.             })
  53.             ->setNormalizer('trim', function (Options $options$trim) {
  54.                 // trim is done in the HTMLPurifierListener
  55.                 return $options['purify_html'] ? false $trim;
  56.             })
  57.         ;
  58.     }
  59.     /**
  60.      * {@inheritdoc}
  61.      */
  62.     public function buildForm(FormBuilderInterface $builder, array $options)
  63.     {
  64.         if ($options['purify_html']) {
  65.             $builder->addEventSubscriber(
  66.                 new HTMLPurifierListener($this->purifiersRegistry$options['purify_html_profile'])
  67.             );
  68.         }
  69.     }
  70. }