Passed
Push — master ( 3948d0...dbc9e5 )
by
unknown
05:33
created

Core::lqip()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 2.0625

Importance

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

207
        array_multisort(array_keys(/** @scrutinizer ignore-type */ $collection), $sort, /** @scrutinizer ignore-type */ \SORT_NATURAL | \SORT_FLAG_CASE, $collection);
Loading history...
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

207
        array_multisort(/** @scrutinizer ignore-type */ array_keys(/** @scrutinizer ignore-type */ $collection), $sort, \SORT_NATURAL | \SORT_FLAG_CASE, $collection);
Loading history...
208
209 1
        return $collection;
210
    }
211
212
    /**
213
     * Sorts a collection by weight.
214
     *
215
     * @param \Traversable|array $collection
216
     */
217 1
    public function sortByWeight($collection): array
218
    {
219 1
        $callback = function ($a, $b) {
220 1
            if (!isset($a['weight'])) {
221 1
                $a['weight'] = 0;
222
            }
223 1
            if (!isset($b['weight'])) {
224
                $a['weight'] = 0;
225
            }
226 1
            if ($a['weight'] == $b['weight']) {
227 1
                return 0;
228
            }
229
230 1
            return $a['weight'] < $b['weight'] ? -1 : 1;
231 1
        };
232
233 1
        if (!\is_array($collection)) {
234 1
            $collection = iterator_to_array($collection);
235
        }
236 1
        usort(/** @scrutinizer ignore-type */ $collection, $callback);
237
238 1
        return $collection;
239
    }
240
241
    /**
242
     * Sorts by creation date (or 'updated' date): the most recent first.
243
     */
244 1
    public function sortByDate(\Traversable $collection, string $variable = 'date', bool $descTitle = false): array
245
    {
246 1
        $callback = function ($a, $b) use ($variable, $descTitle) {
247 1
            if ($a[$variable] == $b[$variable]) {
248
                // if dates are equal and "descTitle" is true
249 1
                if ($descTitle && (isset($a['title']) && isset($b['title']))) {
250
                    return strnatcmp($b['title'], $a['title']);
251
                }
252
253 1
                return 0;
254
            }
255
256 1
            return $a[$variable] > $b[$variable] ? -1 : 1;
257 1
        };
258
259 1
        $collection = iterator_to_array($collection);
260 1
        usort(/** @scrutinizer ignore-type */ $collection, $callback);
261
262 1
        return $collection;
263
    }
264
265
    /**
266
     * Creates an URL.
267
     *
268
     * $options[
269
     *     'canonical' => false,
270
     *     'format'    => 'html',
271
     *     'language'  => null,
272
     * ];
273
     *
274
     * @param array                  $context
275
     * @param Page|Asset|string|null $value
276
     * @param array|null             $options
277
     */
278 1
    public function url(array $context, $value = null, ?array $options = null): string
279
    {
280 1
        $optionsLang = [];
281 1
        $optionsLang['language'] = (string) $context['site']['language'];
282 1
        $options = array_merge($optionsLang, $options ?? []);
283
284 1
        return (new Url($this->builder, $value, $options))->getUrl();
285
    }
286
287
    /**
288
     * Creates an Asset (CSS, JS, images, etc.) from a path or an array of paths.
289
     *
290
     * @param string|array $path    File path or array of files path (relative from `assets/` or `static/` dir).
291
     * @param array|null   $options
292
     *
293
     * @return Asset
294
     */
295 1
    public function asset($path, array|null $options = null): Asset
296
    {
297 1
        if (!\is_string($path) && !\is_array($path)) {
298
            throw new RuntimeException(\sprintf('Argument of "%s()" must a string or an array.', \Cecil\Util::formatMethodName(__METHOD__)));
299
        }
300
301 1
        return new Asset($this->builder, $path, $options);
302
    }
