Core::splitLine()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

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

224
        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

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