-
Notifications
You must be signed in to change notification settings - Fork 30
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Modifying shortcode replacements via event handler? #67
Comments
I may be headed in the wrong direction, but I think this would be straightforward if the |
Yes, this is one of the use cases for
$handlers = new HandlerContainer();
$handlers->setDefault(function(ShortcodeInterface $s) { return $s->getName().$s->getContent(); });
$events = new EventContainer();
$events->addListener(Events::REPLACE_SHORTCODES, new class {
public function __invoke(ReplaceShortcodesEvent $event)
{
$text = $event->getText();
/** @var ReplacedShortcode $s */
foreach(array_reverse($event->getReplacements()) as $s) {
$offset = $s->getOffset();
$length = mb_strlen($s->getText(), 'utf-8');
$textLength = mb_strlen($text, 'utf-8');
$prefix = mb_substr($text, 0, $offset, 'utf-8');
$postfix = mb_substr($text, $offset + $length, $textLength, 'utf-8');
$text = $prefix.$this->rewrite($s).$postfix;
}
$event->setResult($text);
}
private function rewrite(ReplacedShortcode $r)
{
return [
'what' => function(ReplacedShortcode $r) { return '<p>'.$r->getReplacement().'</p>'; },
'goes' => function(ReplacedShortcode $r) { return '<b>'.$r->getReplacement().'</b>'; },
'around' => function(ReplacedShortcode $r) { return '<u>'.$r->getReplacement().'</u>'; },
][$r->getName()]($r);
}
});
$processor = new Processor(new RegularParser(), $handlers);
$processor = $processor->withEventContainer($events);
$text = 'a [what] [goes /] [around /] [/what] z';
$expected = 'a <p>what <b>goes</b> <u>around</u> </p> z';
assert($expected === $processor->process($text)); |
BTW The idea of an event before |
Tomasz, thanks a lot for your quick reply and the code example above. Indeed, I've seen something similar at #40 (comment) ;-). I wonder if it really has to be as complicated as this, since there is already code to do this heavy lifting of merging the original content and the replacements together. I mean, if the Yes, I do know about the advantages of immutable objects... 😀 |
Is it possible to use either
Events::FILTER_SHORTCODES
orEvents::REPLACE_SHORTCODES
to modify/extend the replacement string provided by the handler?I am looking for a way to insert additional HTML (say, a
</div>...<div>
) around shortcodes. When determining this additional HTML, I'd need to know at lease the shortcode name. And I would like to keep this out of the handler, because it is context/situation specific.Any pointers?
The text was updated successfully, but these errors were encountered: