Passed
Pull Request — master (#2009)
by Arnaud
21:25 queued 15:09
created

Parsedown::blockImage()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 12
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 3.2098

Importance

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