303
304
    /**
305
     * Compiles a SCSS asset.
306
     *
307
     * @param string|Asset $asset
308
     *
309
     * @return Asset
310
     */
311 1
    public function toCss($asset): Asset
312
    {
313 1
        if (!$asset instanceof Asset) {
314
            $asset = new Asset($this->builder, $asset);
315
        }
316
317 1
        return $asset->compile();
318
    }
319
320
    /**
321
     * Minifying an asset (CSS or JS).
322
     *
323
     * @param string|Asset $asset
324
     *
325
     * @return Asset
326
     */
327 1
    public function minify($asset): Asset
328
    {
329 1
        if (!$asset instanceof Asset) {
330
            $asset = new Asset($this->builder, $asset);
331
        }
332
333 1
        return $asset->minify();
334
    }
335
336
    /**
337
     * Fingerprinting an asset.
338
     *
339
     * @param string|Asset $asset
340
     *
341
     * @return Asset
342
     */
343 1
    public function fingerprint($asset): Asset
344
    {
345 1
        if (!$asset instanceof Asset) {
346
            $asset = new Asset($this->builder, $asset);
347
        }
348
349 1
        return $asset->fingerprint();
350
    }
351
352
    /**
353
     * Resizes an image.
354
     *
355
     * @param string|Asset $asset
356
     *
357
     * @return Asset
358
     */
359 1
    public function resize($asset, int $size): Asset
360
    {
361 1
        if (!$asset instanceof Asset) {
362
            $asset = new Asset($this->builder, $asset);
363
        }
364
365 1
        return $asset->resize($size);
366
    }
367
368
    /**
369
     * Returns the data URL of an image.
370
     *
371
     * @param string|Asset $asset
372
     *
373
     * @return string
374
     */
375 1
    public function dataurl($asset): string
376
    {
377 1
        if (!$asset instanceof Asset) {
378
            $asset = new Asset($this->builder, $asset);
379
        }
380
381 1
        return $asset->dataurl();
382
    }
383
384
    /**
385
     * Hashing an asset with algo (sha384 by default).
386
     *
387
     * @param string|Asset $asset
388
     * @param string       $algo
389
     *
390
     * @return string
391
     */
392 1
    public function integrity($asset, string $algo = 'sha384'): string
393
    {
394 1
        if (!$asset instanceof Asset) {
395 1
            $asset = new Asset($this->builder, $asset);
396
        }
397
398 1
        return $asset->getIntegrity($algo);
399
    }
400
401
    /**
402
     * Minifying a CSS string.
403
     */
404 1
    public function minifyCss(?string $value): string
405
    {
406 1
        $value = $value ?? '';
407
408 1
        if ($this->builder->isDebug()) {
409 1
            return $value;
410
        }
411
412
        $cache = new Cache($this->builder, 'assets');
413
        $cacheKey = $cache->createKey(null, $value);
414
        if (!$cache->has($cacheKey)) {
415
            $minifier = new Minify\CSS($value);
416
            $value = $minifier->minify();
417
            $cache->set($cacheKey, $value, $this->config->get('cache.assets.ttl'));
418
        }
419
420
        return $cache->get($cacheKey, $value);
421
    }
422
423
    /**
424
     * Minifying a JavaScript string.
425
     */
426 1
    public function minifyJs(?string $value): string
427
    {
428 1
        $value = $value ?? '';
429
430 1
        if ($this->builder->isDebug()) {
431 1
            return $value;
432
        }
433
434
        $cache = new Cache($this->builder, 'assets');
435
        $cacheKey = $cache->createKey(null, $value);
436
        if (!$cache->has($cacheKey)) {
437
            $minifier = new Minify\JS($value);
438
            $value = $minifier->minify();
439
            $cache->set($cacheKey, $value, $this->config->get('cache.assets.ttl'));
440
        }
441
442
        return $cache->get($cacheKey, $value);
443
    }
444
445
    /**
446
     * Compiles a SCSS string.
447
     *
448
     * @throws RuntimeException
449
     */
