ImageRenderer::setConfiguration()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
eloc 1
dl 0
loc 3
ccs 2
cts 2
cp 1
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
crap 1
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of the league/commonmark package.
7
 *
8
 * (c) Colin O'Dell <[email protected]>
9
 *
10
 * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js)
11
 *  - (c) John MacFarlane
12
 *
13
 * For the full copyright and license information, please view the LICENSE
14
 * file that was distributed with this source code.
15
 */
16
17
namespace League\CommonMark\Extension\CommonMark\Renderer\Inline;
18
19
use League\CommonMark\Extension\CommonMark\Node\Inline\Image;
20
use League\CommonMark\Node\Node;
21
use League\CommonMark\Renderer\ChildNodeRendererInterface;
22
use League\CommonMark\Renderer\NodeRendererInterface;
23
use League\CommonMark\Util\HtmlElement;
24
use League\CommonMark\Util\RegexHelper;
25
use League\Config\ConfigurationAwareInterface;
26
use League\Config\ConfigurationInterface;
27
28
final class ImageRenderer implements NodeRendererInterface, ConfigurationAwareInterface
29
{
30
    /**
31
     * @var ConfigurationInterface
32
     *
33
     * @psalm-readonly-allow-private-mutation
34
     */
35
    private $config;
36
37
    /**
38
     * @param Image $node
39
     *
40
     * {@inheritdoc}
41
     *
42
     * @psalm-suppress MoreSpecificImplementedParamType
43
     */
44 93
    public function render(Node $node, ChildNodeRendererInterface $childRenderer)
45
    {
46 93
        if (! ($node instanceof Image)) {
47 3
            throw new \InvalidArgumentException('Incompatible node type: ' . \get_class($node));
48
        }
49
50 90
        $attrs = $node->data->get('attributes');
51
52 90
        $forbidUnsafeLinks = ! $this->config->get('allow_unsafe_links');
53 90
        if ($forbidUnsafeLinks && RegexHelper::isLinkPotentiallyUnsafe($node->getUrl())) {
54 3
            $attrs['src'] = '';
55
        } else {
56 87
            $attrs['src'] = $node->getUrl();
57
        }
58
59 90
        $alt          = $childRenderer->renderNodes($node->children());
60 90
        $alt          = \preg_replace('/\<[^>]*alt="([^"]*)"[^>]*\>/', '$1', $alt);
61 90
        $attrs['alt'] = \preg_replace('/\<[^>]*\>/', '', $alt ?? '');
62
63 90
        if ($node->data->has('title')) {
64 39
            $attrs['title'] = $node->data->get('title');
65
        }
66
67 90
        return new HtmlElement('img', $attrs, '', true);
68
    }
69
70 3003
    public function setConfiguration(ConfigurationInterface $configuration): void
71
    {
72 3003
        $this->config = $configuration;
73 3003
    }
74
}
75