ImageRenderer   A
last analyzed

Complexity

Total Complexity 6

Size/Duplication

Total Lines 45
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 6
eloc 17
dl 0
loc 45
ccs 16
cts 16
cp 1
rs 10
c 1
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A render() 0 24 5
A setConfiguration() 0 3 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\Configuration\ConfigurationAwareInterface;
20
use League\CommonMark\Configuration\ConfigurationInterface;
21
use League\CommonMark\Extension\CommonMark\Node\Inline\Image;
22
use League\CommonMark\Node\Node;
23
use League\CommonMark\Renderer\ChildNodeRendererInterface;
24
use League\CommonMark\Renderer\NodeRendererInterface;
25
use League\CommonMark\Util\HtmlElement;
26
use League\CommonMark\Util\RegexHelper;
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->getData('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 (isset($node->data['title'])) {
64 39
            $attrs['title'] = $node->data['title'];
65
        }
66
67 90
        return new HtmlElement('img', $attrs, '', true);
68
    }
69
70 2847
    public function setConfiguration(ConfigurationInterface $configuration): void
71
    {
72 2847
        $this->config = $configuration;
73 2847
    }
74
}
75