<?php
namespace App\EventSubscriber\Content;
use App\Entity\Content\Text;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use App\Event\Content\ContentDisplayEvent;
use Twig\Environment;
use App\Twig\ModuleExtension;
/**
* @author Przemysław Chrupek <przemyslaw.chrupek@avt.pl>
*/
class ContentInTextModulesSubscriber implements EventSubscriberInterface
{
/**
* @var Content
*/
private $content;
/**
* @var Environment
*/
private $environment;
/**
* @var int
*/
private $moduleCounter;
public function __construct(Environment $environment, ModuleExtension $moduleExtension)
{
$this->environment = $environment;
$this->moduleExtension = $moduleExtension;
$this->moduleCounter = 0;
}
public static function getSubscribedEvents()
{
return [
ContentDisplayEvent::NAME => [
['preContentDisplay', 100],
]
];
}
public function preContentDisplay(ContentDisplayEvent $event)
{
$this->content = $event->getContent();
$text = $this->content->getText();
if (!$text instanceof Text) {
return;
}
$pattern = '/<pre[^{]*?>{\$(in-article-module)}.*?<\/pre>/msi';
$text->setValue(preg_replace_callback($pattern, [$this, 'modules'], $text->getValue()));
}
protected function modules($matches)
{
$html = '';
$this->moduleCounter++;
$position = 'in-article-module-' . $this->moduleCounter;
ob_start();
$this->moduleExtension->renderModulePosition($this->environment, $position);
$html .= ob_get_clean();
return $html;
}
}