Passed
Pull Request — master (#2017)
by Arnaud
11:42 queued 05:15
created

Parsedown::createMediaFromLink()   A

Complexity

Conditions 5
Paths 6

Size

Total Lines 30
Code Lines 20

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 21
CRAP Score 5.0023

Importance

Changes 0
Metric Value
cc 5
eloc 20
nc 6
nop 2
dl 0
loc 30
ccs 21
cts 22
cp 0.9545
crap 5.0023
rs 9.2888
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 formats: a <picture> is required for each <source> -->
369
            <picture>
370
                <source type="image/avif"
371
                    srcset="..."
372
                    sizes="..."
373
                >
374
                <source type="image/webp"
375
                    srcset="..."
376
                    sizes="..."
377
                >
378
                <img src="..."
379
                    srcset="..."
380
                    sizes="..."
381
                >
382
            </picture>
383
            <figcaption><!-- title --></figcaption>
384
        </figure>
385
        */
386
387 1
        $image = $InlineImage;
388
389
        // converts image to formats and put them in picture > source
390
        if (
391 1
            \count($formats = ((array) $this->config->get('pages.body.images.formats') ?? ['webp'])) > 0
392 1
            && \in_array($InlineImage['element']['attributes']['src']['subtype'], ['image/jpeg', 'image/png', 'image/gif'])
393
        ) {
394
            try {
395
                // InlineImage src must be an Asset instance
396 1
                if (!$InlineImage['element']['attributes']['src'] instanceof Asset) {
397
                    throw new RuntimeException(sprintf('Asset "%s" can\'t be converted.', $InlineImage['element']['attributes']['src']));
398
                }
399
                // abord if InlineImage is an animated GIF
400 1
                if (Image::isAnimatedGif($InlineImage['element']['attributes']['src'])) {
401 1
                    throw new RuntimeException(sprintf('Asset "%s" is an animated GIF.', $InlineImage['element']['attributes']['src']));
402
                }
403 1
                foreach ($formats as $format) {
404 1
                    $assetConverted = $InlineImage['element']['attributes']['src']->$format();
405
                    $srcset = '';
406
                    // build responsive images?
407
                    if ((bool) $this->config->get('pages.body.images.responsive.enabled')) {
408
                        try {
409
                            $srcset = Image::buildSrcset($assetConverted, $this->config->getAssetsImagesWidths());
410
                        } catch (\Exception $e) {
411
                            $this->builder->getLogger()->debug($e->getMessage());
412
                        }
413
                    }
414
                    // if not, use default image as srcset
415
                    if (empty($srcset)) {
416
                        $srcset = (string) $assetConverted;
417
                    }
418
                    $sources[] = [
419
                        'name'       => 'source',
420
                        'attributes' => [
421
                            'type'   => "image/$format",
422
                            'srcset' => $srcset,
423
                            'sizes'  => $sizes,
424
                            'width'  => $InlineImage['element']['attributes']['width'],
425
                            'height' => $InlineImage['element']['attributes']['height'],
426
                        ],
427
                    ];
428
                }
429
                $picture = [
430
                    'extent'  => $InlineImage['extent'],
431
                    'element' => [
432
                        'name'       => 'picture',
433
                        'handler'    => 'elements',
434
                        'attributes' => [
435
                            'title' => $image['element']['attributes']['title'],
436
                        ],
437
                    ],
438
                ];
439
                $picture['element']['text'] = $sources;
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $sources seems to be defined by a foreach iteration on line 403. Are you sure the iterator is never empty, otherwise this variable is not defined?
Loading history...
440
                unset($image['element']['attributes']['title']); // @phpstan-ignore unset.offset
441
                $picture['element']['text'][] = $image['element'];
442
                $image = $picture;
443 1
            } catch (\Exception $e) {
444 1
                $this->builder->getLogger()->debug($e->getMessage());
445
            }
446
        }
447
448
        // if title: put the <img> (or <picture>) in a <figure> and create a <figcaption>
449 1
        if ((bool) $this->config->get('pages.body.images.caption.enabled')) {
450 1
            return $this->createFigure($image);
451
        }
452
453
        return $image;
454
    }
