Core::markdownToToc()   A
last analyzed

Complexity

Conditions 2
Paths 4

Size

Total Lines 14
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 9
nc 4
nop 4
dl 0
loc 14
rs 9.9666
c 0
b 0
f 0
1
<?php
2
3
/**
4
 * This file is part of Cecil.
5
 *
6
 * (c) Arnaud Ligny <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
declare(strict_types=1);
13
14
namespace Cecil\Renderer\Extension;
15
16
use Cecil\Asset;
17
use Cecil\Asset\Image;
18
use Cecil\Builder;
19
use Cecil\Cache;
20
use Cecil\Collection\CollectionInterface;
21
use Cecil\Collection\Page\Collection as PagesCollection;
22
use Cecil\Collection\Page\Page;
23
use Cecil\Collection\Page\Type;
24
use Cecil\Config;
25
use Cecil\Converter\Parsedown;
26
use Cecil\Exception\ConfigException;
27
use Cecil\Exception\RuntimeException;
28
use Cecil\Url;
29
use Cecil\Util;
30
use Cocur\Slugify\Bridge\Twig\SlugifyExtension;
31
use Cocur\Slugify\Slugify;
32
use Highlight\Highlighter;
33
use MatthiasMullie\Minify;
34
use ScssPhp\ScssPhp\Compiler;
35
use ScssPhp\ScssPhp\OutputStyle;
36
use Symfony\Component\VarDumper\Cloner\VarCloner;
37
use Symfony\Component\VarDumper\Dumper\HtmlDumper;
38
use Symfony\Component\Yaml\Exception\ParseException;
39
use Symfony\Component\Yaml\Yaml;
40
use Twig\DeprecatedCallableInfo;
41
42
/**
43
 * Core Twig extension.
44
 *
45
 * This extension provides various utility functions and filters for use in Twig templates,
46
 * including URL generation, asset management, content processing, and more.
47
 */
