1<?php
2
3/*
4 * This file is part of the league/commonmark package.
5 *
6 * (c) Colin O'Dell <colinodell@gmail.com>
7 *
8 * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js)
9 *  - (c) John MacFarlane
10 *
11 * For the full copyright and license information, please view the LICENSE
12 * file that was distributed with this source code.
13 */
14
15namespace League\CommonMark\Inline\Renderer;
16
17use League\CommonMark\ElementRendererInterface;
18use League\CommonMark\HtmlElement;
19use League\CommonMark\Inline\Element\AbstractInline;
20use League\CommonMark\Inline\Element\Link;
21use League\CommonMark\Util\ConfigurationAwareInterface;
22use League\CommonMark\Util\ConfigurationInterface;
23use League\CommonMark\Util\RegexHelper;
24
25final class LinkRenderer implements InlineRendererInterface, ConfigurationAwareInterface
26{
27    /**
28     * @var ConfigurationInterface
29     */
30    protected $config;
31
32    /**
33     * @param Link                     $inline
34     * @param ElementRendererInterface $htmlRenderer
35     *
36     * @return HtmlElement
37     */
38    public function render(AbstractInline $inline, ElementRendererInterface $htmlRenderer)
39    {
40        if (!($inline instanceof Link)) {
41            throw new \InvalidArgumentException('Incompatible inline type: ' . \get_class($inline));
42        }
43
44        $attrs = $inline->getData('attributes', []);
45
46        $forbidUnsafeLinks = !$this->config->get('allow_unsafe_links');
47        if (!($forbidUnsafeLinks && RegexHelper::isLinkPotentiallyUnsafe($inline->getUrl()))) {
48            $attrs['href'] = $inline->getUrl();
49        }
50
51        if (isset($inline->data['title'])) {
52            $attrs['title'] = $inline->data['title'];
53        }
54
55        if (isset($attrs['target']) && $attrs['target'] === '_blank' && !isset($attrs['rel'])) {
56            $attrs['rel'] = 'noopener noreferrer';
57        }
58
59        return new HtmlElement('a', $attrs, $htmlRenderer->renderInlines($inline->children()));
60    }
61
62    public function setConfiguration(ConfigurationInterface $configuration)
63    {
64        $this->config = $configuration;
65    }
66}
67