455
456
    /**
457
     * Image block.
458
     */
459 1
    protected function blockImage($Excerpt)
460
    {
461 1
        if (1 !== preg_match($this->regexImage, $Excerpt['text'])) {
462
            return;
463
        }
464
465 1
        $InlineImage = $this->inlineImage($Excerpt);
466 1
        if (!isset($InlineImage)) {
467
            return;
468
        }
469
470 1
        return $InlineImage;
471
    }
472
473
    /**
474
     * Note block-level markup.
475
     *
476
     * :::tip
477
     * **Tip:** This is an advice.
478
     * :::
479
     *
480
     * Code inspired by https://github.com/sixlive/parsedown-alert from TJ Miller (@sixlive).
481
     */
482 1
    protected function blockNote($block)
483
    {
484 1
        if (preg_match('/:::(.*)/', $block['text'], $matches)) {
485 1
            $block = [
486 1
                'char'    => ':',
487 1
                'element' => [
488 1
                    'name'       => 'aside',
489 1
                    'text'       => '',
490 1
                    'attributes' => [
491 1
                        'class' => 'note',
492 1
                    ],
493 1
                ],
494 1
            ];
495 1
            if (!empty($matches[1])) {
496 1
                $block['element']['attributes']['class'] .= " note-{$matches[1]}";
497
            }
498
499 1
            return $block;
500
        }
501
    }
502
503 1
    protected function blockNoteContinue($line, $block)
504
    {
505 1
        if (isset($block['complete'])) {
506 1
            return;
507
        }
508 1
        if (preg_match('/:::/', $line['text'])) {
509 1
            $block['complete'] = true;
510
511 1
            return $block;
512
        }
513 1
        $block['element']['text'] .= $line['text'] . "\n";
514
515 1
        return $block;
516
    }
517
518 1
    protected function blockNoteComplete($block)
519
    {
520 1
        $block['element']['rawHtml'] = $this->text($block['element']['text']);
521 1
        unset($block['element']['text']);
522
523 1
        return $block;
524
    }
525
526
    /**
527
     * Apply Highlight to code blocks.
528
     */
529 1
    protected function blockFencedCodeComplete($block)
530
    {
531 1
        if (!(bool) $this->config->get('pages.body.highlight.enabled')) {
532
            return $block;
533
        }
534 1
        if (!isset($block['element']['text']['attributes'])) {
535
            return $block;
536
        }
537
538
        try {
539 1
            $code = $block['element']['text']['text'];
540 1
            $languageClass = $block['element']['text']['attributes']['class'];
541 1
            $language = explode('-', $languageClass);
542 1
            $highlighted = $this->highlighter->highlight($language[1], $code);
543 1
            $block['element']['text']['attributes']['class'] = vsprintf('%s hljs %s', [
544 1
                $languageClass,
545 1
                $highlighted->language,
546 1
            ]);
547 1
            $block['element']['text']['rawHtml'] = $highlighted->value;
548 1
            $block['element']['text']['allowRawHtmlInSafeMode'] = true;
549 1
            unset($block['element']['text']['text']);
550
        } catch (\Exception $e) {
551
            $this->builder->getLogger()->debug($e->getMessage());
552
        } finally {
553 1
            return $block;
554
        }
555
    }
556
557
    /**
558
     * {@inheritdoc}
559
     */
560 1
    protected function parseAttributeData($attributeString)
