Skip to content

Instantly share code, notes, and snippets.

@drewm
Created May 9, 2018 11:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save drewm/93552813137892c1ac3ab1073cbbac76 to your computer and use it in GitHub Desktop.
Save drewm/93552813137892c1ac3ab1073cbbac76 to your computer and use it in GitHub Desktop.
Adding rel="noopener" to PHP CommonMark
<?php
namespace Notist\Extensions;
use League\CommonMark\ElementRendererInterface;
use League\CommonMark\HtmlElement;
use League\CommonMark\Inline\Element\AbstractInline;
use League\CommonMark\Inline\Element\Link;
use League\CommonMark\Inline\Renderer\InlineRendererInterface;
class ExternalLinkRenderer implements InlineRendererInterface
{
private $host;
public function __construct($host)
{
$this->host = $host;
}
public function render(AbstractInline $inline, ElementRendererInterface $htmlRenderer)
{
if (!($inline instanceof Link)) {
throw new \InvalidArgumentException('Incompatible inline type: ' . get_class($inline));
}
$attrs = [];
$attrs['href'] = $htmlRenderer->escape($inline->getUrl(), true);
if (isset($inline->attributes['title'])) {
$attrs['title'] = $htmlRenderer->escape($inline->data['title'], true);
}
if ($this->isExternalUrl($inline->getUrl())) {
$attrs['target'] = '_blank';
$attrs['rel'] = 'noopener';
}
return new HtmlElement('a', $attrs, $htmlRenderer->renderInlines($inline->children()));
}
private function isExternalUrl($url)
{
return parse_url($url, PHP_URL_HOST) !== $this->host;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment