castopod/modules/Plugins/ExternalLinkProcessor.php
Yassine Doghri dfb7888aeb feat(plugins): add aside with plugin metadata next to plugin's readme
- enhance plugin card ui
- refactor components to be more consistent
- invert toggler label for better UX
- edit view components regex
2024-06-14 15:53:33 +00:00

46 lines
1.2 KiB
PHP

<?php
declare(strict_types=1);
namespace Modules\Plugins;
use CodeIgniter\HTTP\URI;
use League\CommonMark\Event\DocumentParsedEvent;
use League\CommonMark\Extension\CommonMark\Node\Inline\Link;
class ExternalLinkProcessor
{
public function onDocumentParsed(DocumentParsedEvent $event): void
{
$document = $event->getDocument();
$walker = $document->walker();
while ($event = $walker->next()) {
$node = $event->getNode();
// Only stop at Link nodes when we first encounter them
if (! ($node instanceof Link) || ! $event->isEntering()) {
continue;
}
$url = $node->getUrl();
if ($this->isUrlExternal($url)) {
$node->data->append('attributes/target', '_blank');
$node->data->append('attributes/rel', 'noopener noreferrer');
}
}
}
private function isUrlExternal(string $url): bool
{
// Only look at http and https URLs
if (! preg_match('/^https?:\/\//', $url)) {
return false;
}
$host = parse_url($url, PHP_URL_HOST);
// TODO: load from environment's config
return $host !== (new URI(base_url()))->getHost();
}
}