src/Service/ElasticSearchPreTransformListener.php line 35

Open in your IDE?
  1. <?php
  2. namespace App\Service;
  3. use App\Entity\Magazine\Magazine;
  4. use App\Entity\Magazine\MagazinePage;
  5. use HTMLPurifier;
  6. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  7. use FOS\ElasticaBundle\Event\TransformEvent;
  8. class ElasticSearchPreTransformListener implements EventSubscriberInterface
  9. {
  10.     private $anotherService;
  11.     /**
  12.      * @var HtmlPurifier
  13.      */
  14.     private $htmlPurifier;
  15.     /**
  16.      * Constructor.
  17.      *
  18.      * @param HTMLPurifier $htmlPurifier
  19.      */
  20.     public function __construct() {
  21.         $this->htmlPurifier = new HTMLPurifier();
  22.     }
  23.     // ...
  24.     /**
  25.      * @param TransformEvent $event
  26.      */
  27.     public function doPreTransform(TransformEvent $event)
  28.     {
  29.         $entity $event->getObject();
  30.         $document $event->getDocument();
  31.         if ($entity instanceof MagazinePage) {
  32.             $entity->setContent(htmlspecialchars_decode($this->cleanContent($this->htmlPurifier->purify($entity->getContent()))));
  33.         }
  34.         if ($entity instanceof Magazine) {
  35.             foreach($entity->getPages() as $page) {
  36.                 $page->setContent(htmlspecialchars_decode($this->cleanContent($this->htmlPurifier->purify($page->getContent()))));
  37.             }
  38.         }
  39.         //$this->anotherService->reloadTranslation($event->getObject());
  40.     }
  41.     public static function getSubscribedEvents()
  42.     {
  43.         return array(
  44.             TransformEvent::PRE_TRANSFORM => 'doPreTransform',
  45.         );
  46.     }
  47.     /**
  48.      * @param string $string
  49.      * @param string|null $allowable_tags
  50.      * @return string
  51.      */
  52.     private function strip_tags_with_whitespace($string$allowable_tags null): string
  53.     {
  54.         $string str_replace('<'' <'$string);
  55.         $string strip_tags($string$allowable_tags);
  56.         $string str_replace('  '' '$string);
  57.         $string trim($string);
  58.         return $string;
  59.     }
  60.     private function cleanContent($content): string
  61.     {
  62.         $cleanContent $this->strip_tags_with_whitespace($content);
  63.         $cleanContent str_replace("\r"' '$cleanContent);    // --- replace with space
  64.         $cleanContent str_replace("\n"' '$cleanContent);   // --- replace with space
  65.         $cleanContent str_replace("\t"' '$cleanContent);   // --- replace with space
  66.         return trim(preg_replace('/ {2,}/'' '$cleanContent));
  67.     }
  68. }