<?php
namespace App\EventSubscriber\Content;
use App\Entity\Content\Content;
use App\Entity\Content\Text;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use App\Event\Content\ContentDisplayEvent;
use App\Entity\Menu\Item;
use App\Service\Gatherer;
use App\Text\Aliasifer;
/**
* @author Przemysław Chrupek <przemyslaw.chrupek@avt.pl>
*/
class ContentInTextTocSubscriber implements EventSubscriberInterface
{
/**
* @var Content
*/
private $content;
/**
* @var Item
*/
private $menuItem;
/**
* @var Gatherer
*/
protected $gatherer;
/**
* @var Text
*/
private $text;
private $breakpoint;
public function __construct(Gatherer $gatherer)
{
$this->gatherer = $gatherer;
}
public static function getSubscribedEvents()
{
return [
ContentDisplayEvent::NAME => [
['preContentDisplay', 102],
]
];
}
public function preContentDisplay(ContentDisplayEvent $event)
{
$this->content = $event->getContent();
$this->text = $this->content->getText();
$this->menuItem = $this->content->getMenuItem();
if (!$this->text instanceof Text || !$this->menuItem instanceof Item)
return;
$n = $this->regexPagebreak($this->text->getValue());
if (empty($this->breakpoint))
return;
$this->gatherer->add('contentToc', $this->breakpoint);
}
protected function regexPagebreak()
{
$n = 1;
$regex = "/\<pre.*?\>\{PAGEBREAK\|(.*)}.*?\<\/pre>/";
$this->text->setValue(preg_replace_callback($regex, [$this, 'prepareBreakpoint'], $this->text->getValue()));
if (!empty($this->breakpoint)) {
foreach ($this->breakpoint as $value) {
if ($value['newPage'] == true) {
$n++;
}
}
}
return $n;
}
protected function prepareBreakpoint($matches)
{
$data = explode('|', $matches[1]);
$alias = Aliasifer::aliasify(html_entity_decode($data[0]));
$this->breakpoint[$alias]['title'] = html_entity_decode($data[0]);
$this->breakpoint[$alias]['alias'] = $alias;
$this->breakpoint[$alias]['newPage'] = isset($data[1]) ? true : false;
$newPage = isset($data[1]) ? ' toc-breakpoint-newpage' : '';
return '<div id="'.$alias.'" class="toc-breakpoint'. $newPage .'"></div>';
}
}