Passed
Push — master ( a7f3b3...6b5943 )
by Arnaud
07:11
created

Parsedown::inlineImage()   F

Complexity

Conditions 41
Paths > 20000

Size

Total Lines 220
Code Lines 121

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 72
CRAP Score 144.5997

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 41
eloc 121
c 1
b 0
f 0
nc 1051213
nop 1
dl 0
loc 220
ccs 72
cts 119
cp 0.605
crap 144.5997
rs 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of Cecil.
7
 *
8
 * Copyright (c) Arnaud Ligny <[email protected]>
9
 *
10
 * For the full copyright and license information, please view the LICENSE
11
 * file that was distributed with this source code.
12
 */
13
14
namespace Cecil\Converter;
15
16
use Cecil\Assets\Asset;
17
use Cecil\Assets\Image;
18
use Cecil\Builder;
19
use Cecil\Exception\RuntimeException;
20
use Cecil\Url;
21
use Cecil\Util;
22
use Highlight\Highlighter;
23
24
/**
25
 * @property array $InlineTypes
26
 * @property string $inlineMarkerList
27
 * @property array $specialCharacters
28
 * @property array $BlockTypes
29
 */
30
class Parsedown extends \ParsedownToc
31
{
32
    /** @var Builder */
33
    protected $builder;
34
35
    /** @var \Cecil\Config */
36
    protected $config;
37
38
    /** {@inheritdoc} */
39
    protected $regexAttribute = '(?:[#.][-\w:\\\]+[ ]*|[-\w:\\\]+(?:=(?:["\'][^\n]*?["\']|[^\s]+)?)?[ ]*)';
40
41
    /** Regex who's looking for images */
42
    protected $regexImage = "~^!\[.*?\]\(.*?\)~";
43
44
    /** @var Highlighter */
45
    protected $highlighter;
46
47 1
    public function __construct(Builder $builder, ?array $options = null)
48
    {
49 1
        $this->builder = $builder;
50 1
        $this->config = $builder->getConfig();
51
52
        // "insert" line block: ++text++ -> <ins>text</ins>
53 1
        $this->InlineTypes['+'][] = 'Insert';
54 1
        $this->inlineMarkerList = implode('', array_keys($this->InlineTypes));
55 1
        $this->specialCharacters[] = '+';
56
57
        // Image block (to avoid paragraph)
58 1
        $this->BlockTypes['!'][] = 'Image';
59
60
        // "notes" block
61 1
        $this->BlockTypes[':'][] = 'Note';
62
63
        // code highlight
64 1
        $this->highlighter = new Highlighter();
65
66
        // options
67 1
        $options = array_merge(['selectors' => (array) $this->config->get('pages.body.toc')], $options ?? []);
68
69 1
        parent::__construct();
70 1
        parent::setOptions($options);
71
    }
72
73
    /**
74
     * Insert inline.
75
     * e.g.: ++text++ -> <ins>text</ins>.
76
     */
77 1
    protected function inlineInsert($Excerpt)
78
    {
79 1
        if (!isset($Excerpt['text'][1])) {
80
            return;
81
        }
82
83 1
        if ($Excerpt['text'][1] === '+' && preg_match('/^\+\+(?=\S)(.+?)(?<=\S)\+\+/', $Excerpt['text'], $matches)) {
84 1
            return [
85 1
                'extent'  => \strlen($matches[0]),
86 1
                'element' => [
87 1
                    'name'    => 'ins',
88 1
                    'text'    => $matches[1],
89 1
                    'handler' => 'line',
90 1
                ],
91 1
            ];
92
        }
93
    }
94
95
    /**
96
     * {@inheritdoc}
97
     */
98 1
    protected function inlineLink($Excerpt)
99
    {
100 1
        $link = parent::inlineLink($Excerpt); // @phpstan-ignore staticMethod.notFound
101
102 1
        if (!isset($link)) {
103
            return null;
104
        }
105
106
        // Link to a page with "page:page_id" as URL
107 1
        if (Util\Str::startsWith($link['element']['attributes']['href'], 'page:')) {
108 1
            $link['element']['attributes']['href'] = new Url($this->builder, substr($link['element']['attributes']['href'], 5, \strlen($link['element']['attributes']['href'])));
109
110 1
            return $link;
111
        }
112
113
        // External link
114
        if (
115 1
            str_starts_with($link['element']['attributes']['href'], 'http')
116 1
            && (!empty($this->config->get('baseurl')) && !str_starts_with($link['element']['attributes']['href'], (string) $this->config->get('baseurl')))
117
        ) {
118 1
            if ($this->config->get('pages.body.links.external.blank')) {
119
                $link['element']['attributes']['target'] = '_blank';
120
            }
121 1
            if (!\array_key_exists('rel', $link['element']['attributes'])) {
122 1
                $link['element']['attributes']['rel'] = '';
123
            }
124 1
            if ($this->config->get('pages.body.links.external.noopener')) {
125 1
                $link['element']['attributes']['rel'] .= ' noopener';
126
            }
127 1
            if ($this->config->get('pages.body.links.external.noreferrer')) {
128 1
                $link['element']['attributes']['rel'] .= ' noreferrer';
129
            }
130 1
            if ($this->config->get('pages.body.links.external.nofollow')) {
131 1
                $link['element']['attributes']['rel'] .= ' nofollow';
132
            }
133 1
            $link['element']['attributes']['rel'] = trim($link['element']['attributes']['rel']);
134
        }
135
136
        /*
137
         * Embed link?
138
         */
139 1
        $embed = false;
140 1
        $embed = (bool) $this->config->get('pages.body.links.embed.enabled');
141 1
        if (isset($link['element']['attributes']['embed'])) {
142 1
            $embed = true;
143 1
            if ($link['element']['attributes']['embed'] == 'false') {
144 1
                $embed = false;
145
            }
146 1
            unset($link['element']['attributes']['embed']);
147
        }
148 1
        $extension = pathinfo($link['element']['attributes']['href'], PATHINFO_EXTENSION);
149
        // video?
150 1
        if (\in_array($extension, $this->config->get('pages.body.links.embed.video') ?? ['mp4', 'webm'])) {
151
            if (!$embed) {
152
                $link['element']['attributes']['href'] = (string) new Asset($this->builder, $link['element']['attributes']['href'], ['force_slash' => false]);
153
154
                return $link;
155
            }
156
            $video = $this->createMediaFromLink($link, 'video');
157
            if ((bool) $this->config->get('pages.body.images.caption.enabled')) {
158
                return $this->createFigure($video);
159
            }
160
161
            return $video;
162
        }
163
        // audio?
164 1
        if (\in_array($extension, $this->config->get('pages.body.links.embed.audio') ?? ['mp3', 'ogg', 'wav'])) {
165
            if (!$embed) {
166
                $link['element']['attributes']['href'] = (string) new Asset($this->builder, $link['element']['attributes']['href'], ['force_slash' => false]);
167
168
                return $link;
169
            }
170
            $audio = $this->createMediaFromLink($link, 'audio');
171
            if ((bool) $this->config->get('pages.body.images.caption.enabled')) {
172
                return $this->createFigure($audio);
173
            }
174
175
            return $audio;
176
        }
177 1
        if (!$embed) {
178 1
            return $link;
179
        }
180
        // GitHub Gist link?
181
        // https://regex101.com/r/QmCiAL/1
182 1
        $pattern = 'https:\/\/gist\.github.com\/[-a-zA-Z0-9_]+\/[-a-zA-Z0-9_]+';
183 1
        if (preg_match('/' . $pattern . '/is', (string) $link['element']['attributes']['href'], $matches)) {
184 1
            $gist = [
185 1
                'extent'  => $link['extent'],
186 1
                'element' => [
187 1
                    'name'       => 'script',
188 1
                    'text'       => $link['element']['text'],
189 1
                    'attributes' => [
190 1
                        'src'   => $matches[0] . '.js',
191 1
                        'title' => $link['element']['attributes']['title'],
192 1
                    ],
193 1
                ],
194 1
            ];
195 1
            if ((bool) $this->config->get('pages.body.images.caption.enabled')) {
196 1
                return $this->createFigure($gist);
197
            }
198
199
            return $gist;
200
        }
201
        // Youtube link?
202
        // https://regex101.com/r/gznM1j/1
203 1
        $pattern = '(?:https?:\/\/)?(?:www\.)?youtu(?:\.be\/|be.com\/\S*(?:watch|embed)(?:(?:(?=\/[-a-zA-Z0-9_]{11,}(?!\S))\/)|(?:\S*v=|v\/)))([-a-zA-Z0-9_]{11,})';
204 1
        if (preg_match('/' . $pattern . '/is', (string) $link['element']['attributes']['href'], $matches)) {
205 1
            $iframe = [
206 1
                'element' => [
207 1
                    'name'       => 'iframe',
208 1
                    'text'       => $link['element']['text'],
209 1
                    'attributes' => [
210 1
                        'width'           => '560',
211 1
                        'height'          => '315',
212 1
                        'title'           => $link['element']['text'],
213 1
                        'src'             => 'https://www.youtube.com/embed/' . $matches[1],
214 1
                        'frameborder'     => '0',
215 1
                        'allow'           => 'accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture',
216 1
                        'allowfullscreen' => '',
217 1
                        'style'           => 'position:absolute; top:0; left:0; width:100%; height:100%; border:0',
218 1
                    ],
219 1
                ],
220 1
            ];
221 1
            $youtube = [
222 1
                'extent'  => $link['extent'],
223 1
                'element' => [
224 1
                    'name'    => 'div',
225 1
                    'handler' => 'elements',
226 1
                    'text'    => [
227 1
                        $iframe['element'],
228 1
                    ],
229 1
                    'attributes' => [
230 1
                        'style' => 'position:relative; padding-bottom:56.25%; height:0; overflow:hidden',
231 1
                        'title' => $link['element']['attributes']['title'],
232 1
                    ],
233 1
                ],
234 1
            ];
235 1
            if ((bool) $this->config->get('pages.body.images.caption.enabled')) {
236 1
                return $this->createFigure($youtube);
237
            }
238
239
            return $youtube;
240
        }
241
242 1
        return $link;
243
    }
244
245
    /**
246
     * {@inheritdoc}
247
     */
248 1
    protected function inlineImage($Excerpt)
249
    {
250 1
        $InlineImage = parent::inlineImage($Excerpt); // @phpstan-ignore staticMethod.notFound
251 1
        if (!isset($InlineImage)) {
252
            return null;
253
        }
254
255
        // normalize path
256 1
        $InlineImage['element']['attributes']['src'] = $this->normalizePath($InlineImage['element']['attributes']['src']);
257
258
        // should be lazy loaded?
259 1
        if ((bool) $this->config->get('pages.body.images.lazy.enabled') && !isset($InlineImage['element']['attributes']['loading'])) {
260 1
            $InlineImage['element']['attributes']['loading'] = 'lazy';
261
        }
262
        // should be decoding async?
263 1
        if ((bool) $this->config->get('pages.body.images.decoding.enabled') && !isset($InlineImage['element']['attributes']['decoding'])) {
264 1
            $InlineImage['element']['attributes']['decoding'] = 'async';
265
        }
266
        // add default class?
267 1
        if ((string) $this->config->get('pages.body.images.class')) {
268 1
            if (!\array_key_exists('class', $InlineImage['element']['attributes'])) {
269 1
                $InlineImage['element']['attributes']['class'] = '';
270
            }
271 1
            $InlineImage['element']['attributes']['class'] .= ' ' . (string) $this->config->get('pages.body.images.class');
272 1
            $InlineImage['element']['attributes']['class'] = trim($InlineImage['element']['attributes']['class']);
273
        }
274
275
        // disable remote image handling?
276 1
        if (Util\Url::isUrl($InlineImage['element']['attributes']['src']) && !(bool) $this->config->get('pages.body.images.remote.enabled')) {
277
            return $InlineImage;
278
        }
279
280
        // create asset
281 1
        $assetOptions = ['force_slash' => false];
282 1
        if ((bool) $this->config->get('pages.body.images.remote.fallback.enabled')) {
283 1
            $assetOptions += ['remote_fallback' => (string) $this->config->get('pages.body.images.remote.fallback.path')];
284
        }
285 1
        $asset = new Asset($this->builder, $InlineImage['element']['attributes']['src'], $assetOptions);
286 1
        $InlineImage['element']['attributes']['src'] = $asset;
287 1
        $width = $asset['width'];
288
289
        /*
290
         * Should be resized?
291
         */
292 1
        $shouldResize = false;
293 1
        $assetResized = null;
294
        if (
295 1
            (bool) $this->config->get('pages.body.images.resize.enabled')
296 1
            && isset($InlineImage['element']['attributes']['width'])
297 1
            && $width > (int) $InlineImage['element']['attributes']['width']
298
        ) {
299 1
            $shouldResize = true;
300 1
            $width = (int) $InlineImage['element']['attributes']['width'];
301
        }
302
        if (
303 1
            (bool) $this->config->get('pages.body.images.responsive.enabled')
304 1
            && !empty($this->config->getAssetsImagesWidths())
305 1
            && $width > max($this->config->getAssetsImagesWidths())
306
        ) {
307
            $shouldResize = true;
308
            $width = max($this->config->getAssetsImagesWidths());
309
        }
310 1
        if ($shouldResize) {
311
            try {
312 1
                $assetResized = $asset->resize($width);
313 1
                $InlineImage['element']['attributes']['src'] = $assetResized;
314
            } catch (\Exception $e) {
315
                $this->builder->getLogger()->debug($e->getMessage());
316
317
                return $InlineImage;
318
            }
319
        }
320
321
        // set width
322 1
        $InlineImage['element']['attributes']['width'] = $width;
323
        // set height
324 1
        $InlineImage['element']['attributes']['height'] = $assetResized['height'] ?? $asset['height'];
325
326
        // placeholder
327
        if (
328 1
            (!empty($this->config->get('pages.body.images.placeholder')) || isset($InlineImage['element']['attributes']['placeholder']))
329 1
            && \in_array($InlineImage['element']['attributes']['src']['subtype'], ['image/jpeg', 'image/png', 'image/gif'])
330
        ) {
331 1
            if (!\array_key_exists('placeholder', $InlineImage['element']['attributes'])) {
332
                $InlineImage['element']['attributes']['placeholder'] = (string) $this->config->get('pages.body.images.placeholder');
333
            }
334 1
            if (!\array_key_exists('style', $InlineImage['element']['attributes'])) {
335 1
                $InlineImage['element']['attributes']['style'] = '';
336
            }
337 1
            $InlineImage['element']['attributes']['style'] = trim($InlineImage['element']['attributes']['style'], ';');
338 1
            switch ($InlineImage['element']['attributes']['placeholder']) {
339 1
                case 'color':
340 1
                    $InlineImage['element']['attributes']['style'] .= \sprintf(';max-width:100%%;height:auto;background-color:%s;', Image::getDominantColor($InlineImage['element']['attributes']['src']));
341 1
                    break;
342 1
                case 'lqip':
343
                    // aborts if animated GIF for performance reasons
344 1
                    if (Image::isAnimatedGif($InlineImage['element']['attributes']['src'])) {
345
                        break;
346
                    }
347 1
                    $InlineImage['element']['attributes']['style'] .= \sprintf(';max-width:100%%;height:auto;background-image:url(%s);background-repeat:no-repeat;background-position:center;background-size:cover;', Image::getLqip($InlineImage['element']['attributes']['src']));
348 1
                    break;
349
            }
350 1
            unset($InlineImage['element']['attributes']['placeholder']);
351 1
            $InlineImage['element']['attributes']['style'] = trim($InlineImage['element']['attributes']['style']);
352
        }
353
354
        /*
355
         * Should be responsive?
356
         */
357 1
        $sizes = '';
358 1
        if ((bool) $this->config->get('pages.body.images.responsive.enabled')) {
359
            try {
360
                if (
361 1
                    $srcset = Image::buildSrcset(
362 1
                        $assetResized ?? $asset,
363 1
                        $this->config->getAssetsImagesWidths()
364 1
                    )
365
                ) {
366
                    $InlineImage['element']['attributes']['srcset'] = $srcset;
367
                    $sizes = Image::getSizes($InlineImage['element']['attributes']['class'] ?? '', (array) $this->config->getAssetsImagesSizes());
368 1
                    $InlineImage['element']['attributes']['sizes'] = $sizes;
369
                }
370
            } catch (\Exception $e) {
371
                $this->builder->getLogger()->debug($e->getMessage());
372
            }
373
        }
374
375
        /*
376
        <!-- if title: a <figure> is required to put in it a <figcaption> -->
377
        <figure>
378
            <!-- if formats: a <picture> is required for each <source> -->
379
            <picture>
380
                <source type="image/avif"
381
                    srcset="..."
382
                    sizes="..."
383
                >
384
                <source type="image/webp"
385
                    srcset="..."
386
                    sizes="..."
387
                >
388
                <img src="..."
389
                    srcset="..."
390
                    sizes="..."
391
                >
392
            </picture>
393
            <figcaption><!-- title --></figcaption>
394
        </figure>
395
        */
396
397 1
        $image = $InlineImage;
398
399
        // converts image to formats and put them in picture > source
400
        if (
401 1
            \count($formats = ((array) $this->config->get('pages.body.images.formats'))) > 0
402 1
            && \in_array($InlineImage['element']['attributes']['src']['subtype'], ['image/jpeg', 'image/png', 'image/gif'])
403
        ) {
404
            try {
405
                // InlineImage src must be an Asset instance
406 1
                if (!$InlineImage['element']['attributes']['src'] instanceof Asset) {
407
                    throw new RuntimeException(\sprintf('Asset "%s" can\'t be converted.', $InlineImage['element']['attributes']['src']));
408
                }
409
                // abord if InlineImage is an animated GIF
410 1
                if (Image::isAnimatedGif($InlineImage['element']['attributes']['src'])) {
411 1
                    $filepath = Util::joinFile($this->config->getOutputPath(), $InlineImage['element']['attributes']['src']['path']);
412 1
                    throw new RuntimeException(\sprintf('Asset "%s" is not converted (animated GIF).', $filepath));
413
                }
414 1
                $sources = [];
415 1
                foreach ($formats as $format) {
416 1
                    $assetConverted = $InlineImage['element']['attributes']['src']->$format();
417
                    $srcset = '';
418
                    // build responsive images?
419
                    if ((bool) $this->config->get('pages.body.images.responsive.enabled')) {
420
                        try {
421
                            $srcset = Image::buildSrcset($assetConverted, $this->config->getAssetsImagesWidths());
422
                        } catch (\Exception $e) {
423
                            $this->builder->getLogger()->debug($e->getMessage());
424
                        }
425
                    }
426
                    // if not, use default image as srcset
427
                    if (empty($srcset)) {
428
                        $srcset = (string) $assetConverted;
429
                    }
430
                    $sources[] = [
431
                        'name'       => 'source',
432
                        'attributes' => [
433
                            'type'   => "image/$format",
434
                            'srcset' => $srcset,
435
                            'sizes'  => $sizes,
436
                            'width'  => $InlineImage['element']['attributes']['width'],
437
                            'height' => $InlineImage['element']['attributes']['height'],
438
                        ],
439
                    ];
440
                }
441
                if (\count($sources) > 0) {
442
                    $picture = [
443
                        'extent'  => $InlineImage['extent'],
444
                        'element' => [
445
                            'name'       => 'picture',
446
                            'handler'    => 'elements',
447
                            'attributes' => [
448
                                'title' => $image['element']['attributes']['title'],
449
                            ],
450
                        ],
451
                    ];
452
                    $picture['element']['text'] = $sources;
453
                    unset($image['element']['attributes']['title']); // @phpstan-ignore unset.offset
454
                    $picture['element']['text'][] = $image['element'];
455
                    $image = $picture;
456
                }
457 1
            } catch (\Exception $e) {
458 1
                $this->builder->getLogger()->debug($e->getMessage());
459
            }
460
        }
461
462
        // if title: put the <img> (or <picture>) in a <figure> and create a <figcaption>
463 1
        if ((bool) $this->config->get('pages.body.images.caption.enabled')) {
464 1
            return $this->createFigure($image);
465
        }
466
467
        return $image;
468
    }
469
470
    /**
471
     * Image block.
472
     */
473 1
    protected function blockImage($Excerpt)
474
    {
475 1
        if (1 !== preg_match($this->regexImage, $Excerpt['text'])) {
476
            return;
477
        }
478
479 1
        $InlineImage = $this->inlineImage($Excerpt);
480 1
        if (!isset($InlineImage)) {
481
            return;
482
        }
483
484 1
        return $InlineImage;
485
    }
486
487
    /**
488
     * Note block-level markup.
489
     *
490
     * :::tip
491
     * **Tip:** This is an advice.
492
     * :::
493
     *
494
     * Code inspired by https://github.com/sixlive/parsedown-alert from TJ Miller (@sixlive).
495
     */
496 1
    protected function blockNote($block)
497
    {
498 1
        if (preg_match('/:::(.*)/', $block['text'], $matches)) {
499 1
            $block = [
500 1
                'char'    => ':',
501 1
                'element' => [
502 1
                    'name'       => 'aside',
503 1
                    'text'       => '',
504 1
                    'attributes' => [
505 1
                        'class' => 'note',
506 1
                    ],
507 1
                ],
508 1
            ];
509 1
            if (!empty($matches[1])) {
510 1
                $block['element']['attributes']['class'] .= " note-{$matches[1]}";
511
            }
512
513 1
            return $block;
514
        }
515
    }
516
517 1
    protected function blockNoteContinue($line, $block)
518
    {
519 1
        if (isset($block['complete'])) {
520 1
            return;
521
        }
522 1
        if (preg_match('/:::/', $line['text'])) {
523 1
            $block['complete'] = true;
524
525 1
            return $block;
526
        }
527 1
        $block['element']['text'] .= $line['text'] . "\n";
528
529 1
        return $block;
530
    }
531
532 1
    protected function blockNoteComplete($block)
533
    {
534 1
        $block['element']['rawHtml'] = $this->text($block['element']['text']);
535 1
        unset($block['element']['text']);
536
537 1
        return $block;
538
    }
539
540
    /**
541
     * Apply Highlight to code blocks.
542
     */
543 1
    protected function blockFencedCodeComplete($block)
544
    {
545 1
        if (!(bool) $this->config->get('pages.body.highlight.enabled')) {
546
            return $block;
547
        }
548 1
        if (!isset($block['element']['text']['attributes'])) {
549
            return $block;
550
        }
551
552
        try {
553 1
            $code = $block['element']['text']['text'];
554 1
            $languageClass = $block['element']['text']['attributes']['class'];
555 1
            $language = explode('-', $languageClass);
556 1
            $highlighted = $this->highlighter->highlight($language[1], $code);
557 1
            $block['element']['text']['attributes']['class'] = vsprintf('%s hljs %s', [
558 1
                $languageClass,
559 1
                $highlighted->language,
560 1
            ]);
561 1
            $block['element']['text']['rawHtml'] = $highlighted->value;
562 1
            $block['element']['text']['allowRawHtmlInSafeMode'] = true;
563 1
            unset($block['element']['text']['text']);
564
        } catch (\Exception $e) {
565
            $this->builder->getLogger()->debug($e->getMessage());
566
        } finally {
567 1
            return $block;
568
        }
569
    }
570
571
    /**
572
     * {@inheritdoc}
573
     */
574 1
    protected function parseAttributeData($attributeString)
575
    {
576 1
        $attributes = preg_split('/[ ]+/', $attributeString, -1, PREG_SPLIT_NO_EMPTY);
577 1
        $Data = [];
578 1
        $HtmlAtt = [];
579
580 1
        if (is_iterable($attributes)) {
581 1
            foreach ($attributes as $attribute) {
582 1
                switch ($attribute[0]) {
583 1
                    case '#': // ID
584 1
                        $Data['id'] = substr($attribute, 1);
585 1
                        break;
586 1
                    case '.': // Classes
587 1
                        $classes[] = substr($attribute, 1);
588 1
                        break;
589
                    default:  // Attributes
590 1
                        parse_str($attribute, $parsed);
591 1
                        $HtmlAtt = array_merge($HtmlAtt, $parsed);
592
                }
593
            }
594
595 1
            if (isset($classes)) {
596 1
                $Data['class'] = implode(' ', $classes);
597
            }
598 1
            if (!empty($HtmlAtt)) {
599 1
                foreach ($HtmlAtt as $a => $v) {
600 1
                    $Data[$a] = trim($v, '"');
601
                }
602
            }
603
        }
604
605 1
        return $Data;
606
    }
607
608
    /**
609
     * {@inheritdoc}
610
     *
611
     * Converts XHTML '<br />' tag to '<br>'.
612
     *
613
     * @return string
614
     */
615 1
    protected function unmarkedText($text)
616
    {
617 1
        return str_replace('<br />', '<br>', parent::unmarkedText($text)); // @phpstan-ignore staticMethod.notFound
618
    }
619
620
    /**
621
     * {@inheritdoc}
622
     *
623
     * XHTML closing tag to HTML5 closing tag.
624
     *
625
     * @return string
626
     */
627 1
    protected function element(array $Element)
628
    {
629 1
        return str_replace(' />', '>', parent::element($Element)); // @phpstan-ignore staticMethod.notFound
630
    }
631
632
    /**
633
     * Turns a path relative to static or assets into a website relative path.
634
     *
635
     *   "../../assets/images/img.jpeg"
636
     *   ->
637
     *   "/images/img.jpeg"
638
     */
639 1
    private function normalizePath(string $path): string
640
    {
641
        // https://regex101.com/r/Rzguzh/1
642 1
        $pattern = \sprintf(
643 1
            '(\.\.\/)+(\b%s|%s\b)+(\/.*)',
644 1
            (string) $this->config->get('static.dir'),
645 1
            (string) $this->config->get('assets.dir')
646 1
        );
647 1
        $path = Util::joinPath($path);
648 1
        if (!preg_match('/' . $pattern . '/is', $path, $matches)) {
649 1
            return $path;
650
        }
651
652 1
        return $matches[3];
653
    }
654
655
    /**
656
     * Create a media (video or audio) element from a link.
657
     */
658
    private function createMediaFromLink(array $link, string $type = 'video'): array
659
    {
660
        $block = [
661
            'extent'  => $link['extent'],
662
            'element' => [
663
                'text' => $link['element']['text'],
664
            ],
665
        ];
666
        $block['element']['attributes'] = $link['element']['attributes'];
667
        unset($block['element']['attributes']['href']);
668
        $block['element']['attributes']['src'] = (string) new Asset($this->builder, $link['element']['attributes']['href'], ['force_slash' => false]);
669
        switch ($type) {
670
            case 'video':
671
                $block['element']['name'] = 'video';
672
                if (!isset($block['element']['attributes']['controls'])) {
673
                    $block['element']['attributes']['autoplay'] = '';
674
                    $block['element']['attributes']['loop'] = '';
675
                }
676
                if (isset($block['element']['attributes']['poster'])) {
677
                    $block['element']['attributes']['poster'] = (string) new Asset($this->builder, $block['element']['attributes']['poster'], ['force_slash' => false]);
678
                }
679
                $block['element']['attributes']['style'] = 'background-color: #d8d8d8;'; // background color if offline
680
681
                return $block;
682
            case 'audio':
683
                $block['element']['name'] = 'audio';
684
685
                return $block;
686
        }
687
688
        throw new \Exception(\sprintf('Can\'t create %s from "%s".', $type, $link['element']['attributes']['href']));
689
    }
690
691
    /**
692
     * Create a figure / caption element.
693
     */
694 1
    private function createFigure(array $inline): array
695
    {
696 1
        if (empty($inline['element']['attributes']['title'])) {
697 1
            return $inline;
698
        }
699
700 1
        $titleRawHtml = $this->line($inline['element']['attributes']['title']); // @phpstan-ignore method.notFound
701 1
        $inline['element']['attributes']['title'] = strip_tags($titleRawHtml);
702
703 1
        $figcaption = [
704 1
            'element' => [
705 1
                'name'                   => 'figcaption',
706 1
                'allowRawHtmlInSafeMode' => true,
707 1
                'rawHtml'                => $titleRawHtml,
708 1
            ],
709 1
        ];
710 1
        $figure = [
711 1
            'extent'  => $inline['extent'],
712 1
            'element' => [
713 1
                'name'    => 'figure',
714 1
                'handler' => 'elements',
715 1
                'text'    => [
716 1
                    $inline['element'],
717 1
                    $figcaption['element'],
718 1
                ],
719 1
            ],
720 1
        ];
721
722 1
        return $figure;
723
    }
724
}
725