Created
May 9, 2018 11:40
-
-
Save drewm/93552813137892c1ac3ab1073cbbac76 to your computer and use it in GitHub Desktop.
Adding rel="noopener" to PHP CommonMark
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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