450 1
    public function scssToCss(?string $value): string
451
    {
452 1
        $value = $value ?? '';
453
454 1
        $cache = new Cache($this->builder, 'assets');
455 1
        $cacheKey = $cache->createKey(null, $value);
456 1
        if (!$cache->has($cacheKey)) {
457 1
            $scssPhp = new Compiler();
458 1
            $outputStyles = ['expanded', 'compressed'];
459 1
            $outputStyle = strtolower((string) $this->config->get('assets.compile.style'));
460 1
            if (!\in_array($outputStyle, $outputStyles)) {
461
                throw new ConfigException(\sprintf('"%s" value must be "%s".', 'assets.compile.style', implode('" or "', $outputStyles)));
462
            }
463 1
            $scssPhp->setOutputStyle($outputStyle == 'compressed' ? OutputStyle::COMPRESSED : OutputStyle::EXPANDED);
464 1
            $variables = $this->config->get('assets.compile.variables');
465 1
            if (!empty($variables)) {
466 1
                $variables = array_map('ScssPhp\ScssPhp\ValueConverter::parseValue', $variables);
467 1
                $scssPhp->replaceVariables($variables);
468
            }
469 1
            $value = $scssPhp->compileString($value)->getCss();
470 1
            $cache->set($cacheKey, $value, $this->config->get('cache.assets.ttl'));
471
        }
472
473 1
        return $cache->get($cacheKey, $value);
474
    }
475
476
    /**
477
     * Creates the HTML element of an asset.
478
     *
479
     * $options[
480
     *     'preload'    => false,
481
     *     'responsive' => false,
482
     *     'formats'    => [],
483
     * ];
484
     *
485
     * @throws RuntimeException
486
     */
487 1
    public function html(array $context, Asset $asset, array $attributes = [], array $options = []): string
488
    {
489 1
        $htmlAttributes = '';
490 1
        $preload = false;
491 1
        $responsive = $this->config->isEnabled('layouts.images.responsive');
492 1
        $formats = (array) $this->config->get('layouts.images.formats');
493 1
        extract($options, EXTR_IF_EXISTS);
494
495
        // builds HTML attributes
496 1
        foreach ($attributes as $name => $value) {
497 1
            $attribute = \sprintf(' %s="%s"', $name, $value);
498 1
            if (!isset($value)) {
499
                $attribute = \sprintf(' %s', $name);
500
            }
501 1
            $htmlAttributes .= $attribute;
502
        }
503
504
        // be sure Asset file is saved
505 1
        $asset->save();
506
507
        // CSS or JavaScript
508 1
        switch ($asset['ext']) {
509 1
            case 'css':
510 1
                if ($preload) {
511
                    return \sprintf(
512
                        '<link href="%s" rel="preload" as="style" onload="this.onload=null;this.rel=\'stylesheet\'"%s><noscript><link rel="stylesheet" href="%1$s"%2$s></noscript>',
513
                        $this->url($context, $asset, $options),
514
                        $htmlAttributes
515
                    );
516
                }
517
518 1
                return \sprintf('<link rel="stylesheet" href="%s"%s>', $this->url($context, $asset, $options), $htmlAttributes);
519 1
            case 'js':
520 1
                return \sprintf('<script src="%s"%s></script>', $this->url($context, $asset, $options), $htmlAttributes);
521
        }
522
        // image
523 1
        if ($asset['type'] == 'image') {
524
            // responsive
525 1
            $sizes = '';
526
            if (
527 1
                $responsive && $srcset = Image::buildSrcset(
528 1
                    $asset,
529 1
                    $this->config->getAssetsImagesWidths()
530 1
                )
531
            ) {
532 1
                $htmlAttributes .= \sprintf(' srcset="%s"', $srcset);
533 1
                $sizes = Image::getSizes($attributes['class'] ?? '', $this->config->getAssetsImagesSizes());
534 1
                $htmlAttributes .= \sprintf(' sizes="%s"', $sizes);
535 1
                if ($asset['width'] > max($this->config->getAssetsImagesWidths())) {
536
                    $asset = $asset->resize(max($this->config->getAssetsImagesWidths()));
537
                }
538
            }
539
540
            // <img> element
541 1
            $img = \sprintf(
542 1
                '<img src="%s" width="' . ($asset['width'] ?: '') . '" height="' . ($asset['height'] ?: '') . '"%s>',
543 1
                $this->url($context, $asset, $options),
544 1
                $htmlAttributes
545 1
            );
546
547
            // multiple <source>?
548 1
            if (\count($formats) > 0) {
549 1
                $source = '';
550 1
                foreach ($formats as $format) {
551 1
                    if ($asset['subtype'] != "image/$format" && !Image::isAnimatedGif($asset)) {
552
                        try {
553 1
                            $assetConverted = $asset->convert($format);
554
                            // responsive?
555
                            if ($responsive && $srcset = Image::buildSrcset($assetConverted, $this->config->getAssetsImagesWidths())) {
556
                                // <source> element
557
                                $source .= \sprintf(
558
                                    "\n  <source type=\"image/$format\" srcset=\"%s\" sizes=\"%s\">",
559
                                    $srcset,
560
                                    $sizes
561
                                );
562
                                continue;
563
                            }
564
                            // <source> element
565
                            $source .= \sprintf("\n  <source type=\"image/$format\" srcset=\"%s\">", $assetConverted);
566 1
                        } catch (\Exception $e) {
567 1
                            $this->builder->getLogger()->error($e->getMessage());
568
                        }
569
                    }
570
                }
571
572 1
                return \sprintf("<picture>%s\n  %s\n</picture>", $source, $img);
573
            }
574
575
            return $img;
576
        }
577
578
        throw new RuntimeException(\sprintf('%s is available for CSS, JavaScript and images files only.', '"html" filter'));
579
    }
