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\Image; 21use League\CommonMark\Util\ConfigurationAwareInterface; 22use League\CommonMark\Util\ConfigurationInterface; 23use League\CommonMark\Util\RegexHelper; 24 25final class ImageRenderer implements InlineRendererInterface, ConfigurationAwareInterface 26{ 27 /** 28 * @var ConfigurationInterface 29 */ 30 protected $config; 31 32 /** 33 * @param Image $inline 34 * @param ElementRendererInterface $htmlRenderer 35 * 36 * @return HtmlElement 37 */ 38 public function render(AbstractInline $inline, ElementRendererInterface $htmlRenderer) 39 { 40 if (!($inline instanceof Image)) { 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['src'] = ''; 49 } else { 50 $attrs['src'] = $inline->getUrl(); 51 } 52 53 $alt = $htmlRenderer->renderInlines($inline->children()); 54 $alt = \preg_replace('/\<[^>]*alt="([^"]*)"[^>]*\>/', '$1', $alt); 55 $attrs['alt'] = \preg_replace('/\<[^>]*\>/', '', $alt); 56 57 if (isset($inline->data['title'])) { 58 $attrs['title'] = $inline->data['title']; 59 } 60 61 return new HtmlElement('img', $attrs, '', true); 62 } 63 64 public function setConfiguration(ConfigurationInterface $configuration) 65 { 66 $this->config = $configuration; 67 } 68} 69