48
class Core extends SlugifyExtension
49
{
50
    /** @var Builder */
51
    protected $builder;
52
53
    /** @var Config */
54
    protected $config;
55
56
    /** @var Slugify */
57
    private static $slugifier;
58
59
    public function __construct(Builder $builder)
60
    {
61
        if (!self::$slugifier instanceof Slugify) {
62
            self::$slugifier = Slugify::create(['regexp' => Page::SLUGIFY_PATTERN]);
63
        }
64
65
        parent::__construct(self::$slugifier);
66
67
        $this->builder = $builder;
68
        $this->config = $builder->getConfig();
69
    }
70
71
    /**
72
     * {@inheritdoc}
73
     */
74
    public function getName(): string
75
    {
76
        return 'CoreExtension';
77
    }
78
79
    /**
80
     * {@inheritdoc}
81
     */
82
    public function getFunctions()
83
    {
84
        return [
85
            new \Twig\TwigFunction('url', [$this, 'url'], ['needs_context' => true]),
86
            // assets
87
            new \Twig\TwigFunction('asset', [$this, 'asset']),
88
            new \Twig\TwigFunction('html', [$this, 'html'], ['needs_context' => true]),
89
            new \Twig\TwigFunction('css', [$this, 'htmlCss'], ['needs_context' => true]),
90
            new \Twig\TwigFunction('js', [$this, 'htmlJs'], ['needs_context' => true]),
91
            new \Twig\TwigFunction('image', [$this, 'htmlImage'], ['needs_context' => true]),
92
            new \Twig\TwigFunction('audio', [$this, 'htmlAudio'], ['needs_context' => true]),
93
            new \Twig\TwigFunction('video', [$this, 'htmlVideo'], ['needs_context' => true]),
94
            new \Twig\TwigFunction('integrity', [$this, 'integrity']),
95
            new \Twig\TwigFunction('image_srcset', [$this, 'imageSrcset']),
96
            new \Twig\TwigFunction('image_sizes', [$this, 'imageSizes']),
97
            new \Twig\TwigFunction('image_from_website', [$this, 'htmlImageFromWebsite'], ['needs_context' => true]),
98
            // content
99
            new \Twig\TwigFunction('readtime', [$this, 'readtime']),
100
            new \Twig\TwigFunction('hash', [$this, 'hash']),
101
            // others
102
            new \Twig\TwigFunction('getenv', [$this, 'getEnv']),
103
            new \Twig\TwigFunction('d', [$this, 'varDump'], ['needs_context' => true, 'needs_environment' => true]),
104
            // deprecated
105
            new \Twig\TwigFunction(
106
                'minify',
107
                [$this, 'minify'],
108
                ['deprecation_info' => new DeprecatedCallableInfo('', '', 'minify filter')]
109
            ),
110
            new \Twig\TwigFunction(
111
                'toCSS',
112
                [$this, 'toCss'],
113
                ['deprecation_info' => new DeprecatedCallableInfo('', '', 'to_css filter')]
114
            ),
115
            new \Twig\TwigFunction(
116
                'image_from_url',
117
                [$this, 'htmlImageFromWebsite'],
118
                ['deprecation_info' => new DeprecatedCallableInfo('', '', 'image_from_website function')]
119
            ),
120
        ];
121
    }
122
123
    /**
124
     * {@inheritdoc}
125
     */
126
    public function getFilters(): array
127
    {
128
        return [
129
            new \Twig\TwigFilter('url', [$this, 'url'], ['needs_context' => true]),
130
            // collections
131
            new \Twig\TwigFilter('sort_by_title', [$this, 'sortByTitle']),
132
            new \Twig\TwigFilter('sort_by_weight', [$this, 'sortByWeight']),
133
            new \Twig\TwigFilter('sort_by_date', [$this, 'sortByDate']),
134
            new \Twig\TwigFilter('filter_by', [$this, 'filterBy']),
135
            // assets
136
            new \Twig\TwigFilter('inline', [$this, 'inline']),
137
            new \Twig\TwigFilter('fingerprint', [$this, 'fingerprint']),
138
            new \Twig\TwigFilter('to_css', [$this, 'toCss']),
139
            new \Twig\TwigFilter('minify', [$this, 'minify']),
140
            new \Twig\TwigFilter('minify_css', [$this, 'minifyCss']),
141
            new \Twig\TwigFilter('minify_js', [$this, 'minifyJs']),
142
            new \Twig\TwigFilter('scss_to_css', [$this, 'scssToCss']),
143
            new \Twig\TwigFilter('sass_to_css', [$this, 'scssToCss']),
144
            new \Twig\TwigFilter('resize', [$this, 'resize']),
145
            new \Twig\TwigFilter('maskable', [$this, 'maskable']),
146
            new \Twig\TwigFilter('dataurl', [$this, 'dataurl']),
147
            new \Twig\TwigFilter('dominant_color', [$this, 'dominantColor']),
148
            new \Twig\TwigFilter('lqip', [$this, 'lqip']),
149
            new \Twig\TwigFilter('webp', [$this, 'webp']),
150
            new \Twig\TwigFilter('avif', [$this, 'avif']),
151
            // content
152
            new \Twig\TwigFilter('slugify', [$this, 'slugifyFilter']),
153
            new \Twig\TwigFilter('excerpt', [$this, 'excerpt']),
154
            new \Twig\TwigFilter('excerpt_html', [$this, 'excerptHtml']),
155
            new \Twig\TwigFilter('markdown_to_html', [$this, 'markdownToHtml']),
156
            new \Twig\TwigFilter('toc', [$this, 'markdownToToc']),
157
            new \Twig\TwigFilter('json_decode', [$this, 'jsonDecode']),
158
            new \Twig\TwigFilter('yaml_parse', [$this, 'yamlParse']),
159
            new \Twig\TwigFilter('preg_split', [$this, 'pregSplit']),
160
            new \Twig\TwigFilter('preg_match_all', [$this, 'pregMatchAll']),
161
            new \Twig\TwigFilter('hex_to_rgb', [$this, 'hexToRgb']),
162
            new \Twig\TwigFilter('splitline', [$this, 'splitLine']),
163
            new \Twig\TwigFilter('iterable', [$this, 'iterable']),
164
            new \Twig\TwigFilter('highlight', [$this, 'highlight']),
165
            new \Twig\TwigFilter('unique', [$this, 'unique']),
166
            // date
167
            new \Twig\TwigFilter('duration_to_iso8601', ['\Cecil\Util\Date', 'durationToIso8601']),
168
            // deprecated
169
            new \Twig\TwigFilter(
170
                'html',
171
                [$this, 'html'],
172
                [
173
                    'needs_context' => true,
174
                    'deprecation_info' => new DeprecatedCallableInfo('', '', 'html function')
175
                ]
176
            ),
177
            new \Twig\TwigFilter(
178
                'cover',
179
                [$this, 'resize'],
180
                [
181
                    'needs_context' => true,
182
                    'deprecation_info' => new DeprecatedCallableInfo('', '', 'resize filter')
183
                ]
184
            ),
185
        ];
186
    }
187
188
    /**
189
     * {@inheritdoc}
190
     */
191
    public function getTests()
192
    {
193
        return [
194
            new \Twig\TwigTest('asset', [$this, 'isAsset']),
195
            new \Twig\TwigTest('image_large', [$this, 'isImageLarge']),
196
            new \Twig\TwigTest('image_square', [$this, 'isImageSquare']),
197
        ];
198
    }
199
200
    /**
201
     * Filters by Section.
202
     */
203
    public function filterBySection(PagesCollection $pages, string $section): CollectionInterface
204
    {
205
        return $this->filterBy($pages, 'section', $section);
206
    }
207
208
    /**
209
     * Filters a pages collection by variable's name/value.
210
     */
211
    public function filterBy(PagesCollection $pages, string $variable, string $value): CollectionInterface
212
    {
213
        $filteredPages = $pages->filter(function (Page $page) use ($variable, $value) {
214
            // is a dedicated getter exists?
215
            $method = 'get' . ucfirst($variable);
216
            if (method_exists($page, $method) && $page->$method() == $value) {
217
                return $page->getType() == Type::PAGE->value && !$page->isVirtual() && true;
218
            }
219
            // or a classic variable
220
            if ($page->getVariable($variable) == $value) {
221
                return $page->getType() == Type::PAGE->value && !$page->isVirtual() && true;
222
            }
223
        });
224
225
        return $filteredPages;
226
    }
227
228
    /**
229
     * Sorts a collection by title.
230
     */
231
    public function sortByTitle(\Traversable $collection): array
232
    {
233
        $sort = \SORT_ASC;
234
235
        $collection = iterator_to_array($collection);
236
        array_multisort(array_keys(/** @scrutinizer ignore-type */ $collection), $sort, \SORT_NATURAL | \SORT_FLAG_CASE, $collection);
0 ignored issues
show
Bug introduced by
array_keys($collection) cannot be passed to array_multisort() as the parameter $array expects a reference. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

236
        array_multisort(/** @scrutinizer ignore-type */ array_keys(/** @scrutinizer ignore-type */ $collection), $sort, \SORT_NATURAL | \SORT_FLAG_CASE, $collection);
Loading history...
Bug introduced by
SORT_NATURAL | SORT_FLAG_CASE cannot be passed to array_multisort() as the parameter $rest expects a reference. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

236
        array_multisort(array_keys(/** @scrutinizer ignore-type */ $collection), $sort, /** @scrutinizer ignore-type */ \SORT_NATURAL | \SORT_FLAG_CASE, $collection);
Loading history...
237
238
        return $collection;
239
    }
240
241
    /**
242
     * Sorts a collection by weight.
243
     *
244
     * @param \Traversable|array $collection
245
     */
246
    public function sortByWeight($collection): array
247
    {
248
        $callback = function ($a, $b) {
249
            if (!isset($a['weight'])) {
250
                $a['weight'] = 0;
251
            }
252
            if (!isset($b['weight'])) {
253
                $a['weight'] = 0;
254
            }
255
            if ($a['weight'] == $b['weight']) {
256
                return 0;
257
            }
258
259
            return $a['weight'] < $b['weight'] ? -1 : 1;
260
        };
261
262
        if (!\is_array($collection)) {
263
            $collection = iterator_to_array($collection);
264
        }
265
        usort(/** @scrutinizer ignore-type */ $collection, $callback);
266
267
        return $collection;
268
    }
269
270
    /**
271
     * Sorts by creation date (or 'updated' date): the most recent first.
272
     */
273
    public function sortByDate(\Traversable $collection, string $variable = 'date', bool $descTitle = false): array
274
    {
275
        $callback = function ($a, $b) use ($variable, $descTitle) {
276
            if ($a[$variable] == $b[$variable]) {
277
                // if dates are equal and "descTitle" is true
278
                if ($descTitle && (isset($a['title']) && isset($b['title']))) {
279
                    return strnatcmp($b['title'], $a['title']);
280
                }
281
282
                return 0;
283
            }
284
285
            return $a[$variable] > $b[$variable] ? -1 : 1;
286
        };
287
288
        $collection = iterator_to_array($collection);
289
        usort(/** @scrutinizer ignore-type */ $collection, $callback);
290
291
        return $collection;
292
    }
293
294
    /**
295
     * Creates an URL.
296
     *
297
     * $options[
298
     *     'canonical' => false,
299
     *     'format'    => 'html',
300
     *     'language'  => null,
301
     * ];
302
     *
303
     * @param array                  $context
304
     * @param Page|Asset|string|null $value
305
     * @param array|null             $options
306
     */
307
    public function url(array $context, $value = null, ?array $options = null): string
308
    {
309
        $optionsLang = [];
310
        $optionsLang['language'] = (string) $context['site']['language'];
311
        $options = array_merge($optionsLang, $options ?? []);
312
313
        return (new Url($this->builder, $value, $options))->getUrl();
314
    }
315
316
    /**
317
     * Creates an Asset (CSS, JS, images, etc.) from a path or an array of paths.
318
     *
319
     * @param string|array $path    File path or array of files path (relative from `assets/` or `static/` dir).
320
     * @param array|null   $options
321
     *
322
     * @return Asset
323
     */
324
    public function asset($path, array|null $options = null): Asset
325
    {
326
        if (!\is_string($path) && !\is_array($path)) {
327
            throw new RuntimeException(\sprintf('Argument of "%s()" must a string or an array.', \Cecil\Util::formatMethodName(__METHOD__)));
328
        }
329
330
        return new Asset($this->builder, $path, $options);
331
    }
332
333
    /**
334
     * Compiles a SCSS asset.
335
     *
336
     * @param string|Asset $asset
337
     *
338
     * @return Asset
339
     */
340
    public function toCss($asset): Asset
341
    {
342
        if (!$asset instanceof Asset) {
343
            $asset = new Asset($this->builder, $asset);
344
        }
345
346
        return $asset->compile();
347
    }
348
349
    /**
350
     * Minifying an asset (CSS or JS).
351
     *
352
     * @param string|Asset $asset
353
     *
354
     * @return Asset
355
     */
356
    public function minify($asset): Asset
357
    {
358
        if (!$asset instanceof Asset) {
359
            $asset = new Asset($this->builder, $asset);
360
        }
361
362
        return $asset->minify();
363
    }
364
365
    /**
366
     * Fingerprinting an asset.
367
     *
368
     * @param string|Asset $asset
369
     *
370
     * @return Asset
371
     */
372
    public function fingerprint($asset): Asset
373
    {
374
        if (!$asset instanceof Asset) {
375
            $asset = new Asset($this->builder, $asset);
376
        }
377
378
        return $asset->fingerprint();
379
    }
380
381
    /**
382
     * Resizes an image Asset to the given width or/and height.
383
     *
384
     * - If only the width is specified, the height is calculated to preserve the aspect ratio
385
     * - If only the height is specified, the width is calculated to preserve the aspect ratio
386
     * - If both width and height are specified, the image is resized to fit within the given dimensions, image is cropped and centered if necessary
387
     * - If remove_animation is true, any animation in the image (e.g., GIF) will be removed.
388
     *
389
     * @param string|Asset $asset
390
     *
391
     * @return Asset
392
     */
393
    public function resize($asset, ?int $width = null, ?int $height = null, bool $remove_animation = false): Asset
394
    {
395
        if (!$asset instanceof Asset) {
396
            $asset = new Asset($this->builder, $asset);
397
        }
398
399
        return $asset->resize(width: $width, height: $height, rmAnimation: $remove_animation);
400
    }
401
402
    /**
403
     * Creates a maskable icon from an image asset.
404
     * The maskable icon is used for Progressive Web Apps (PWAs).
405
     *
406
     * @param string|Asset $asset
407
     *
408
     * @return Asset
409
     */
410
    public function maskable($asset, ?int $padding = null): Asset
411
    {
412
        if (!$asset instanceof Asset) {
413
            $asset = new Asset($this->builder, $asset);
414
        }
415
416
        return $asset->maskable($padding);
417
    }
418
419
    /**
420
     * Returns the data URL of an image.
421
     *
422
     * @param string|Asset $asset
423
     *
424
     * @return string
425
     */
426
    public function dataurl($asset): string
427
    {
428
        if (!$asset instanceof Asset) {
429
            $asset = new Asset($this->builder, $asset);
430
        }
431
432
        return $asset->dataurl();
433
    }
434
435
    /**
436
     * Hashing an asset with algo (sha384 by default).
437
     *
438
     * @param string|Asset $asset
439
     * @param string       $algo
440
     *
441
     * @return string
442
     */
443
    public function integrity($asset, string $algo = 'sha384'): string
444
    {
445
        if (!$asset instanceof Asset) {
446
            $asset = new Asset($this->builder, $asset);
447
        }
448
449
        return $asset->integrity($algo);
450
    }
451
452
    /**
453
     * Minifying a CSS string.
454
     */
455
    public function minifyCss(?string $value): string
456
    {
457
        $value = $value ?? '';
458
459
        if ($this->builder->isDebug()) {
460
            return $value;
461
        }
462
463
        $cache = new Cache($this->builder, 'assets');
464
        $cacheKey = $cache->createKeyFromValue(null, $value);
465
        if (!$cache->has($cacheKey)) {
466
            $minifier = new Minify\CSS($value);
467
            $value = $minifier->minify();
468
            $cache->set($cacheKey, $value, $this->config->get('cache.assets.ttl'));
469
        }
470
471
        return $cache->get($cacheKey, $value);
472
    }
473
474
    /**
475
     * Minifying a JavaScript string.
476
     */
477
    public function minifyJs(?string $value): string
478
    {
479
        $value = $value ?? '';
480
481
        if ($this->builder->isDebug()) {
482
            return $value;
483
        }
484
485
        $cache = new Cache($this->builder, 'assets');
486
        $cacheKey = $cache->createKeyFromValue(null, $value);
487
        if (!$cache->has($cacheKey)) {
488
            $minifier = new Minify\JS($value);
489
            $value = $minifier->minify();
490
            $cache->set($cacheKey, $value, $this->config->get('cache.assets.ttl'));
491
        }
492
493
        return $cache->get($cacheKey, $value);
494
    }
495
496
    /**
497
     * Compiles a SCSS string.
498
     *
499
     * @throws RuntimeException
500
     */
501
    public function scssToCss(?string $value): string
502
    {
503
        $value = $value ?? '';
504
505
        $cache = new Cache($this->builder, 'assets');
506
        $cacheKey = $cache->createKeyFromValue(null, $value);
507
        if (!$cache->has($cacheKey)) {
508
            $scssPhp = new Compiler();
509
            $outputStyles = ['expanded', 'compressed'];
510
            $outputStyle = strtolower((string) $this->config->get('assets.compile.style'));
511
            if (!\in_array($outputStyle, $outputStyles)) {
512
                throw new ConfigException(\sprintf('"%s" value must be "%s".', 'assets.compile.style', implode('" or "', $outputStyles)));
513
            }
514
            $scssPhp->setOutputStyle($outputStyle == 'compressed' ? OutputStyle::COMPRESSED : OutputStyle::EXPANDED);
515
            $variables = $this->config->get('assets.compile.variables');
516
            if (!empty($variables)) {
517
                $variables = array_map('ScssPhp\ScssPhp\ValueConverter::parseValue', $variables);
518
                $scssPhp->replaceVariables($variables);
519
            }
520
            $value = $scssPhp->compileString($value)->getCss();
521
            $cache->set($cacheKey, $value, $this->config->get('cache.assets.ttl'));
522
        }
523
524
        return $cache->get($cacheKey, $value);
525
    }
526
527
    /**
528
     * Creates the HTML element of an asset.
529
     *
530
     * @param array                                                                $context    Twig context
531
     * @param Asset|array<int,array{asset:Asset,attributes:?array<string,string>}> $assets     Asset or array of assets + attributes
532
     * @param array                                                                $attributes HTML attributes to add to the element
533
     * @param array                                                                $options    Options:
534
     * [
535
     *     'preload'    => false,
536
     *     'responsive' => false,
537
     *     'formats'    => [],
538
     * ];
539
     *
540
     * @return string HTML element
541
     *
542
     * @throws RuntimeException
543
     */
544
    public function html(array $context, Asset|array $assets, array $attributes = [], array $options = []): string
545
    {
546
        $html = array();
547
        if (!\is_array($assets)) {
0 ignored issues
show
introduced by
The condition is_array($assets) is always true.
Loading history...
548
            $assets = [['asset' => $assets, 'attributes' => null]];
549
        }
550
        foreach ($assets as $assetData) {
551
            $asset = $assetData['asset'];
552
            if (!$asset instanceof Asset) {
553
                $asset = new Asset($this->builder, $asset);
554
            }
555
            $asset->save(); // be sure Asset file is saved
556
            // merge attributes
557
            $attr = $attributes;
558
            if ($assetData['attributes'] !== null) {
559
                $attr = $attributes + $assetData['attributes'];
560
            }
561
            // process by extension
562
            $attributes['as'] = $asset['type'];
563
            switch ($asset['ext']) {
564
                case 'css':
565
                    $html[] = $this->htmlCss($context, $asset, $attr, $options);
566
                    $attributes['as'] = 'style';
567
                    unset($attributes['defer']);
568
                    break;
569
                case 'js':
570
                    $html[] = $this->htmlJs($context, $asset, $attr, $options);
571
                    $attributes['as'] = $asset['script'];
572
                    break;
573
            }
574
            // preload
575
            if ($options['preload'] ?? false) {
576
                $attributes['type'] = $asset['subtype'];
577
                if (empty($attributes['crossorigin'])) {
578
                    $attributes['crossorigin'] = 'anonymous';
579
                }
580
                $preloadLink = \sprintf('<link rel="preload" href="%s"%s>', $this->url($context, $asset, $options), self::htmlAttributes($attributes));
581
                // if image asset with a specified width, preload the right size
582
                if (null !== $width = isset($attributes['width']) && $attributes['width'] > 0 ? (int) $attributes['width'] : null) {
583
                    $preloadLink = \sprintf('<link rel="preload" href="%s"%s>', $this->url($context, $asset->resize($width), $options), self::htmlAttributes($attributes));
584
                }
585
                array_unshift($html, $preloadLink);
586
                // only CSS and JS can be preloaded this way
587
                if (!\in_array($asset['ext'], ['css', 'js'])) {
588
                    break;
589
                }
590
            }
591
            // process by MIME type
592
            switch ($asset['type']) {
593
                case 'image':
594
                    $html[] = $this->htmlImage($context, $asset, $attr, $options);
595
                    break;
596
                case 'audio':
597
                    $html[] = $this->htmlAudio($context, $asset, $attr, $options);
598
                    break;
599
                case 'video':
600
                    $html[] = $this->htmlVideo($context, $asset, $attr, $options);
601
                    break;
602
            }
603
            unset($attr);
604
        }
605
        if (empty($html)) {
606
            throw new RuntimeException(\sprintf('%s failed to generate HTML element(s) for file(s) provided.', '"html" function'));
607
        }
608
609
        return implode("\n    ", $html);
610
    }
611
612
    /**
613
     * Builds the HTML link element of a CSS Asset.
614
     */
615
    public function htmlCss(array $context, Asset $asset, array $attributes = [], array $options = []): string
616
    {
617
        // simulate "defer" by using "preload" and "onload"
618
        if (isset($attributes['defer'])) {
619
            unset($attributes['defer']);
620
            return \sprintf(
621
                '<link rel="preload" href="%s" as="style" onload="this.onload=null;this.rel=\'stylesheet\'"%s><noscript><link rel="stylesheet" href="%1$s"%2$s></noscript>',
622
                $this->url($context, $asset, $options),
623
                self::htmlAttributes($attributes)
624
            );
625
        }
626
627
        return \sprintf('<link rel="stylesheet" href="%s"%s>', $this->url($context, $asset, $options), self::htmlAttributes($attributes));
628
    }
629
630
    /**
631
     * Builds the HTML script element of a JS Asset.
632
     */
633
    public function htmlJs(array $context, Asset $asset, array $attributes = [], array $options = []): string
634
    {
635
        return \sprintf('<script src="%s"%s></script>', $this->url($context, $asset, $options), self::htmlAttributes($attributes));
636
    }
637
638
    /**
639
     * Builds the HTML img element of an image Asset.
640
     */
641
    public function htmlImage(array $context, Asset $asset, array $attributes = [], array $options = []): string
642
    {
643
        $responsive = $options['responsive'] ?? $this->config->get('layouts.images.responsive');
644
645
        // build responsive attributes
646
        try {
647
            if ($responsive === true || $responsive == 'width') {
648
                $srcset = Image::buildHtmlSrcsetW($asset, $this->config->getAssetsImagesWidths());
649
                if (!empty($srcset)) {
650
                    $attributes['srcset'] = $srcset;
651
                }
652
                $attributes['sizes'] = Image::getHtmlSizes($attributes['class'] ?? '', $this->config->getAssetsImagesSizes());
653
                // prevent oversized images
654
                if ($asset['width'] > max($this->config->getAssetsImagesWidths())) {
655
                    $asset = $asset->resize(max($this->config->getAssetsImagesWidths()));
656
                }
657
            } elseif ($responsive == 'density') {
658
                $width1x = isset($attributes['width']) && $attributes['width'] > 0 ? (int) $attributes['width'] : $asset['width'];
659
                $srcset = Image::buildHtmlSrcsetX($asset, $width1x, $this->config->getAssetsImagesDensities());
660
                if (!empty($srcset)) {
661
                    $attributes['srcset'] = $srcset;
662
                }
663
            }
664
        } catch (\Exception $e) {
665
            $this->builder->getLogger()->warning($e->getMessage());
666
        }
667
668
        // create alternative formats (`<source>`)
669
        try {
670
            $formats = $options['formats'] ?? (array) $this->config->get('layouts.images.formats');
671
            if (\count($formats) > 0) {
672
                $source = '';
673
                foreach ($formats as $format) {
674
                    try {
675
                        $assetConverted = $asset->convert($format);
676
                        // responsive
677
                        if ($responsive === true || $responsive == 'width') {
678
                            $srcset = Image::buildHtmlSrcsetW($assetConverted, $this->config->getAssetsImagesWidths());
679
                            if (empty($srcset)) {
680
                                $source .= \sprintf("\n  <source type=\"image/$format\" srcset=\"%s\">", (string) $assetConverted);
681
                                continue;
682
                            }
683
                            $source .= \sprintf("\n  <source type=\"image/$format\" srcset=\"%s\" sizes=\"%s\">", $srcset, Image::getHtmlSizes($attributes['class'] ?? '', $this->config->getAssetsImagesSizes()));
684
                            continue;
685
                        }
686
                        if ($responsive == 'density') {
687
                            $width1x = isset($attributes['width']) && $attributes['width'] > 0 ? (int) $attributes['width'] : $asset['width'];
688
                            $srcset = Image::buildHtmlSrcsetX($assetConverted, $width1x, $this->config->getAssetsImagesDensities());
689
                            if (empty($srcset)) {
690
                                $srcset = (string) $assetConverted;
691
                            }
692
                            $source .= \sprintf("\n  <source type=\"image/$format\" srcset=\"%s\">", $srcset);
693
                            continue;
694
                        }
695
                        $source .= \sprintf("\n  <source type=\"image/$format\" srcset=\"%s\">", $assetConverted);
696
                    } catch (\Exception $e) {
697
                        $this->builder->getLogger()->warning($e->getMessage());
698
                        continue;
699
                    }
700
                }
701
            }
702
        } catch (\Exception $e) {
703
            $this->builder->getLogger()->warning($e->getMessage());
704
        }
705
706
        // create `<img>` element
707
        if (!isset($attributes['alt'])) {
708
            $attributes['alt'] = '';
709
        }
710
        if (isset($attributes['width']) && $attributes['width'] > 0) {
711
            $asset = $asset->resize((int) $attributes['width']);
712
        }
713
        if (!isset($attributes['width'])) {
714
            $attributes['width'] = $asset['width'] ?: '';
715
        }
716
        if (!isset($attributes['height'])) {
717
            $attributes['height'] = $asset['height'] ?: '';
718
        }
719
        $img = \sprintf('<img src="%s"%s>', $this->url($context, $asset, $options), self::htmlAttributes($attributes));
720
721
        // put `<source>` elements in `<picture>` if exists
722
        if (!empty($source)) {
723
            return \sprintf("<picture>%s\n  %s\n</picture>", $source, $img);
724
        }
725
726
        return $img;
727
    }
728
729
    /**
730
     * Builds the HTML audio element of an audio Asset.
731
     */
732
    public function htmlAudio(array $context, Asset $asset, array $attributes = [], array $options = []): string
733
    {
734
        if (empty($attributes)) {
735
            $attributes['controls'] = '';
736
        }
737
738
        return \sprintf('<audio%s src="%s" type="%s"></audio>', self::htmlAttributes($attributes), $this->url($context, $asset, $options), $asset['subtype']);
739
    }
740
741
    /**
742
     * Builds the HTML video element of a video Asset.
743
     */
744
    public function htmlVideo(array $context, Asset $asset, array $attributes = [], array $options = []): string
745
    {
746
        if (empty($attributes)) {
747
            $attributes['controls'] = '';
748
        }
749
750
        return \sprintf('<video%s><source src="%s" type="%s"></video>', self::htmlAttributes($attributes), $this->url($context, $asset, $options), $asset['subtype']);
751
    }
752
753
    /**
754
     * Builds the HTML img `srcset` (responsive) attribute of an image Asset, based on configured widths.
755
     *
756
     * @throws RuntimeException
757
     */
758
    public function imageSrcset(Asset $asset): string
759
    {
760
        return Image::buildHtmlSrcsetW($asset, $this->config->getAssetsImagesWidths(), true);
761
    }
762
763
    /**
764
     * Returns the HTML img `sizes` attribute based on a CSS class name.
765
     */
766
    public function imageSizes(string $class): string
767
    {
768
        return Image::getHtmlSizes($class, $this->config->getAssetsImagesSizes());
769
    }
770
771
    /**
772
     * Builds the HTML img element from a website URL by extracting the image from meta tags.
773
     * Returns null if no image found.
774
     *
775
     * @todo enhance performance by caching results?
776
     *
777
     * @throws RuntimeException
778
     */
779
    public function htmlImageFromWebsite(array $context, string $url, array $attributes = [], array $options = []): ?string
780
    {
781
        if (false !== $html = Util\File::fileGetContents($url)) {
782
            $imageUrl = Util\Html::getImageFromMetaTags($html);
783
            if ($imageUrl !== null) {
784
                $asset = new Asset($this->builder, $imageUrl);
785
786
                return $this->htmlImage($context, $asset, $attributes, $options);
787
            }
788
        }
789
790
        return null;
791
    }
792
793
    /**
794
     * Converts an image Asset to WebP format.
795
     */
796
    public function webp(Asset $asset, ?int $quality = null): Asset
797
    {
798
        return $this->convert($asset, 'webp', $quality);
799
    }
800
801
    /**
802
     * Converts an image Asset to AVIF format.
803
     */
804
    public function avif(Asset $asset, ?int $quality = null): Asset
805
    {
806
        return $this->convert($asset, 'avif', $quality);
807
    }
808
809
    /**
810
     * Converts an image Asset to the given format.
811
     *
812
     * @throws RuntimeException
813
     */
814
    private function convert(Asset $asset, string $format, ?int $quality = null): Asset
815
    {
816
        if ($asset['subtype'] == "image/$format") {
817
            return $asset;
818
        }
819
        if (Image::isAnimatedGif($asset)) {
820
            throw new RuntimeException(\sprintf('Unable to convert the animated GIF "%s" to %s.', $asset['path'], $format));
821
        }
822
823
        try {
824
            return $asset->$format($quality);
825
        } catch (\Exception $e) {
826
            throw new RuntimeException(\sprintf('Unable to convert "%s" to %s (%s).', $asset['path'], $format, $e->getMessage()));
827
        }
828
    }
829
830
    /**
831
     * Returns the content of an asset.
832
     */
833
    public function inline(Asset $asset): string
834
    {
835
        return $asset['content'];
836
    }
837
838
    /**
839
     * Reads $length first characters of a string and adds a suffix.
840
     */
841
    public function excerpt(?string $string, int $length = 450, string $suffix = ' …'): string
842
    {
843
        $string = $string ?? '';
844
845
        $string = str_replace('</p>', '<br><br>', $string);
846
        $string = trim(strip_tags($string, '<br>'));
847
        if (mb_strlen($string) > $length) {
848
            $string = mb_substr($string, 0, $length);
849
            $string .= $suffix;
850
        }
851
852
        return $string;
853
    }
854
855
    /**
856
     * Reads characters before or after '<!-- separator -->'.
857
     * Options:
858
     *  - separator: string to use as separator (`excerpt|break` by default)
859
     *  - capture: part to capture, `before` or `after` the separator (`before` by default).
860
     */
861
    public function excerptHtml(?string $string, array $options = []): string
862
    {
863
        $string = $string ?? '';
864
865
        $separator = (string) $this->config->get('pages.body.excerpt.separator');
866
        $capture = (string) $this->config->get('pages.body.excerpt.capture');
867
        extract($options, EXTR_IF_EXISTS);
868
869
        // https://regex101.com/r/n9TWHF/1
870
        $pattern = '(.*)<!--[[:blank:]]?(' . $separator . ')[[:blank:]]?-->(.*)';
871
        preg_match('/' . $pattern . '/is', $string, $matches);
872
873
        if (empty($matches)) {
874
            return $string;
875
        }
876
        $result = trim($matches[1]);
877
        if ($capture == 'after') {
878
            $result = trim($matches[3]);
879
        }
880
        // removes footnotes and returns result
881
        return preg_replace('/<sup[^>]*>[^u]*<\/sup>/', '', $result);
882
    }
883
884
    /**
885
     * Converts a Markdown string to HTML.
886
     *
887
     * @throws RuntimeException
888
     */
889
    public function markdownToHtml(?string $markdown): ?string
890
    {
891
        $markdown = $markdown ?? '';
892
893
        try {
894
            $parsedown = new Parsedown($this->builder);
895
            $html = $parsedown->text($markdown);
896
        } catch (\Exception $e) {
897
            throw new RuntimeException(
898
                '"markdown_to_html" filter can not convert supplied Markdown.',
899
                previous: $e
900
            );
901
        }
902
903
        return $html;
904
    }
905
906
    /**
907
     * Extracts only headings matching the given `selectors` (h2, h3, etc.),
908
     * or those defined in config `pages.body.toc` if not specified.
909
     * The `format` parameter defines the output format: `html` or `json`.
910
     * The `url` parameter is used to build links to headings.
911
     *
912
     * @throws RuntimeException
913
     */
914
    public function markdownToToc(?string $markdown, $format = 'html', ?array $selectors = null, string $url = ''): ?string
915
    {
916
        $markdown = $markdown ?? '';
917
        $selectors = $selectors ?? (array) $this->config->get('pages.body.toc');
918
919
        try {
920
            $parsedown = new Parsedown($this->builder, ['selectors' => $selectors, 'url' => $url]);
921
            $parsedown->body($markdown);
922
            $return = $parsedown->contentsList($format);
923
        } catch (\Exception) {
924
            throw new RuntimeException('"toc" filter can not convert supplied Markdown.');
925
        }
926
927
        return $return;
928
    }
929
930
    /**
931
     * Converts a JSON string to an array.
932
     *
933
     * @throws RuntimeException
934
     */
935
    public function jsonDecode(?string $json): ?array
936
    {
937
        $json = $json ?? '';
938
939
        try {
940
            $array = json_decode($json, true);
941
            if ($array === null && json_last_error() !== JSON_ERROR_NONE) {
942
                throw new \Exception('JSON error.');
943
            }
944
        } catch (\Exception) {
945
            throw new RuntimeException('"json_decode" filter can not parse supplied JSON.');
946
        }
947
948
        return $array;
949
    }
950
951
    /**
952
     * Converts a YAML string to an array.
953
     *
954
     * @throws RuntimeException
955
     */
956
    public function yamlParse(?string $yaml): ?array
957
    {
958
        $yaml = $yaml ?? '';
959
960
        try {
961
            $array = Yaml::parse($yaml, Yaml::PARSE_DATETIME);
962
            if (!\is_array($array)) {
963
                throw new ParseException('YAML error.');
964
            }
965
        } catch (ParseException $e) {
966
            throw new RuntimeException(\sprintf('"yaml_parse" filter can not parse supplied YAML: %s', $e->getMessage()));
967
        }
968
969
        return $array;
970
    }
971
972
    /**
973
     * Split a string into an array using a regular expression.
974
     *
975
     * @throws RuntimeException
976
     */
977
    public function pregSplit(?string $value, string $pattern, int $limit = 0): ?array
978
    {
979
        $value = $value ?? '';
980
981
        try {
982
            $array = preg_split($pattern, $value, $limit);
983
            if ($array === false) {
984
                throw new RuntimeException('PREG split error.');
985
            }
986
        } catch (\Exception) {
987
            throw new RuntimeException('"preg_split" filter can not split supplied string.');
988
        }
989
990
        return $array;
991
    }
992
993
    /**
994
     * Perform a regular expression match and return the group for all matches.
995
     *
996
     * @throws RuntimeException
997
     */
998
    public function pregMatchAll(?string $value, string $pattern, int $group = 0): ?array
999
    {
1000
        $value = $value ?? '';
1001
1002
        try {
1003
            $array = preg_match_all($pattern, $value, $matches, PREG_PATTERN_ORDER);
1004
            if ($array === false) {
1005
                throw new RuntimeException('PREG match all error.');
1006
            }
1007
        } catch (\Exception) {
1008
            throw new RuntimeException('"preg_match_all" filter can not match in supplied string.');
1009
        }
1010
1011
        return $matches[$group];
1012
    }
1013
1014
    /**
1015
     * Calculates estimated time to read a text.
1016
     */
1017
    public function readtime(?string $text): string
1018
    {
1019
        $text = $text ?? '';
1020
1021
        $words = str_word_count(strip_tags($text));
1022
        $min = floor($words / 200);
1023
        if ($min === 0) {
1024
            return '1';
1025
        }
1026
1027
        return (string) $min;
1028
    }
1029
1030
    /**
1031
     * Gets the value of an environment variable.
1032
     */
1033
    public function getEnv(?string $var): ?string
1034
    {
1035
        $var = $var ?? '';
1036
1037
        return getenv($var) ?: null;
1038
    }
1039
1040
    /**
1041
     * Dump variable (or Twig context).
1042
     */
1043
    public function varDump(\Twig\Environment $env, array $context, $var = null, ?array $options = null): void
1044
    {
1045
        if (!$env->isDebug()) {
1046
            return;
1047
        }
1048
1049
        if ($var === null) {
1050
            $var = array();
1051
            foreach ($context as $key => $value) {
1052
                if (!$value instanceof \Twig\Template && !$value instanceof \Twig\TemplateWrapper) {
1053
                    $var[$key] = $value;
1054
                }
1055
            }
1056
        }
1057
1058
        $cloner = new VarCloner();
1059
        $cloner->setMinDepth(3);
1060
        $dumper = new HtmlDumper();
1061
        $dumper->setTheme($options['theme'] ?? 'light');
1062
1063
        $data = $cloner->cloneVar($var)->withMaxDepth(3);
1064
        $dumper->dump($data, null, ['maxDepth' => 3]);
1065
    }
1066
1067
    /**
1068
     * Tests if a variable is an Asset.
1069
     */
1070
    public function isAsset($variable): bool
1071
    {
1072
        return $variable instanceof Asset;
1073
    }
1074
1075
    /**
1076
     * Tests if an image Asset is large enough to be used as a cover image.
1077
     * A large image is defined as having a width >= 600px and height >= 315px.
1078
     */
1079
    public function isImageLarge(Asset $asset): bool
1080
    {
1081
        return $asset['type'] == 'image' && $asset['width'] > $asset['height'] && $asset['width'] >= 600 && $asset['height'] >= 315;
1082
    }
1083
1084
    /**
1085
     * Tests if an image Asset is square.
1086
     * A square image is defined as having the same width and height.
1087
     */
1088
    public function isImageSquare(Asset $asset): bool
1089
    {
1090
        return $asset['type'] == 'image' && $asset['width'] == $asset['height'];
1091
    }
1092
1093
    /**
1094
     * Returns the dominant hex color of an image asset.
1095
     *
1096
     * @param string|Asset $asset
1097
     *
1098
     * @return string
1099
     */
1100
    public function dominantColor($asset): string
1101
    {
1102
        if (!$asset instanceof Asset) {
1103
            $asset = new Asset($this->builder, $asset);
1104
        }
1105
1106
        return Image::getDominantColor($asset);
1107
    }
1108
1109
    /**
1110
     * Returns a Low Quality Image Placeholder (LQIP) as data URL.
1111
     *
1112
     * @param string|Asset $asset
1113
     *
1114
     * @return string
1115
     */
1116
    public function lqip($asset): string
1117
    {
1118
        if (!$asset instanceof Asset) {
1119
            $asset = new Asset($this->builder, $asset);
1120
        }
1121
1122
        return Image::getLqip($asset);
1123
    }
1124
1125
    /**
1126
     * Converts an hexadecimal color to RGB.
1127
     *
1128
     * @throws RuntimeException
1129
     */
1130
    public function hexToRgb(?string $variable): array
1131
    {
1132
        $variable = $variable ?? '';
1133
1134
        if (!self::isHex($variable)) {
1135
            throw new RuntimeException(\sprintf('"%s" is not a valid hexadecimal value.', $variable));
1136
        }
1137
        $hex = ltrim($variable, '#');
1138
        if (\strlen($hex) == 3) {
1139
            $hex = $hex[0] . $hex[0] . $hex[1] . $hex[1] . $hex[2] . $hex[2];
1140
        }
1141
        $c = hexdec($hex);
1142
1143
        return [
1144
            'red'   => $c >> 16 & 0xFF,
1145
            'green' => $c >> 8 & 0xFF,
1146
            'blue'  => $c & 0xFF,
1147
        ];
1148
    }
1149
1150
    /**
1151
     * Split a string in multiple lines.
1152
     */
1153
    public function splitLine(?string $variable, int $max = 18): array
1154
    {
1155
        $variable = $variable ?? '';
1156
1157
        return preg_split("/.{0,{$max}}\K(\s+|$)/", $variable, 0, PREG_SPLIT_NO_EMPTY);
1158
    }
1159
1160
    /**
1161
     * Hashing an object, an array or a string (with algo, md5 by default).
1162
     */
1163
    public function hash(object|array|string $data, $algo = 'md5'): string
1164
    {
1165
        switch (\gettype($data)) {
1166
            case 'object':
1167
                return spl_object_hash($data);
1168
            case 'array':
1169
                return hash($algo, serialize($data));
1170
        }
1171
1172
        return hash($algo, $data);
1173
    }
1174
1175
    /**
1176
     * Converts a variable to an iterable (array).
1177
     */
1178
    public function iterable($value): array
1179
    {
1180
        if (\is_array($value)) {
1181
            return $value;
1182
        }
1183
        if (\is_string($value)) {
1184
            return [$value];
1185
        }
1186
        if ($value instanceof \Traversable) {
1187
            return iterator_to_array($value);
1188
        }
1189
        if ($value instanceof \stdClass) {
1190
            return (array) $value;
1191
        }
1192
        if (\is_object($value)) {
1193
            return [$value];
1194
        }
1195
        if (\is_int($value) || \is_float($value)) {
1196
            return [$value];
1197
        }
1198
        return [$value];
1199
    }
1200
1201
    /**
1202
     * Highlights a code snippet.
1203
     */
1204
    public function highlight(string $code, string $language): string
1205
    {
1206
        return (new Highlighter())->highlight($language, $code)->value;
1207
    }
1208
1209
    /**
1210
     * Returns an array with unique values.
1211
     */
1212
    public function unique(array $array): array
1213
    {
1214
        return array_intersect_key($array, array_unique(array_map('strtolower', $array), SORT_STRING));
1215
    }
1216
1217
    /**
1218
     * Is a hexadecimal color is valid?
1219
     */
1220
    private static function isHex(string $hex): bool
1221
    {
1222
        $valid = \is_string($hex);
1223
        $hex = ltrim($hex, '#');
1224
        $length = \strlen($hex);
1225
        $valid = $valid && ($length === 3 || $length === 6);
1226
        $valid = $valid && ctype_xdigit($hex);
1227
1228
        return $valid;
1229
    }
1230
1231
    /**
1232
     * Builds the HTML attributes string from an array.
1233
     */
1234
    private static function htmlAttributes(array $attributes): string
1235
    {
1236
        $htmlAttributes = '';
1237
        foreach ($attributes as $name => $value) {
1238
            $attribute = \sprintf(' %s="%s"', $name, $value);
1239
            if (empty($value)) {
1240
                $attribute = \sprintf(' %s', $name);
1241
            }
1242
            $htmlAttributes .= $attribute;
1243
        }
1244
1245
        return $htmlAttributes;
1246
    }
1247
}
1248