580
581
    /**
582
     * Builds the HTML img `srcset` (responsive) attribute of an image Asset.
583
     *
584
     * @throws RuntimeException
585
     */
586 1
    public function imageSrcset(Asset $asset): string
587
    {
588 1
        return Image::buildSrcset($asset, $this->config->getAssetsImagesWidths());
589
    }
590
591
    /**
592
     * Returns the HTML img `sizes` attribute based on a CSS class name.
593
     */
594 1
    public function imageSizes(string $class): string
595
    {
596 1
        return Image::getSizes($class, $this->config->getAssetsImagesSizes());
597
    }
598
599
    /**
600
     * Converts an image Asset to WebP format.
601
     */
602
    public function webp(Asset $asset, ?int $quality = null): Asset
603
    {
604
        return $this->convert($asset, 'webp', $quality);
605
    }
606
607
    /**
608
     * Converts an image Asset to AVIF format.
609
     */
610
    public function avif(Asset $asset, ?int $quality = null): Asset
611
    {
612
        return $this->convert($asset, 'avif', $quality);
613
    }
614
615
    /**
616
     * Converts an image Asset to the given format.
617
     *
618
     * @throws RuntimeException
619
     */
620
    private function convert(Asset $asset, string $format, ?int $quality = null): Asset
621
    {
622
        if ($asset['subtype'] == "image/$format") {
623
            return $asset;
624
        }
625
        if (Image::isAnimatedGif($asset)) {
626
            throw new RuntimeException(\sprintf('Can\'t convert the animated GIF "%s" to %s.', $asset['path'], $format));
627
        }
628
629
        try {
630
            return $asset->$format($quality);
631
        } catch (\Exception $e) {
632
            throw new RuntimeException(\sprintf('Can\'t convert "%s" to %s (%s).', $asset['path'], $format, $e->getMessage()));
633
        }
634
    }
