• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

Cecilapp / Cecil / 15615077248

12 Jun 2025 03:42PM UTC coverage: 82.644% (-0.009%) from 82.653%
15615077248

push

github

web-flow
fix: asset cache key with content hash (#2189)

10 of 12 new or added lines in 3 files covered. (83.33%)

11 existing lines in 1 file now uncovered.

3119 of 3774 relevant lines covered (82.64%)

0.83 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

73.67
/src/Renderer/Extension/Core.php
1
<?php
2

3
declare(strict_types=1);
4

5
/*
6
 * This file is part of Cecil.
7
 *
8
 * Copyright (c) Arnaud Ligny <arnaud@ligny.fr>
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
    public function __construct(Builder $builder)
55
    {
56
        if (!self::$slugifier instanceof Slugify) {
1✔
57
            self::$slugifier = Slugify::create(['regexp' => Page::SLUGIFY_PATTERN]);
1✔
58
        }
59

60
        parent::__construct(self::$slugifier);
1✔
61

62
        $this->builder = $builder;
1✔
63
        $this->config = $builder->getConfig();
1✔
64
    }
65

66
    /**
67
     * {@inheritdoc}
68
     */
69
    public function getName(): string
70
    {
71
        return 'CoreExtension';
×
72
    }
73

74
    /**
75
     * {@inheritdoc}
76
     */
77
    public function getFunctions()
78
    {
79
        return [
1✔
80
            new \Twig\TwigFunction('url', [$this, 'url'], ['needs_context' => true]),
1✔
81
            // assets
82
            new \Twig\TwigFunction('asset', [$this, 'asset']),
1✔
83
            new \Twig\TwigFunction('html', [$this, 'html'], ['needs_context' => true]),
1✔
84
            new \Twig\TwigFunction('integrity', [$this, 'integrity']),
1✔
85
            new \Twig\TwigFunction('image_srcset', [$this, 'imageSrcset']),
1✔
86
            new \Twig\TwigFunction('image_sizes', [$this, 'imageSizes']),
1✔
87
            // content
88
            new \Twig\TwigFunction('readtime', [$this, 'readtime']),
1✔
89
            new \Twig\TwigFunction('hash', [$this, 'hash']),
1✔
90
            // others
91
            new \Twig\TwigFunction('getenv', [$this, 'getEnv']),
1✔
92
            new \Twig\TwigFunction('d', [$this, 'varDump'], ['needs_context' => true, 'needs_environment' => true]),
1✔
93
            // deprecated
94
            new \Twig\TwigFunction(
1✔
95
                'minify',
1✔
96
                [$this, 'minify'],
1✔
97
                ['deprecation_info' => new DeprecatedCallableInfo('', '', 'minify filter')]
1✔
98
            ),
1✔
99
            new \Twig\TwigFunction(
1✔
100
                'toCSS',
1✔
101
                [$this, 'toCss'],
1✔
102
                ['deprecation_info' => new DeprecatedCallableInfo('', '', 'to_css filter')]
1✔
103
            ),
1✔
104
        ];
1✔
105
    }
106

107
    /**
108
     * {@inheritdoc}
109
     */
110
    public function getFilters(): array
111
    {
112
        return [
1✔
113
            new \Twig\TwigFilter('url', [$this, 'url'], ['needs_context' => true]),
1✔
114
            // collections
115
            new \Twig\TwigFilter('sort_by_title', [$this, 'sortByTitle']),
1✔
116
            new \Twig\TwigFilter('sort_by_weight', [$this, 'sortByWeight']),
1✔
117
            new \Twig\TwigFilter('sort_by_date', [$this, 'sortByDate']),
1✔
118
            new \Twig\TwigFilter('filter_by', [$this, 'filterBy']),
1✔
119
            // assets
120
            new \Twig\TwigFilter('inline', [$this, 'inline']),
1✔
121
            new \Twig\TwigFilter('fingerprint', [$this, 'fingerprint']),
1✔
122
            new \Twig\TwigFilter('to_css', [$this, 'toCss']),
1✔
123
            new \Twig\TwigFilter('minify', [$this, 'minify']),
1✔
124
            new \Twig\TwigFilter('minify_css', [$this, 'minifyCss']),
1✔
125
            new \Twig\TwigFilter('minify_js', [$this, 'minifyJs']),
1✔
126
            new \Twig\TwigFilter('scss_to_css', [$this, 'scssToCss']),
1✔
127
            new \Twig\TwigFilter('sass_to_css', [$this, 'scssToCss']),
1✔
128
            new \Twig\TwigFilter('resize', [$this, 'resize']),
1✔
129
            new \Twig\TwigFilter('cover', [$this, 'cover']),
1✔
130
            new \Twig\TwigFilter('dataurl', [$this, 'dataurl']),
1✔
131
            new \Twig\TwigFilter('dominant_color', [$this, 'dominantColor']),
1✔
132
            new \Twig\TwigFilter('lqip', [$this, 'lqip']),
1✔
133
            new \Twig\TwigFilter('webp', [$this, 'webp']),
1✔
134
            new \Twig\TwigFilter('avif', [$this, 'avif']),
1✔
135
            // content
136
            new \Twig\TwigFilter('slugify', [$this, 'slugifyFilter']),
1✔
137
            new \Twig\TwigFilter('excerpt', [$this, 'excerpt']),
1✔
138
            new \Twig\TwigFilter('excerpt_html', [$this, 'excerptHtml']),
1✔
139
            new \Twig\TwigFilter('markdown_to_html', [$this, 'markdownToHtml']),
1✔
140
            new \Twig\TwigFilter('toc', [$this, 'markdownToToc']),
1✔
141
            new \Twig\TwigFilter('json_decode', [$this, 'jsonDecode']),
1✔
142
            new \Twig\TwigFilter('yaml_parse', [$this, 'yamlParse']),
1✔
143
            new \Twig\TwigFilter('preg_split', [$this, 'pregSplit']),
1✔
144
            new \Twig\TwigFilter('preg_match_all', [$this, 'pregMatchAll']),
1✔
145
            new \Twig\TwigFilter('hex_to_rgb', [$this, 'hexToRgb']),
1✔
146
            new \Twig\TwigFilter('splitline', [$this, 'splitLine']),
1✔
147
            new \Twig\TwigFilter('iterable', [$this, 'iterable']),
1✔
148
            // date
149
            new \Twig\TwigFilter('duration_to_iso8601', ['\Cecil\Util\Date', 'durationToIso8601']),
1✔
150
            // deprecated
151
            new \Twig\TwigFilter(
1✔
152
                'html',
1✔
153
                [$this, 'html'],
1✔
154
                [
1✔
155
                    'needs_context' => true,
1✔
156
                    'deprecation_info' => new DeprecatedCallableInfo('', '', 'html function')
1✔
157
                ]
1✔
158
            ),
1✔
159
        ];
1✔
160
    }
161

162
    /**
163
     * {@inheritdoc}
164
     */
165
    public function getTests()
166
    {
167
        return [
1✔
168
            new \Twig\TwigTest('asset', [$this, 'isAsset']),
1✔
169
        ];
1✔
170
    }
171

172
    /**
173
     * Filters by Section.
174
     */
175
    public function filterBySection(PagesCollection $pages, string $section): CollectionInterface
176
    {
177
        return $this->filterBy($pages, 'section', $section);
×
178
    }
179

180
    /**
181
     * Filters a pages collection by variable's name/value.
182
     */
183
    public function filterBy(PagesCollection $pages, string $variable, string $value): CollectionInterface
184
    {
185
        $filteredPages = $pages->filter(function (Page $page) use ($variable, $value) {
1✔
186
            // is a dedicated getter exists?
187
            $method = 'get' . ucfirst($variable);
1✔
188
            if (method_exists($page, $method) && $page->$method() == $value) {
1✔
189
                return $page->getType() == Type::PAGE->value && !$page->isVirtual() && true;
×
190
            }
191
            // or a classic variable
192
            if ($page->getVariable($variable) == $value) {
1✔
193
                return $page->getType() == Type::PAGE->value && !$page->isVirtual() && true;
1✔
194
            }
195
        });
1✔
196

197
        return $filteredPages;
1✔
198
    }
199

200
    /**
201
     * Sorts a collection by title.
202
     */
203
    public function sortByTitle(\Traversable $collection): array
204
    {
205
        $sort = \SORT_ASC;
1✔
206

207
        $collection = iterator_to_array($collection);
1✔
208
        array_multisort(array_keys(/** @scrutinizer ignore-type */ $collection), $sort, \SORT_NATURAL | \SORT_FLAG_CASE, $collection);
1✔
209

210
        return $collection;
1✔
211
    }
212

213
    /**
214
     * Sorts a collection by weight.
215
     *
216
     * @param \Traversable|array $collection
217
     */
218
    public function sortByWeight($collection): array
219
    {
220
        $callback = function ($a, $b) {
1✔
221
            if (!isset($a['weight'])) {
1✔
222
                $a['weight'] = 0;
1✔
223
            }
224
            if (!isset($b['weight'])) {
1✔
225
                $a['weight'] = 0;
×
226
            }
227
            if ($a['weight'] == $b['weight']) {
1✔
228
                return 0;
1✔
229
            }
230

231
            return $a['weight'] < $b['weight'] ? -1 : 1;
1✔
232
        };
1✔
233

234
        if (!\is_array($collection)) {
1✔
235
            $collection = iterator_to_array($collection);
1✔
236
        }
237
        usort(/** @scrutinizer ignore-type */ $collection, $callback);
1✔
238

239
        return $collection;
1✔
240
    }
241

242
    /**
243
     * Sorts by creation date (or 'updated' date): the most recent first.
244
     */
245
    public function sortByDate(\Traversable $collection, string $variable = 'date', bool $descTitle = false): array
246
    {
247
        $callback = function ($a, $b) use ($variable, $descTitle) {
1✔
248
            if ($a[$variable] == $b[$variable]) {
1✔
249
                // if dates are equal and "descTitle" is true
250
                if ($descTitle && (isset($a['title']) && isset($b['title']))) {
1✔
251
                    return strnatcmp($b['title'], $a['title']);
×
252
                }
253

254
                return 0;
1✔
255
            }
256

257
            return $a[$variable] > $b[$variable] ? -1 : 1;
1✔
258
        };
1✔
259

260
        $collection = iterator_to_array($collection);
1✔
261
        usort(/** @scrutinizer ignore-type */ $collection, $callback);
1✔
262

263
        return $collection;
1✔
264
    }
265

266
    /**
267
     * Creates an URL.
268
     *
269
     * $options[
270
     *     'canonical' => false,
271
     *     'format'    => 'html',
272
     *     'language'  => null,
273
     * ];
274
     *
275
     * @param array                  $context
276
     * @param Page|Asset|string|null $value
277
     * @param array|null             $options
278
     */
279
    public function url(array $context, $value = null, ?array $options = null): string
280
    {
281
        $optionsLang = [];
1✔
282
        $optionsLang['language'] = (string) $context['site']['language'];
1✔
283
        $options = array_merge($optionsLang, $options ?? []);
1✔
284

285
        return (new Url($this->builder, $value, $options))->getUrl();
1✔
286
    }
287

288
    /**
289
     * Creates an Asset (CSS, JS, images, etc.) from a path or an array of paths.
290
     *
291
     * @param string|array $path    File path or array of files path (relative from `assets/` or `static/` dir).
292
     * @param array|null   $options
293
     *
294
     * @return Asset
295
     */
296
    public function asset($path, array|null $options = null): Asset
297
    {
298
        if (!\is_string($path) && !\is_array($path)) {
1✔
299
            throw new RuntimeException(\sprintf('Argument of "%s()" must a string or an array.', \Cecil\Util::formatMethodName(__METHOD__)));
×
300
        }
301

302
        return new Asset($this->builder, $path, $options);
1✔
303
    }
304

305
    /**
306
     * Compiles a SCSS asset.
307
     *
308
     * @param string|Asset $asset
309
     *
310
     * @return Asset
311
     */
312
    public function toCss($asset): Asset
313
    {
314
        if (!$asset instanceof Asset) {
1✔
315
            $asset = new Asset($this->builder, $asset);
×
316
        }
317

318
        return $asset->compile();
1✔
319
    }
320

321
    /**
322
     * Minifying an asset (CSS or JS).
323
     *
324
     * @param string|Asset $asset
325
     *
326
     * @return Asset
327
     */
328
    public function minify($asset): Asset
329
    {
330
        if (!$asset instanceof Asset) {
1✔
331
            $asset = new Asset($this->builder, $asset);
×
332
        }
333

334
        return $asset->minify();
1✔
335
    }
336

337
    /**
338
     * Fingerprinting an asset.
339
     *
340
     * @param string|Asset $asset
341
     *
342
     * @return Asset
343
     */
344
    public function fingerprint($asset): Asset
345
    {
346
        if (!$asset instanceof Asset) {
1✔
347
            $asset = new Asset($this->builder, $asset);
×
348
        }
349

350
        return $asset->fingerprint();
1✔
351
    }
352

353
    /**
354
     * Resizes an image.
355
     *
356
     * @param string|Asset $asset
357
     *
358
     * @return Asset
359
     */
360
    public function resize($asset, int $size): Asset
361
    {
362
        if (!$asset instanceof Asset) {
1✔
363
            $asset = new Asset($this->builder, $asset);
×
364
        }
365

366
        return $asset->resize($size);
1✔
367
    }
368

369
    /**
370
     * Crops an image Asset to the given width and height, keeping the aspect ratio.
371
     *
372
     * @param string|Asset $asset
373
     * @param int          $width
374
     * @param int          $height
375
     * @param string       $position
376
     *
377
     * @return Asset
378
     */
379
    public function cover($asset, int $width, int $height, string $position = 'center'): Asset
380
    {
381
        if (!$asset instanceof Asset) {
1✔
382
            $asset = new Asset($this->builder, $asset);
×
383
        }
384

385
        return $asset->cover($width, $height, $position);
1✔
386
    }
387

388
    /**
389
     * Returns the data URL of an image.
390
     *
391
     * @param string|Asset $asset
392
     *
393
     * @return string
394
     */
395
    public function dataurl($asset): string
396
    {
397
        if (!$asset instanceof Asset) {
1✔
398
            $asset = new Asset($this->builder, $asset);
×
399
        }
400

401
        return $asset->dataurl();
1✔
402
    }
403

404
    /**
405
     * Hashing an asset with algo (sha384 by default).
406
     *
407
     * @param string|Asset $asset
408
     * @param string       $algo
409
     *
410
     * @return string
411
     */
412
    public function integrity($asset, string $algo = 'sha384'): string
413
    {
414
        if (!$asset instanceof Asset) {
1✔
415
            $asset = new Asset($this->builder, $asset);
1✔
416
        }
417

418
        return $asset->getIntegrity($algo);
1✔
419
    }
420

421
    /**
422
     * Minifying a CSS string.
423
     */
424
    public function minifyCss(?string $value): string
425
    {
426
        $value = $value ?? '';
1✔
427

428
        if ($this->builder->isDebug()) {
1✔
429
            return $value;
1✔
430
        }
431

432
        $cache = new Cache($this->builder, 'assets');
×
NEW
433
        $cacheKey = $cache->createKeyFromValue(null, $value);
×
434
        if (!$cache->has($cacheKey)) {
×
435
            $minifier = new Minify\CSS($value);
×
436
            $value = $minifier->minify();
×
437
            $cache->set($cacheKey, $value, $this->config->get('cache.assets.ttl'));
×
438
        }
439

440
        return $cache->get($cacheKey, $value);
×
441
    }
442

443
    /**
444
     * Minifying a JavaScript string.
445
     */
446
    public function minifyJs(?string $value): string
447
    {
448
        $value = $value ?? '';
1✔
449

450
        if ($this->builder->isDebug()) {
1✔
451
            return $value;
1✔
452
        }
453

454
        $cache = new Cache($this->builder, 'assets');
×
NEW
455
        $cacheKey = $cache->createKeyFromValue(null, $value);
×
456
        if (!$cache->has($cacheKey)) {
×
457
            $minifier = new Minify\JS($value);
×
458
            $value = $minifier->minify();
×
459
            $cache->set($cacheKey, $value, $this->config->get('cache.assets.ttl'));
×
460
        }
461

462
        return $cache->get($cacheKey, $value);
×
463
    }
464

465
    /**
466
     * Compiles a SCSS string.
467
     *
468
     * @throws RuntimeException
469
     */
470
    public function scssToCss(?string $value): string
471
    {
472
        $value = $value ?? '';
1✔
473

474
        $cache = new Cache($this->builder, 'assets');
1✔
475
        $cacheKey = $cache->createKeyFromValue(null, $value);
1✔
476
        if (!$cache->has($cacheKey)) {
1✔
477
            $scssPhp = new Compiler();
1✔
478
            $outputStyles = ['expanded', 'compressed'];
1✔
479
            $outputStyle = strtolower((string) $this->config->get('assets.compile.style'));
1✔
480
            if (!\in_array($outputStyle, $outputStyles)) {
1✔
481
                throw new ConfigException(\sprintf('"%s" value must be "%s".', 'assets.compile.style', implode('" or "', $outputStyles)));
×
482
            }
483
            $scssPhp->setOutputStyle($outputStyle == 'compressed' ? OutputStyle::COMPRESSED : OutputStyle::EXPANDED);
1✔
484
            $variables = $this->config->get('assets.compile.variables');
1✔
485
            if (!empty($variables)) {
1✔
486
                $variables = array_map('ScssPhp\ScssPhp\ValueConverter::parseValue', $variables);
1✔
487
                $scssPhp->replaceVariables($variables);
1✔
488
            }
489
            $value = $scssPhp->compileString($value)->getCss();
1✔
490
            $cache->set($cacheKey, $value, $this->config->get('cache.assets.ttl'));
1✔
491
        }
492

493
        return $cache->get($cacheKey, $value);
1✔
494
    }
495

496
    /**
497
     * Creates the HTML element of an asset.
498
     *
499
     * $options[
500
     *     'preload'    => false,
501
     *     'responsive' => false,
502
     *     'formats'    => [],
503
     * ];
504
     *
505
     * @throws RuntimeException
506
     */
507
    public function html(array $context, Asset $asset, array $attributes = [], array $options = []): string
508
    {
509
        $htmlAttributes = '';
1✔
510
        $preload = false;
1✔
511
        $responsive = $this->config->isEnabled('layouts.images.responsive');
1✔
512
        $formats = (array) $this->config->get('layouts.images.formats');
1✔
513
        extract($options, EXTR_IF_EXISTS);
1✔
514

515
        // builds HTML attributes
516
        foreach ($attributes as $name => $value) {
1✔
517
            $attribute = \sprintf(' %s="%s"', $name, $value);
1✔
518
            if (!isset($value)) {
1✔
519
                $attribute = \sprintf(' %s', $name);
×
520
            }
521
            $htmlAttributes .= $attribute;
1✔
522
        }
523

524
        // be sure Asset file is saved
525
        $asset->save();
1✔
526

527
        // CSS or JavaScript
528
        switch ($asset['ext']) {
1✔
529
            case 'css':
1✔
530
                if ($preload) {
1✔
531
                    return \sprintf(
×
532
                        '<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>',
×
533
                        $this->url($context, $asset, $options),
×
534
                        $htmlAttributes
×
535
                    );
×
536
                }
537

538
                return \sprintf('<link rel="stylesheet" href="%s"%s>', $this->url($context, $asset, $options), $htmlAttributes);
1✔
539
            case 'js':
1✔
540
                return \sprintf('<script src="%s"%s></script>', $this->url($context, $asset, $options), $htmlAttributes);
1✔
541
        }
542
        // image
543
        if ($asset['type'] == 'image') {
1✔
544
            // responsive
545
            $sizes = '';
1✔
546
            if (
547
                $responsive && $srcset = Image::buildSrcset(
1✔
548
                    $asset,
1✔
549
                    $this->config->getAssetsImagesWidths()
1✔
550
                )
1✔
551
            ) {
552
                $htmlAttributes .= \sprintf(' srcset="%s"', $srcset);
1✔
553
                $sizes = Image::getSizes($attributes['class'] ?? '', $this->config->getAssetsImagesSizes());
1✔
554
                $htmlAttributes .= \sprintf(' sizes="%s"', $sizes);
1✔
555
                if ($asset['width'] > max($this->config->getAssetsImagesWidths())) {
1✔
556
                    $asset = $asset->resize(max($this->config->getAssetsImagesWidths()));
×
557
                }
558
            }
559

560
            // <img> element
561
            $img = \sprintf(
1✔
562
                '<img src="%s" width="' . ($asset['width'] ?: '') . '" height="' . ($asset['height'] ?: '') . '"%s>',
1✔
563
                $this->url($context, $asset, $options),
1✔
564
                $htmlAttributes
1✔
565
            );
1✔
566

567
            // multiple <source>?
568
            if (\count($formats) > 0) {
1✔
569
                $source = '';
1✔
570
                foreach ($formats as $format) {
1✔
571
                    if ($asset['subtype'] != "image/$format" && !Image::isAnimatedGif($asset)) {
1✔
572
                        try {
573
                            $assetConverted = $asset->convert($format);
1✔
574
                            // responsive?
575
                            if ($responsive && $srcset = Image::buildSrcset($assetConverted, $this->config->getAssetsImagesWidths())) {
1✔
576
                                // <source> element
577
                                $source .= \sprintf(
1✔
578
                                    "\n  <source type=\"image/$format\" srcset=\"%s\" sizes=\"%s\">",
1✔
579
                                    $srcset,
1✔
580
                                    $sizes
1✔
581
                                );
1✔
582
                                continue;
1✔
583
                            }
584
                            // <source> element
585
                            $source .= \sprintf("\n  <source type=\"image/$format\" srcset=\"%s\">", $assetConverted);
×
586
                        } catch (\Exception $e) {
×
587
                            $this->builder->getLogger()->error($e->getMessage());
×
588
                            continue;
×
589
                        }
590
                    }
591
                }
592
                if (!empty($source)) {
1✔
593
                    return \sprintf("<picture>%s\n  %s\n</picture>", $source, $img);
1✔
594
                }
595
            }
596

597
            return $img;
×
598
        }
599

600
        throw new RuntimeException(\sprintf('%s is available for CSS, JavaScript and images files only.', '"html" filter'));
×
601
    }
602

603
    /**
604
     * Builds the HTML img `srcset` (responsive) attribute of an image Asset.
605
     *
606
     * @throws RuntimeException
607
     */
608
    public function imageSrcset(Asset $asset): string
609
    {
610
        return Image::buildSrcset($asset, $this->config->getAssetsImagesWidths());
1✔
611
    }
612

613
    /**
614
     * Returns the HTML img `sizes` attribute based on a CSS class name.
615
     */
616
    public function imageSizes(string $class): string
617
    {
618
        return Image::getSizes($class, $this->config->getAssetsImagesSizes());
1✔
619
    }
620

621
    /**
622
     * Converts an image Asset to WebP format.
623
     */
624
    public function webp(Asset $asset, ?int $quality = null): Asset
625
    {
626
        return $this->convert($asset, 'webp', $quality);
×
627
    }
628

629
    /**
630
     * Converts an image Asset to AVIF format.
631
     */
632
    public function avif(Asset $asset, ?int $quality = null): Asset
633
    {
634
        return $this->convert($asset, 'avif', $quality);
×
635
    }
636

637
    /**
638
     * Converts an image Asset to the given format.
639
     *
640
     * @throws RuntimeException
641
     */
642
    private function convert(Asset $asset, string $format, ?int $quality = null): Asset
643
    {
644
        if ($asset['subtype'] == "image/$format") {
×
645
            return $asset;
×
646
        }
647
        if (Image::isAnimatedGif($asset)) {
×
648
            throw new RuntimeException(\sprintf('Can\'t convert the animated GIF "%s" to %s.', $asset['path'], $format));
×
649
        }
650

651
        try {
652
            return $asset->$format($quality);
×
653
        } catch (\Exception $e) {
×
654
            throw new RuntimeException(\sprintf('Can\'t convert "%s" to %s (%s).', $asset['path'], $format, $e->getMessage()));
×
655
        }
656
    }
657

658
    /**
659
     * Returns the content of an asset.
660
     */
661
    public function inline(Asset $asset): string
662
    {
663
        return $asset['content'];
1✔
664
    }
665

666
    /**
667
     * Reads $length first characters of a string and adds a suffix.
668
     */
669
    public function excerpt(?string $string, int $length = 450, string $suffix = ' …'): string
670
    {
671
        $string = $string ?? '';
1✔
672

673
        $string = str_replace('</p>', '<br><br>', $string);
1✔
674
        $string = trim(strip_tags($string, '<br>'));
1✔
675
        if (mb_strlen($string) > $length) {
1✔
676
            $string = mb_substr($string, 0, $length);
1✔
677
            $string .= $suffix;
1✔
678
        }
679

680
        return $string;
1✔
681
    }
682

683
    /**
684
     * Reads characters before or after '<!-- separator -->'.
685
     * Options:
686
     *  - separator: string to use as separator (`excerpt|break` by default)
687
     *  - capture: part to capture, `before` or `after` the separator (`before` by default).
688
     */
689
    public function excerptHtml(?string $string, array $options = []): string
690
    {
691
        $string = $string ?? '';
1✔
692

693
        $separator = (string) $this->config->get('pages.body.excerpt.separator');
1✔
694
        $capture = (string) $this->config->get('pages.body.excerpt.capture');
1✔
695
        extract($options, EXTR_IF_EXISTS);
1✔
696

697
        // https://regex101.com/r/n9TWHF/1
698
        $pattern = '(.*)<!--[[:blank:]]?(' . $separator . ')[[:blank:]]?-->(.*)';
1✔
699
        preg_match('/' . $pattern . '/is', $string, $matches);
1✔
700

701
        if (empty($matches)) {
1✔
702
            return $string;
×
703
        }
704
        $result = trim($matches[1]);
1✔
705
        if ($capture == 'after') {
1✔
706
            $result = trim($matches[3]);
1✔
707
        }
708
        // removes footnotes and returns result
709
        return preg_replace('/<sup[^>]*>[^u]*<\/sup>/', '', $result);
1✔
710
    }
711

712
    /**
713
     * Converts a Markdown string to HTML.
714
     *
715
     * @throws RuntimeException
716
     */
717
    public function markdownToHtml(?string $markdown): ?string
718
    {
719
        $markdown = $markdown ?? '';
1✔
720

721
        try {
722
            $parsedown = new Parsedown($this->builder);
1✔
723
            $html = $parsedown->text($markdown);
1✔
724
        } catch (\Exception $e) {
×
725
            throw new RuntimeException(
×
726
                '"markdown_to_html" filter can not convert supplied Markdown.',
×
727
                previous: $e
×
728
            );
×
729
        }
730

731
        return $html;
1✔
732
    }
733

734
    /**
735
     * Extract table of content of a Markdown string,
736
     * in the given format ("html" or "json", "html" by default).
737
     *
738
     * @throws RuntimeException
739
     */
740
    public function markdownToToc(?string $markdown, $format = 'html', ?array $selectors = null, string $url = ''): ?string
741
    {
742
        $markdown = $markdown ?? '';
1✔
743
        $selectors = $selectors ?? (array) $this->config->get('pages.body.toc');
1✔
744

745
        try {
746
            $parsedown = new Parsedown($this->builder, ['selectors' => $selectors, 'url' => $url]);
1✔
747
            $parsedown->body($markdown);
1✔
748
            $return = $parsedown->contentsList($format);
1✔
749
        } catch (\Exception) {
×
750
            throw new RuntimeException('"toc" filter can not convert supplied Markdown.');
×
751
        }
752

753
        return $return;
1✔
754
    }
755

756
    /**
757
     * Converts a JSON string to an array.
758
     *
759
     * @throws RuntimeException
760
     */
761
    public function jsonDecode(?string $json): ?array
762
    {
763
        $json = $json ?? '';
1✔
764

765
        try {
766
            $array = json_decode($json, true);
1✔
767
            if ($array === null && json_last_error() !== JSON_ERROR_NONE) {
1✔
768
                throw new \Exception('JSON error.');
1✔
769
            }
770
        } catch (\Exception) {
×
771
            throw new RuntimeException('"json_decode" filter can not parse supplied JSON.');
×
772
        }
773

774
        return $array;
1✔
775
    }
776

777
    /**
778
     * Converts a YAML string to an array.
779
     *
780
     * @throws RuntimeException
781
     */
782
    public function yamlParse(?string $yaml): ?array
783
    {
784
        $yaml = $yaml ?? '';
1✔
785

786
        try {
787
            $array = Yaml::parse($yaml, Yaml::PARSE_DATETIME);
1✔
788
            if (!\is_array($array)) {
1✔
789
                throw new ParseException('YAML error.');
1✔
790
            }
791
        } catch (ParseException $e) {
×
792
            throw new RuntimeException(\sprintf('"yaml_parse" filter can not parse supplied YAML: %s', $e->getMessage()));
×
793
        }
794

795
        return $array;
1✔
796
    }
797

798
    /**
799
     * Split a string into an array using a regular expression.
800
     *
801
     * @throws RuntimeException
802
     */
803
    public function pregSplit(?string $value, string $pattern, int $limit = 0): ?array
804
    {
805
        $value = $value ?? '';
×
806

807
        try {
808
            $array = preg_split($pattern, $value, $limit);
×
809
            if ($array === false) {
×
810
                throw new RuntimeException('PREG split error.');
×
811
            }
812
        } catch (\Exception) {
×
813
            throw new RuntimeException('"preg_split" filter can not split supplied string.');
×
814
        }
815

816
        return $array;
×
817
    }
818

819
    /**
820
     * Perform a regular expression match and return the group for all matches.
821
     *
822
     * @throws RuntimeException
823
     */
824
    public function pregMatchAll(?string $value, string $pattern, int $group = 0): ?array
825
    {
826
        $value = $value ?? '';
×
827

828
        try {
829
            $array = preg_match_all($pattern, $value, $matches, PREG_PATTERN_ORDER);
×
830
            if ($array === false) {
×
831
                throw new RuntimeException('PREG match all error.');
×
832
            }
833
        } catch (\Exception) {
×
834
            throw new RuntimeException('"preg_match_all" filter can not match in supplied string.');
×
835
        }
836

837
        return $matches[$group];
×
838
    }
839

840
    /**
841
     * Calculates estimated time to read a text.
842
     */
843
    public function readtime(?string $text): string
844
    {
845
        $text = $text ?? '';
1✔
846

847
        $words = str_word_count(strip_tags($text));
1✔
848
        $min = floor($words / 200);
1✔
849
        if ($min === 0) {
1✔
850
            return '1';
×
851
        }
852

853
        return (string) $min;
1✔
854
    }
855

856
    /**
857
     * Gets the value of an environment variable.
858
     */
859
    public function getEnv(?string $var): ?string
860
    {
861
        $var = $var ?? '';
1✔
862

863
        return getenv($var) ?: null;
1✔
864
    }
865

866
    /**
867
     * Dump variable (or Twig context).
868
     */
869
    public function varDump(\Twig\Environment $env, array $context, $var = null, ?array $options = null): void
870
    {
871
        if (!$env->isDebug()) {
1✔
872
            return;
×
873
        }
874

875
        if ($var === null) {
1✔
876
            $var = array();
×
877
            foreach ($context as $key => $value) {
×
878
                if (!$value instanceof \Twig\Template && !$value instanceof \Twig\TemplateWrapper) {
×
879
                    $var[$key] = $value;
×
880
                }
881
            }
882
        }
883

884
        $cloner = new VarCloner();
1✔
885
        $cloner->setMinDepth(3);
1✔
886
        $dumper = new HtmlDumper();
1✔
887
        $dumper->setTheme($options['theme'] ?? 'light');
1✔
888

889
        $data = $cloner->cloneVar($var)->withMaxDepth(3);
1✔
890
        $dumper->dump($data, null, ['maxDepth' => 3]);
1✔
891
    }
892

893
    /**
894
     * Tests if a variable is an Asset.
895
     */
896
    public function isAsset($variable): bool
897
    {
898
        return $variable instanceof Asset;
1✔
899
    }
900

901
    /**
902
     * Returns the dominant hex color of an image asset.
903
     *
904
     * @param string|Asset $asset
905
     *
906
     * @return string
907
     */
908
    public function dominantColor($asset): string
909
    {
910
        if (!$asset instanceof Asset) {
1✔
911
            $asset = new Asset($this->builder, $asset);
×
912
        }
913

914
        return Image::getDominantColor($asset);
1✔
915
    }
916

917
    /**
918
     * Returns a Low Quality Image Placeholder (LQIP) as data URL.
919
     *
920
     * @param string|Asset $asset
921
     *
922
     * @return string
923
     */
924
    public function lqip($asset): string
925
    {
926
        if (!$asset instanceof Asset) {
1✔
927
            $asset = new Asset($this->builder, $asset);
×
928
        }
929

930
        return Image::getLqip($asset);
1✔
931
    }
932

933
    /**
934
     * Converts an hexadecimal color to RGB.
935
     *
936
     * @throws RuntimeException
937
     */
938
    public function hexToRgb(?string $variable): array
939
    {
940
        $variable = $variable ?? '';
1✔
941

942
        if (!self::isHex($variable)) {
1✔
943
            throw new RuntimeException(\sprintf('"%s" is not a valid hexadecimal value.', $variable));
×
944
        }
945
        $hex = ltrim($variable, '#');
1✔
946
        if (\strlen($hex) == 3) {
1✔
947
            $hex = $hex[0] . $hex[0] . $hex[1] . $hex[1] . $hex[2] . $hex[2];
×
948
        }
949
        $c = hexdec($hex);
1✔
950

951
        return [
1✔
952
            'red'   => $c >> 16 & 0xFF,
1✔
953
            'green' => $c >> 8 & 0xFF,
1✔
954
            'blue'  => $c & 0xFF,
1✔
955
        ];
1✔
956
    }
957

958
    /**
959
     * Split a string in multiple lines.
960
     */
961
    public function splitLine(?string $variable, int $max = 18): array
962
    {
963
        $variable = $variable ?? '';
1✔
964

965
        return preg_split("/.{0,{$max}}\K(\s+|$)/", $variable, 0, PREG_SPLIT_NO_EMPTY);
1✔
966
    }
967

968
    /**
969
     * Hashing an object, an array or a string (with algo, md5 by default).
970
     */
971
    public function hash(object|array|string $data, $algo = 'md5'): string
972
    {
973
        switch (\gettype($data)) {
1✔
974
            case 'object':
1✔
975
                return spl_object_hash($data);
1✔
976
            case 'array':
×
977
                return hash($algo, serialize($data));
×
978
        }
979

980
        return hash($algo, $data);
×
981
    }
982

983
    /**
984
     * Converts a variable to an iterable (array).
985
     */
986
    public function iterable($value): array
987
    {
988
        if (\is_array($value)) {
1✔
989
            return $value;
1✔
990
        }
991
        if (\is_string($value)) {
×
992
            return [$value];
×
993
        }
994
        if ($value instanceof \Traversable) {
×
995
            return iterator_to_array($value);
×
996
        }
997
        if ($value instanceof \stdClass) {
×
998
            return (array) $value;
×
999
        }
1000
        if (\is_object($value)) {
×
1001
            return [$value];
×
1002
        }
1003
        if (\is_int($value) || \is_float($value)) {
×
1004
            return [$value];
×
1005
        }
1006
        return [$value];
×
1007
    }
1008

1009
    /**
1010
     * Is a hexadecimal color is valid?
1011
     */
1012
    private static function isHex(string $hex): bool
1013
    {
1014
        $valid = \is_string($hex);
1✔
1015
        $hex = ltrim($hex, '#');
1✔
1016
        $length = \strlen($hex);
1✔
1017
        $valid = $valid && ($length === 3 || $length === 6);
1✔
1018
        $valid = $valid && ctype_xdigit($hex);
1✔
1019

1020
        return $valid;
1✔
1021
    }
1022
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc