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