635
636
    /**
637
     * Returns the content of an asset.
638
     */
639 1
    public function inline(Asset $asset): string
640
    {
641 1
        return $asset['content'];
642
    }
643
644
    /**
645
     * Reads $length first characters of a string and adds a suffix.
646
     */
647 1
    public function excerpt(?string $string, int $length = 450, string $suffix = ' …'): string
648
    {
649 1
        $string = $string ?? '';
650
651 1
        $string = str_replace('</p>', '<br><br>', $string);
652 1
        $string = trim(strip_tags($string, '<br>'));
653 1
        if (mb_strlen($string) > $length) {
654 1
            $string = mb_substr($string, 0, $length);
655 1
            $string .= $suffix;
656
        }
657
658 1
        return $string;
659
    }
660
661
    /**
662
     * Reads characters before or after '<!-- separator -->'.
663
     * Options:
664
     *  - separator: string to use as separator (`excerpt|break` by default)
665
     *  - capture: part to capture, `before` or `after` the separator (`before` by default).
666
     */
667 1
    public function excerptHtml(?string $string, array $options = []): string
668
    {
669 1
        $string = $string ?? '';
670
671 1
        $separator = (string) $this->config->get('pages.body.excerpt.separator');
672 1
        $capture = (string) $this->config->get('pages.body.excerpt.capture');
673 1
        extract($options, EXTR_IF_EXISTS);
674
675
        // https://regex101.com/r/n9TWHF/1
676 1
        $pattern = '(.*)<!--[[:blank:]]?(' . $separator . ')[[:blank:]]?-->(.*)';
677 1
        preg_match('/' . $pattern . '/is', $string, $matches);
678
679 1
        if (empty($matches)) {
680
            return $string;
681
        }
682 1
        $result = trim($matches[1]);
683 1
        if ($capture == 'after') {
684 1
            $result = trim($matches[3]);
685
        }
686
        // removes footnotes and returns result
687 1
        return preg_replace('/<sup[^>]*>[^u]*<\/sup>/', '', $result);
688
    }
689
690
    /**
691
     * Converts a Markdown string to HTML.
692
     *
693
     * @throws RuntimeException
694
     */
695 1
    public function markdownToHtml(?string $markdown): ?string
696
    {
697 1
        $markdown = $markdown ?? '';
698
699
        try {
700 1
            $parsedown = new Parsedown($this->builder);
701 1
            $html = $parsedown->text($markdown);
702
        } catch (\Exception $e) {
703
            throw new RuntimeException(
704
                '"markdown_to_html" filter can not convert supplied Markdown.',
705
                previous: $e
706
            );
707
        }
708
709 1
        return $html;
710
    }
711
712
    /**
713
     * Extract table of content of a Markdown string,
714
     * in the given format ("html" or "json", "html" by default).
715
     *
716
     * @throws RuntimeException
717
     */
718 1
    public function markdownToToc(?string $markdown, $format = 'html', ?array $selectors = null, string $url = ''): ?string
719
    {
720 1
        $markdown = $markdown ?? '';
721 1
        $selectors = $selectors ?? (array) $this->config->get('pages.body.toc');
722
723
        try {
724 1
            $parsedown = new Parsedown($this->builder, ['selectors' => $selectors, 'url' => $url]);
725 1
            $parsedown->body($markdown);
726 1
            $return = $parsedown->contentsList($format);
727
        } catch (\Exception) {
728
            throw new RuntimeException('"toc" filter can not convert supplied Markdown.');
729
        }
730
731 1
        return $return;
732
    }
733
734
    /**
735
     * Converts a JSON string to an array.
736
     *
737
     * @throws RuntimeException
738
     */
739 1
    public function jsonDecode(?string $json): ?array