561
    {
562 1
        $attributes = preg_split('/[ ]+/', $attributeString, -1, PREG_SPLIT_NO_EMPTY);
563 1
        $Data = [];
564 1
        $HtmlAtt = [];
565
566 1
        foreach ($attributes as $attribute) {
567 1
            switch ($attribute[0]) {
568 1
                case '#': // ID
569 1
                    $Data['id'] = substr($attribute, 1);
570 1
                    break;
571 1
                case '.': // Classes
572 1
                    $classes[] = substr($attribute, 1);
573 1
                    break;
574
                default:  // Attributes
575 1
                    parse_str($attribute, $parsed);
576 1
                    $HtmlAtt = array_merge($HtmlAtt, $parsed);
577
            }
578
        }
579
580 1
        if (isset($classes)) {
581 1
            $Data['class'] = implode(' ', $classes);
582
        }
583 1
        if (!empty($HtmlAtt)) {
584 1
            foreach ($HtmlAtt as $a => $v) {
585 1
                $Data[$a] = trim($v, '"');
586
            }
587
        }
588
589 1
        return $Data;
590
    }
591
592
    /**
593
     * Turns a path relative to static or assets into a website relative path.
594
     *
595
     *   "../../assets/images/img.jpeg"
596
     *   ->
597
     *   "/images/img.jpeg"
598
     */
599 1
    private function normalizePath(string $path): string
600
    {
601
        // https://regex101.com/r/Rzguzh/1
602 1
        $pattern = sprintf(
603 1
            '(\.\.\/)+(\b%s|%s\b)+(\/.*)',
604 1
            (string) $this->config->get('static.dir'),
605 1
            (string) $this->config->get('assets.dir')
606 1
        );
607 1
        $path = Util::joinPath($path);
608 1
        if (!preg_match('/' . $pattern . '/is', $path, $matches)) {
609 1
            return $path;
610
        }
611
612 1
        return $matches[3];
613
    }
614
615
    /**
616
     * Create a media (video or audio) element from a link.
617
     */
618 1
    private function createMediaFromLink(array $link, string $type = 'video'): array
619
    {
620 1
        $block = [
621 1
            'extent'  => $link['extent'],
622 1
            'element' => [
623 1
                'text' => $link['element']['text'],
624 1
            ],
625 1
        ];
626 1
        $block['element']['attributes'] = $link['element']['attributes'];
627 1
        unset($block['element']['attributes']['href']);
628 1
        $block['element']['attributes']['src'] = (string) new Asset($this->builder, $link['element']['attributes']['href'], ['force_slash' => false]);
629
        switch ($type) {
630 1
            case 'video':
631 1
                $block['element']['name'] = 'video';
632 1
                if (!isset($block['element']['attributes']['controls'])) {
633 1
                    $block['element']['attributes']['autoplay'] = '';
634 1
                    $block['element']['attributes']['loop'] = '';
635
                }
636 1
                if (isset($block['element']['attributes']['poster'])) {
637 1
                    $block['element']['attributes']['poster'] = (string) new Asset($this->builder, $block['element']['attributes']['poster'], ['force_slash' => false]);
638
                }
639
640 1
                return $block;
641 1
            case 'audio':
642 1
                $block['element']['name'] = 'audio';
643
644 1
                return $block;
645
        }
646
647
        throw new \Exception(sprintf('Can\'t create %s from "%s".', $type, $link['element']['attributes']['href']));
648
    }
649
650
    /**
651
     * Create a figure / caption element.
652
     */
653 1
    private function createFigure(array $inline): array
654
    {
655 1
        if (empty($inline['element']['attributes']['title'])) {
656 1
            return $inline;
657
        }
658
659 1
        $titleRawHtml = $this->line($inline['element']['attributes']['title']); // @phpstan-ignore method.notFound
660 1
        $inline['element']['attributes']['title'] = strip_tags($titleRawHtml);
661
662 1
        $figcaption = [
663 1
            'element' => [
664 1
                'name'                   => 'figcaption',
665 1
                'allowRawHtmlInSafeMode' => true,
666 1
                'rawHtml'                => $titleRawHtml,
667 1
            ],
668 1
        ];
669 1
        $figure = [
670 1
            'extent'  => $inline['extent'],
671 1
            'element' => [
672 1
                'name'    => 'figure',
673 1
                'handler' => 'elements',
674 1
                'text'    => [
675 1
                    $inline['element'],
676 1
                    $figcaption['element'],
677 1
                ],
678 1
            ],
679 1
        ];
680
681 1
        return $figure;
682
    }
683
}
684