Passed
Push — master ( e1404d...4cf546 )
by Arnaud
05:28
created

Core::integrity()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 3
nc 2
nop 2
dl 0
loc 7
ccs 4
cts 4
cp 1
crap 2
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\Assets\Url;
20
use Cecil\Builder;
21
use Cecil\Collection\CollectionInterface;
22
use Cecil\Collection\Page\Collection as PagesCollection;
23
use Cecil\Collection\Page\Page;
24
use Cecil\Collection\Page\Type;
25
use Cecil\Config;
26
use Cecil\Converter\Parsedown;
27
use Cecil\Exception\RuntimeException;
28
use Cocur\Slugify\Bridge\Twig\SlugifyExtension;
29
use Cocur\Slugify\Slugify;
30
use MatthiasMullie\Minify;
31
use ScssPhp\ScssPhp\Compiler;
32
use Symfony\Component\VarDumper\Cloner\VarCloner;
33
use Symfony\Component\VarDumper\Dumper\HtmlDumper;
34
use Symfony\Component\Yaml\Exception\ParseException;
35
use Symfony\Component\Yaml\Yaml;
36
37
/**
38
 * Class Renderer\Extension\Core.
39
 */
40
class Core extends SlugifyExtension
41
{
42
    /** @var Builder */
43
    protected $builder;
44
45
    /** @var Config */
46
    protected $config;
47
48
    /** @var Slugify */
49
    private static $slugifier;
50
51 1
    public function __construct(Builder $builder)
52
    {
53 1
        if (!self::$slugifier instanceof Slugify) {
54 1
            self::$slugifier = Slugify::create(['regexp' => Page::SLUGIFY_PATTERN]);
55
        }
56
57 1
        parent::__construct(self::$slugifier);
58
59 1
        $this->builder = $builder;
60 1
        $this->config = $builder->getConfig();
61
    }
62
63
    /**
64
     * {@inheritdoc}
65
     */
66
    public function getName(): string
67
    {
68
        return 'CoreExtension';
69
    }
70
71
    /**
72
     * {@inheritdoc}
73
     */
74 1
    public function getFunctions()
75
    {
76 1
        return [
77 1
            new \Twig\TwigFunction('url', [$this, 'url'], ['needs_context' => true]),
78
            // assets
79 1
            new \Twig\TwigFunction('asset', [$this, 'asset']),
80 1
            new \Twig\TwigFunction('integrity', [$this, 'integrity']),
81 1
            new \Twig\TwigFunction('image_srcset', [$this, 'imageSrcset']),
82 1
            new \Twig\TwigFunction('image_sizes', [$this, 'imageSizes']),
83
            // content
84 1
            new \Twig\TwigFunction('readtime', [$this, 'readtime']),
85
            // others
86 1
            new \Twig\TwigFunction('getenv', [$this, 'getEnv']),
87 1
            new \Twig\TwigFunction('d', [$this, 'varDump'], ['needs_context' => true, 'needs_environment' => true]),
88
            // deprecated
89 1
            new \Twig\TwigFunction(
90 1
                'hash',
91 1
                [$this, 'integrity'],
92 1
                ['deprecated' => true, 'alternative' => 'integrity']
93 1
            ),
94 1
            new \Twig\TwigFunction(
95 1
                'minify',
96 1
                [$this, 'minify'],
97 1
                ['deprecated' => true, 'alternative' => 'minify filter']
98 1
            ),
99 1
            new \Twig\TwigFunction(
100 1
                'toCSS',
101 1
                [$this, 'toCss'],
102 1
                ['deprecated' => true, 'alternative' => '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('html', [$this, 'html'], ['needs_context' => true]),
121 1
            new \Twig\TwigFilter('inline', [$this, 'inline']),
122 1
            new \Twig\TwigFilter('fingerprint', [$this, 'fingerprint']),
123 1
            new \Twig\TwigFilter('to_css', [$this, 'toCss']),
124 1
            new \Twig\TwigFilter('minify', [$this, 'minify']),
125 1
            new \Twig\TwigFilter('minify_css', [$this, 'minifyCss']),
126 1
            new \Twig\TwigFilter('minify_js', [$this, 'minifyJs']),
127 1
            new \Twig\TwigFilter('scss_to_css', [$this, 'scssToCss']),
128 1
            new \Twig\TwigFilter('sass_to_css', [$this, 'scssToCss']),
129 1
            new \Twig\TwigFilter('resize', [$this, 'resize']),
130 1
            new \Twig\TwigFilter('dataurl', [$this, 'dataurl']),
131 1
            new \Twig\TwigFilter('dominant_color', [$this, 'dominantColor']),
132 1
            new \Twig\TwigFilter('lqip', [$this, 'lqip']),
133 1
            new \Twig\TwigFilter('webp', [$this, 'webp']),
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
            // deprecated
147 1
            new \Twig\TwigFilter(
148 1
                'filterBySection',
149 1
                [$this, 'filterBySection'],
150 1
                ['deprecated' => true, 'alternative' => 'filter_by']
151 1
            ),
152 1
            new \Twig\TwigFilter(
153 1
                'filterBy',
154 1
                [$this, 'filterBy'],
155 1
                ['deprecated' => true, 'alternative' => 'filter_by']
156 1
            ),
157 1
            new \Twig\TwigFilter(
158 1
                'sortByTitle',
159 1
                [$this, 'sortByTitle'],
160 1
                ['deprecated' => true, 'alternative' => 'sort_by_title']
161 1
            ),
162 1
            new \Twig\TwigFilter(
163 1
                'sortByWeight',
164 1
                [$this, 'sortByWeight'],
165 1
                ['deprecated' => true, 'alternative' => 'sort_by_weight']
166 1
            ),
167 1
            new \Twig\TwigFilter(
168 1
                'sortByDate',
169 1
                [$this, 'sortByDate'],
170 1
                ['deprecated' => true, 'alternative' => 'sort_by_date']
171 1
            ),
172 1
            new \Twig\TwigFilter(
173 1
                'minifyCSS',
174 1
                [$this, 'minifyCss'],
175 1
                ['deprecated' => true, 'alternative' => 'minifyCss']
176 1
            ),
177 1
            new \Twig\TwigFilter(
178 1
                'minifyJS',
179 1
                [$this, 'minifyJs'],
180 1
                ['deprecated' => true, 'alternative' => 'minifyJs']
181 1
            ),
182 1
            new \Twig\TwigFilter(
183 1
                'SCSStoCSS',
184 1
                [$this, 'scssToCss'],
185 1
                ['deprecated' => true, 'alternative' => 'scss_to_css']
186 1
            ),
187 1
            new \Twig\TwigFilter(
188 1
                'excerptHtml',
189 1
                [$this, 'excerptHtml'],
190 1
                ['deprecated' => true, 'alternative' => 'excerpt_html']
191 1
            ),
192 1
            new \Twig\TwigFilter(
193 1
                'urlize',
194 1
                [$this, 'slugifyFilter'],
195 1
                ['deprecated' => true, 'alternative' => 'slugify']
196 1
            ),
197 1
        ];
198
    }
199
200
    /**
201
     * {@inheritdoc}
202
     */
203 1
    public function getTests()
204
    {
205 1
        return [
206 1
            new \Twig\TwigTest('asset', [$this, 'isAsset']),
207 1
        ];
208
    }
209
210
    /**
211
     * Filters by Section.
212
     */
213
    public function filterBySection(PagesCollection $pages, string $section): CollectionInterface
214
    {
215
        return $this->filterBy($pages, 'section', $section);
216
    }
217
218
    /**
219
     * Filters a pages collection by variable's name/value.
220
     */
221 1
    public function filterBy(PagesCollection $pages, string $variable, string $value): CollectionInterface
222
    {
223 1
        $filteredPages = $pages->filter(function (Page $page) use ($variable, $value) {
224
            // is a dedicated getter exists?
225 1
            $method = 'get' . ucfirst($variable);
226 1
            if (method_exists($page, $method) && $page->$method() == $value) {
227
                return $page->getType() == Type::PAGE() && !$page->isVirtual() && true;
228
            }
229
            // or a classic variable
230 1
            if ($page->getVariable($variable) == $value) {
231 1
                return $page->getType() == Type::PAGE() && !$page->isVirtual() && true;
232
            }
233 1
        });
234
235 1
        return $filteredPages;
236
    }
237
238
    /**
239
     * Sorts a collection by title.
240
     */
241 1
    public function sortByTitle(\Traversable $collection): array
242
    {
243 1
        $sort = \SORT_ASC;
244
245 1
        $collection = iterator_to_array($collection);
246 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

246
        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

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