740
    {
741 1
        $json = $json ?? '';
742
743
        try {
744 1
            $array = json_decode($json, true);
745 1
            if ($array === null && json_last_error() !== JSON_ERROR_NONE) {
746 1
                throw new \Exception('JSON error.');
747
            }
748
        } catch (\Exception) {
749
            throw new RuntimeException('"json_decode" filter can not parse supplied JSON.');
750
        }
751
752 1
        return $array;
753
    }
754
755
    /**
756
     * Converts a YAML string to an array.
757
     *
758
     * @throws RuntimeException
759
     */
760 1
    public function yamlParse(?string $yaml): ?array
761
    {
762 1
        $yaml = $yaml ?? '';
763
764
        try {
765 1
            $array = Yaml::parse($yaml, Yaml::PARSE_DATETIME);
766 1
            if (!\is_array($array)) {
767 1
                throw new ParseException('YAML error.');
768
            }
769
        } catch (ParseException $e) {
770
            throw new RuntimeException(\sprintf('"yaml_parse" filter can not parse supplied YAML: %s', $e->getMessage()));
771
        }
772
773 1
        return $array;
774
    }
775
776
    /**
777
     * Split a string into an array using a regular expression.
778
     *
779
     * @throws RuntimeException
780
     */
781
    public function pregSplit(?string $value, string $pattern, int $limit = 0): ?array
782
    {
783
        $value = $value ?? '';
784
785
        try {
786
            $array = preg_split($pattern, $value, $limit);
787
            if ($array === false) {
788
                throw new RuntimeException('PREG split error.');
789
            }
790
        } catch (\Exception) {
791
            throw new RuntimeException('"preg_split" filter can not split supplied string.');
792
        }
793
794
        return $array;
795
    }
796
797
    /**
798
     * Perform a regular expression match and return the group for all matches.
799
     *
800
     * @throws RuntimeException
801
     */
802
    public function pregMatchAll(?string $value, string $pattern, int $group = 0): ?array
803
    {
804
        $value = $value ?? '';
805
806
        try {
807
            $array = preg_match_all($pattern, $value, $matches, PREG_PATTERN_ORDER);
808
            if ($array === false) {
809
                throw new RuntimeException('PREG match all error.');
810
            }
811
        } catch (\Exception) {
812
            throw new RuntimeException('"preg_match_all" filter can not match in supplied string.');
813
        }
814
815
        return $matches[$group];
816
    }
817
818
    /**
819
     * Calculates estimated time to read a text.
820
     */
821 1
    public function readtime(?string $text): string
822
    {
823 1
        $text = $text ?? '';
824
825 1
        $words = str_word_count(strip_tags($text));
826 1
        $min = floor($words / 200);
827 1
        if ($min === 0) {
828
            return '1';
829
        }
830
831 1
        return (string) $min;
832
    }
833
834
    /**
835
     * Gets the value of an environment variable.
836
     */
837 1
    public function getEnv(?string $var): ?string
838
    {
839 1
        $var = $var ?? '';
840
841 1
        return getenv($var) ?: null;
842
    }
843
844
    /**
845
     * Dump variable (or Twig context).
846
     */
847 1
    public function varDump(\Twig\Environment $env, array $context, $var = null, ?array $options = null): void
848
    {
849 1
        if (!$env->isDebug()) {
850
            return;
851
        }
852
853 1
        if ($var === null) {
854
            $var = array();
855
            foreach ($context as $key => $value) {
856
                if (!$value instanceof \Twig\Template && !$value instanceof \Twig\TemplateWrapper) {
857
                    $var[$key] = $value;
858
                }
859
            }
860
        }
861
862 1
        $cloner = new VarCloner();
863 1
        $cloner->setMinDepth(3);
864 1
        $dumper = new HtmlDumper();
865 1
        $dumper->setTheme($options['theme'] ?? 'light');
866
867 1
        $data = $cloner->cloneVar($var)->withMaxDepth(3);
868 1
        $dumper->dump($data, null, ['maxDepth' => 3]);
869
    }
870
871
    /**
872
     * Tests if a variable is an Asset.
873
     */
