<?php
namespace App\Service;
use App\Entity\Magazine\Magazine;
use App\Entity\Magazine\MagazinePage;
use HTMLPurifier;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use FOS\ElasticaBundle\Event\TransformEvent;
class ElasticSearchPreTransformListener implements EventSubscriberInterface
{
private $anotherService;
/**
* @var HtmlPurifier
*/
private $htmlPurifier;
/**
* Constructor.
*
* @param HTMLPurifier $htmlPurifier
*/
public function __construct() {
$this->htmlPurifier = new HTMLPurifier();
}
// ...
/**
* @param TransformEvent $event
*/
public function doPreTransform(TransformEvent $event)
{
$entity = $event->getObject();
$document = $event->getDocument();
if ($entity instanceof MagazinePage) {
$entity->setContent(htmlspecialchars_decode($this->cleanContent($this->htmlPurifier->purify($entity->getContent()))));
}
if ($entity instanceof Magazine) {
foreach($entity->getPages() as $page) {
$page->setContent(htmlspecialchars_decode($this->cleanContent($this->htmlPurifier->purify($page->getContent()))));
}
}
//$this->anotherService->reloadTranslation($event->getObject());
}
public static function getSubscribedEvents()
{
return array(
TransformEvent::PRE_TRANSFORM => 'doPreTransform',
);
}
/**
* @param string $string
* @param string|null $allowable_tags
* @return string
*/
private function strip_tags_with_whitespace($string, $allowable_tags = null): string
{
$string = str_replace('<', ' <', $string);
$string = strip_tags($string, $allowable_tags);
$string = str_replace(' ', ' ', $string);
$string = trim($string);
return $string;
}
private function cleanContent($content): string
{
$cleanContent = $this->strip_tags_with_whitespace($content);
$cleanContent = str_replace("\r", ' ', $cleanContent); // --- replace with space
$cleanContent = str_replace("\n", ' ', $cleanContent); // --- replace with space
$cleanContent = str_replace("\t", ' ', $cleanContent); // --- replace with space
return trim(preg_replace('/ {2,}/', ' ', $cleanContent));
}
}