874 1
    public function isAsset($variable): bool
875
    {
876 1
        return $variable instanceof Asset;
877
    }
878
879
    /**
880
     * Returns the dominant hex color of an image asset.
881
     *
882
     * @param string|Asset $asset
883
     *
884
     * @return string
885
     */
886 1
    public function dominantColor($asset): string
887
    {
888 1
        if (!$asset instanceof Asset) {
889
            $asset = new Asset($this->builder, $asset);
890
        }
891
892 1
        return Image::getDominantColor($asset);
893
    }
894
895
    /**
896
     * Returns a Low Quality Image Placeholder (LQIP) as data URL.
897
     *
898
     * @param string|Asset $asset
899
     *
900
     * @return string
901
     */
902 1
    public function lqip($asset): string
903
    {
904 1
        if (!$asset instanceof Asset) {
905
            $asset = new Asset($this->builder, $asset);
906
        }
907
908 1
        return Image::getLqip($asset);
909
    }
910
911
    /**
912
     * Converts an hexadecimal color to RGB.
913
     *
914
     * @throws RuntimeException
915
     */
916 1
    public function hexToRgb(?string $variable): array
917
    {
918 1
        $variable = $variable ?? '';
919
920 1
        if (!self::isHex($variable)) {
921
            throw new RuntimeException(\sprintf('"%s" is not a valid hexadecimal value.', $variable));
922
        }
923 1
        $hex = ltrim($variable, '#');
924 1
        if (\strlen($hex) == 3) {
925
            $hex = $hex[0] . $hex[0] . $hex[1] . $hex[1] . $hex[2] . $hex[2];
926
        }
927 1
        $c = hexdec($hex);
928
929 1
        return [
930 1
            'red'   => $c >> 16 & 0xFF,
931 1
            'green' => $c >> 8 & 0xFF,
932 1
            'blue'  => $c & 0xFF,
933 1
        ];
934
    }
935
936
    /**
937
     * Split a string in multiple lines.
938
     */
939 1
    public function splitLine(?string $variable, int $max = 18): array
940
    {
941 1
        $variable = $variable ?? '';
942
943 1
        return preg_split("/.{0,{$max}}\K(\s+|$)/", $variable, 0, PREG_SPLIT_NO_EMPTY);
944
    }
945
946
    /**
947
     * Hashing an object, an array or a string (with algo, md5 by default).
948
     */
949 1
    public function hash(object|array|string $data, $algo = 'md5'): string
950
    {
951 1
        switch (\gettype($data)) {
952 1
            case 'object':
953 1
                return spl_object_hash($data);
954
            case 'array':
955
                return hash($algo, serialize($data));
956
        }
957
958
        return hash($algo, $data);
959
    }
960
961
    /**
962
     * Converts a variable to an iterable (array).
963
     */
964 1
    public function iterable($value): array
965
    {
966 1
        if (\is_array($value)) {
967 1
            return $value;
968
        }
969
        if (\is_string($value)) {
970
            return [$value];
971
        }
972
        if ($value instanceof \Traversable) {
973
            return iterator_to_array($value);
974
        }
975
        if ($value instanceof \stdClass) {
976
            return (array) $value;
977
        }
978
        if (\is_object($value)) {
979
            return [$value];
980
        }
981
        if (\is_int($value) || \is_float($value)) {
982
            return [$value];
983
        }
984
        return [$value];
985
    }
986
987
    /**
988
     * Is a hexadecimal color is valid?
989
     */
990 1
    private static function isHex(string $hex): bool
991
    {
992 1
        $valid = \is_string($hex);
993 1
        $hex = ltrim($hex, '#');
994 1
        $length = \strlen($hex);
995 1
        $valid = $valid && ($length === 3 || $length === 6);
996 1
        $valid = $valid && ctype_xdigit($hex);
997
998 1
        return $valid;
999
    }
1000
}
1001