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

Cecilapp / Cecil / 19348690432

13 Nov 2025 11:09PM UTC coverage: 81.965% (+0.06%) from 81.909%
19348690432

push

github

web-flow
feat: pixels density support for responsive images (#2244)

48 of 49 new or added lines in 4 files covered. (97.96%)

3 existing lines in 1 file now uncovered.

3204 of 3909 relevant lines covered (81.96%)

0.82 hits per line

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

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

3
/**
4
 * This file is part of Cecil.
5
 *
6
 * (c) Arnaud Ligny <arnaud@ligny.fr>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11

12
declare(strict_types=1);
13

14
namespace Cecil\Renderer\Extension;
15

16
use Cecil\Asset;
17
use Cecil\Asset\Image;
18
use Cecil\Builder;
19
use Cecil\Cache;
20
use Cecil\Collection\CollectionInterface;
21
use Cecil\Collection\Page\Collection as PagesCollection;
22
use Cecil\Collection\Page\Page;
23
use Cecil\Collection\Page\Type;
24
use Cecil\Config;
25
use Cecil\Converter\Parsedown;
26
use Cecil\Exception\ConfigException;
27
use Cecil\Exception\RuntimeException;
28
use Cecil\Url;
29
use Cocur\Slugify\Bridge\Twig\SlugifyExtension;
30
use Cocur\Slugify\Slugify;
31
use Highlight\Highlighter;
32
use MatthiasMullie\Minify;
33
use ScssPhp\ScssPhp\Compiler;
34
use ScssPhp\ScssPhp\OutputStyle;
35
use Symfony\Component\VarDumper\Cloner\VarCloner;
36
use Symfony\Component\VarDumper\Dumper\HtmlDumper;
37
use Symfony\Component\Yaml\Exception\ParseException;
38
use Symfony\Component\Yaml\Yaml;
39
use Twig\DeprecatedCallableInfo;
40

41
/**
42
 * Core Twig extension.
43
 *
44
 * This extension provides various utility functions and filters for use in Twig templates,
45
 * including URL generation, asset management, content processing, and more.
46
 */
47
class Core extends SlugifyExtension
48
{
49
    /** @var Builder */
50
    protected $builder;
51

52
    /** @var Config */
53
    protected $config;
54

55
    /** @var Slugify */
56
    private static $slugifier;
57

58
    public function __construct(Builder $builder)
59
    {
60
        if (!self::$slugifier instanceof Slugify) {
1✔
61
            self::$slugifier = Slugify::create(['regexp' => Page::SLUGIFY_PATTERN]);
1✔
62
        }
63

64
        parent::__construct(self::$slugifier);
1✔
65

66
        $this->builder = $builder;
1✔
67
        $this->config = $builder->getConfig();
1✔
68
    }
69

70
    /**
71
     * {@inheritdoc}
72
     */
73
    public function getName(): string
74
    {
75
        return 'CoreExtension';
×
76
    }
77

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

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

169
    /**
170
     * {@inheritdoc}
171
     */
172
    public function getTests()
173
    {
174
        return [
1✔
175
            new \Twig\TwigTest('asset', [$this, 'isAsset']),
1✔
176
            new \Twig\TwigTest('image_large', [$this, 'isImageLarge']),
1✔
177
            new \Twig\TwigTest('image_square', [$this, 'isImageSquare']),
1✔
178
        ];
1✔
179
    }
180

181
    /**
182
     * Filters by Section.
183
     */
184
    public function filterBySection(PagesCollection $pages, string $section): CollectionInterface
185
    {
186
        return $this->filterBy($pages, 'section', $section);
×
187
    }
188

189
    /**
190
     * Filters a pages collection by variable's name/value.
191
     */
192
    public function filterBy(PagesCollection $pages, string $variable, string $value): CollectionInterface
193
    {
194
        $filteredPages = $pages->filter(function (Page $page) use ($variable, $value) {
1✔
195
            // is a dedicated getter exists?
196
            $method = 'get' . ucfirst($variable);
1✔
197
            if (method_exists($page, $method) && $page->$method() == $value) {
1✔
198
                return $page->getType() == Type::PAGE->value && !$page->isVirtual() && true;
×
199
            }
200
            // or a classic variable
201
            if ($page->getVariable($variable) == $value) {
1✔
202
                return $page->getType() == Type::PAGE->value && !$page->isVirtual() && true;
1✔
203
            }
204
        });
1✔
205

206
        return $filteredPages;
1✔
207
    }
208

209
    /**
210
     * Sorts a collection by title.
211
     */
212
    public function sortByTitle(\Traversable $collection): array
213
    {
214
        $sort = \SORT_ASC;
1✔
215

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

219
        return $collection;
1✔
220
    }
221

222
    /**
223
     * Sorts a collection by weight.
224
     *
225
     * @param \Traversable|array $collection
226
     */
227
    public function sortByWeight($collection): array
228
    {
229
        $callback = function ($a, $b) {
1✔
230
            if (!isset($a['weight'])) {
1✔
231
                $a['weight'] = 0;
1✔
232
            }
233
            if (!isset($b['weight'])) {
1✔
234
                $a['weight'] = 0;
×
235
            }
236
            if ($a['weight'] == $b['weight']) {
1✔
237
                return 0;
1✔
238
            }
239

240
            return $a['weight'] < $b['weight'] ? -1 : 1;
1✔
241
        };
1✔
242

243
        if (!\is_array($collection)) {
1✔
244
            $collection = iterator_to_array($collection);
1✔
245
        }
246
        usort(/** @scrutinizer ignore-type */ $collection, $callback);
1✔
247

248
        return $collection;
1✔
249
    }
250

251
    /**
252
     * Sorts by creation date (or 'updated' date): the most recent first.
253
     */
254
    public function sortByDate(\Traversable $collection, string $variable = 'date', bool $descTitle = false): array
255
    {
256
        $callback = function ($a, $b) use ($variable, $descTitle) {
1✔
257
            if ($a[$variable] == $b[$variable]) {
1✔
258
                // if dates are equal and "descTitle" is true
259
                if ($descTitle && (isset($a['title']) && isset($b['title']))) {
1✔
260
                    return strnatcmp($b['title'], $a['title']);
×
261
                }
262

263
                return 0;
1✔
264
            }
265

266
            return $a[$variable] > $b[$variable] ? -1 : 1;
1✔
267
        };
1✔
268

269
        $collection = iterator_to_array($collection);
1✔
270
        usort(/** @scrutinizer ignore-type */ $collection, $callback);
1✔
271

272
        return $collection;
1✔
273
    }
274

275
    /**
276
     * Creates an URL.
277
     *
278
     * $options[
279
     *     'canonical' => false,
280
     *     'format'    => 'html',
281
     *     'language'  => null,
282
     * ];
283
     *
284
     * @param array                  $context
285
     * @param Page|Asset|string|null $value
286
     * @param array|null             $options
287
     */
288
    public function url(array $context, $value = null, ?array $options = null): string
289
    {
290
        $optionsLang = [];
1✔
291
        $optionsLang['language'] = (string) $context['site']['language'];
1✔
292
        $options = array_merge($optionsLang, $options ?? []);
1✔
293

294
        return (new Url($this->builder, $value, $options))->getUrl();
1✔
295
    }
296

297
    /**
298
     * Creates an Asset (CSS, JS, images, etc.) from a path or an array of paths.
299
     *
300
     * @param string|array $path    File path or array of files path (relative from `assets/` or `static/` dir).
301
     * @param array|null   $options
302
     *
303
     * @return Asset
304
     */
305
    public function asset($path, array|null $options = null): Asset
306
    {
307
        if (!\is_string($path) && !\is_array($path)) {
1✔
308
            throw new RuntimeException(\sprintf('Argument of "%s()" must a string or an array.', \Cecil\Util::formatMethodName(__METHOD__)));
×
309
        }
310

311
        return new Asset($this->builder, $path, $options);
1✔
312
    }
313

314
    /**
315
     * Compiles a SCSS asset.
316
     *
317
     * @param string|Asset $asset
318
     *
319
     * @return Asset
320
     */
321
    public function toCss($asset): Asset
322
    {
323
        if (!$asset instanceof Asset) {
1✔
324
            $asset = new Asset($this->builder, $asset);
×
325
        }
326

327
        return $asset->compile();
1✔
328
    }
329

330
    /**
331
     * Minifying an asset (CSS or JS).
332
     *
333
     * @param string|Asset $asset
334
     *
335
     * @return Asset
336
     */
337
    public function minify($asset): Asset
338
    {
339
        if (!$asset instanceof Asset) {
1✔
340
            $asset = new Asset($this->builder, $asset);
×
341
        }
342

343
        return $asset->minify();
1✔
344
    }
345

346
    /**
347
     * Fingerprinting an asset.
348
     *
349
     * @param string|Asset $asset
350
     *
351
     * @return Asset
352
     */
353
    public function fingerprint($asset): Asset
354
    {
355
        if (!$asset instanceof Asset) {
1✔
356
            $asset = new Asset($this->builder, $asset);
×
357
        }
358

359
        return $asset->fingerprint();
1✔
360
    }
361

362
    /**
363
     * Resizes an image.
364
     *
365
     * @param string|Asset $asset
366
     *
367
     * @return Asset
368
     */
369
    public function resize($asset, int $size): Asset
370
    {
371
        if (!$asset instanceof Asset) {
1✔
372
            $asset = new Asset($this->builder, $asset);
×
373
        }
374

375
        return $asset->resize($size);
1✔
376
    }
377

378
    /**
379
     * Crops an image Asset to the given width and height, keeping the aspect ratio.
380
     *
381
     * @param string|Asset $asset
382
     *
383
     * @return Asset
384
     */
385
    public function cover($asset, int $width, int $height): Asset
386
    {
387
        if (!$asset instanceof Asset) {
1✔
388
            $asset = new Asset($this->builder, $asset);
×
389
        }
390

391
        return $asset->cover($width, $height);
1✔
392
    }
393

394
    /**
395
     * Creates a maskable icon from an image asset.
396
     * The maskable icon is used for Progressive Web Apps (PWAs).
397
     *
398
     * @param string|Asset $asset
399
     *
400
     * @return Asset
401
     */
402
    public function maskable($asset, ?int $padding = null): Asset
403
    {
404
        if (!$asset instanceof Asset) {
×
405
            $asset = new Asset($this->builder, $asset);
×
406
        }
407

408
        return $asset->maskable($padding);
×
409
    }
410

411
    /**
412
     * Returns the data URL of an image.
413
     *
414
     * @param string|Asset $asset
415
     *
416
     * @return string
417
     */
418
    public function dataurl($asset): string
419
    {
420
        if (!$asset instanceof Asset) {
1✔
421
            $asset = new Asset($this->builder, $asset);
×
422
        }
423

424
        return $asset->dataurl();
1✔
425
    }
426

427
    /**
428
     * Hashing an asset with algo (sha384 by default).
429
     *
430
     * @param string|Asset $asset
431
     * @param string       $algo
432
     *
433
     * @return string
434
     */
435
    public function integrity($asset, string $algo = 'sha384'): string
436
    {
437
        if (!$asset instanceof Asset) {
1✔
438
            $asset = new Asset($this->builder, $asset);
1✔
439
        }
440

441
        return $asset->getIntegrity($algo);
1✔
442
    }
443

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

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

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

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

466
    /**
467
     * Minifying a JavaScript string.
468
     */
469
    public function minifyJs(?string $value): string
470
    {
471
        $value = $value ?? '';
1✔
472

473
        if ($this->builder->isDebug()) {
1✔
474
            return $value;
1✔
475
        }
476

477
        $cache = new Cache($this->builder, 'assets');
×
478
        $cacheKey = $cache->createKeyFromValue(null, $value);
×
479
        if (!$cache->has($cacheKey)) {
×
480
            $minifier = new Minify\JS($value);
×
481
            $value = $minifier->minify();
×
482
            $cache->set($cacheKey, $value, $this->config->get('cache.assets.ttl'));
×
483
        }
484

485
        return $cache->get($cacheKey, $value);
×
486
    }
487

488
    /**
489
     * Compiles a SCSS string.
490
     *
491
     * @throws RuntimeException
492
     */
493
    public function scssToCss(?string $value): string
494
    {
495
        $value = $value ?? '';
1✔
496

497
        $cache = new Cache($this->builder, 'assets');
1✔
498
        $cacheKey = $cache->createKeyFromValue(null, $value);
1✔
499
        if (!$cache->has($cacheKey)) {
1✔
500
            $scssPhp = new Compiler();
1✔
501
            $outputStyles = ['expanded', 'compressed'];
1✔
502
            $outputStyle = strtolower((string) $this->config->get('assets.compile.style'));
1✔
503
            if (!\in_array($outputStyle, $outputStyles)) {
1✔
504
                throw new ConfigException(\sprintf('"%s" value must be "%s".', 'assets.compile.style', implode('" or "', $outputStyles)));
×
505
            }
506
            $scssPhp->setOutputStyle($outputStyle == 'compressed' ? OutputStyle::COMPRESSED : OutputStyle::EXPANDED);
1✔
507
            $variables = $this->config->get('assets.compile.variables');
1✔
508
            if (!empty($variables)) {
1✔
509
                $variables = array_map('ScssPhp\ScssPhp\ValueConverter::parseValue', $variables);
1✔
510
                $scssPhp->replaceVariables($variables);
1✔
511
            }
512
            $value = $scssPhp->compileString($value)->getCss();
1✔
513
            $cache->set($cacheKey, $value, $this->config->get('cache.assets.ttl'));
1✔
514
        }
515

516
        return $cache->get($cacheKey, $value);
1✔
517
    }
518

519
    /**
520
     * Creates the HTML element of an asset.
521
     *
522
     * @param array                                                                $context    Twig context
523
     * @param Asset|array<int,array{asset:Asset,attributes:?array<string,string>}> $assets     Asset or array of assets + attributes
524
     * @param array                                                                $attributes HTML attributes to add to the element
525
     * @param array                                                                $options    Options:
526
     * [
527
     *     'preload'    => false,
528
     *     'responsive' => false,
529
     *     'formats'    => [],
530
     * ];
531
     *
532
     * @return string HTML element
533
     *
534
     * @throws RuntimeException
535
     */
536
    public function html(array $context, Asset|array $assets, array $attributes = [], array $options = []): string
537
    {
538
        $html = array();
1✔
539
        if (!\is_array($assets)) {
1✔
540
            $assets = [['asset' => $assets, 'attributes' => null]];
1✔
541
        }
542
        foreach ($assets as $assetData) {
1✔
543
            $asset = $assetData['asset'];
1✔
544
            if (!$asset instanceof Asset) {
1✔
545
                $asset = new Asset($this->builder, $asset);
×
546
            }
547
            $attr = $attributes;
1✔
548
            // specific attributes
549
            if ($assetData['attributes'] !== null) {
1✔
550
                $attr = $attributes + $assetData['attributes'];
1✔
551
            }
552
            // be sure Asset file is saved
553
            $asset->save();
1✔
554
            // CSS or JavaScript
555
            switch ($asset['ext']) {
1✔
556
                case 'css':
1✔
557
                    $html[] = $this->htmlCss($context, $asset, $attr, $options);
1✔
558
                    break;
1✔
559
                case 'js':
1✔
560
                    $html[] = $this->htmlJs($context, $asset, $attr, $options);
1✔
561
            }
562
            // image
563
            if ($asset['type'] == 'image') {
1✔
564
                $html[] = $this->htmlImage($context, $asset, $attr, $options);
1✔
565
            }
566
            unset($attr);
1✔
567
        }
568
        if (empty($html)) {
1✔
569
            throw new RuntimeException(\sprintf('%s is available for CSS, JavaScript and image files only.', '"html" filter'));
×
570
        }
571

572
        return implode(PHP_EOL, $html);
1✔
573
    }
574

575
    /**
576
     * Builds the HTML link element of a CSS Asset.
577
     */
578
    public function htmlCss(array $context, Asset $asset, array $attributes = [], array $options = []): string
579
    {
580
        $htmlAttributes = self::htmlAttributes($attributes);
1✔
581
        $preload = $options['preload'] ?? false;
1✔
582
        if ($preload) {
1✔
583
            return \sprintf(
×
584
                '<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>',
×
585
                $this->url($context, $asset, $options),
×
586
                $htmlAttributes
×
587
            );
×
588
        }
589

590
        return \sprintf('<link rel="stylesheet" href="%s"%s>', $this->url($context, $asset, $options), $htmlAttributes);
1✔
591
    }
592

593
    /**
594
     * Builds the HTML script element of a JS Asset.
595
     */
596
    public function htmlJs(array $context, Asset $asset, array $attributes = [], array $options = []): string
597
    {
598
        $htmlAttributes = self::htmlAttributes($attributes);
1✔
599

600
        return \sprintf('<script src="%s"%s></script>', $this->url($context, $asset, $options), $htmlAttributes);
1✔
601
    }
602

603
    /**
604
     * Builds the HTML img element of an image Asset.
605
     */
606
    public function htmlImage(array $context, Asset $asset, array $attributes = [], array $options = []): string
607
    {
608
        $htmlAttributes = self::htmlAttributes($attributes);
1✔
609
        if (!isset($attributes['alt'])) {
1✔
610
            $htmlAttributes .= ' alt=""';
1✔
611
        }
612
        $responsive = $options['responsive'] ?? $this->config->get('layouts.images.responsive');
1✔
613

614
        // build responsive attributes
615
        try {
616
            if ($responsive === true || $responsive == 'width') {
1✔
617
                $srcset = Image::buildHtmlSrcsetW($asset, $this->config->getAssetsImagesWidths());
1✔
618
                $htmlAttributes .= \sprintf(' srcset="%s" sizes="%s"', $srcset, Image::getHtmlSizes($attributes['class'] ?? '', $this->config->getAssetsImagesSizes()));
1✔
619
                // prevent oversized images
620
                if ($asset['width'] > max($this->config->getAssetsImagesWidths())) {
1✔
UNCOV
621
                    $asset = $asset->resize(max($this->config->getAssetsImagesWidths()));
×
622
                }
623
            }
624
            if ($responsive == 'density') {
1✔
625
                $width1x = isset($attributes['width']) && $attributes['width'] > 0 ? (int) $attributes['width'] : $asset['width'];
1✔
626
                $srcset = Image::buildHtmlSrcsetX($asset, $width1x, $this->config->getAssetsImagesDensities());
1✔
627
                $htmlAttributes .= \sprintf(' srcset="%s"', $srcset);
1✔
628
            }
629
        } catch (\Exception $e) {
×
630
            $this->builder->getLogger()->warning($e->getMessage());
×
631
        }
632

633
        // create alternative formats (`<source>`)
634
        try {
635
            $formats = $options['formats'] ?? (array) $this->config->get('layouts.images.formats');
1✔
636
            if (\count($formats) > 0) {
1✔
637
                $source = '';
1✔
638
                foreach ($formats as $format) {
1✔
639
                    try {
640
                        $assetConverted = $asset->convert($format);
1✔
641
                        // responsive
642
                        if ($responsive === true || $responsive == 'width') {
1✔
643
                            $srcset = Image::buildHtmlSrcsetW($assetConverted, $this->config->getAssetsImagesWidths());
1✔
644
                            $source .= \sprintf("\n  <source type=\"image/$format\" srcset=\"%s\" sizes=\"%s\">", $srcset, Image::getHtmlSizes($attributes['class'] ?? '', $this->config->getAssetsImagesSizes()));
1✔
645
                            continue;
1✔
646
                        }
647
                        if ($responsive == 'density') {
1✔
648
                            $width1x = isset($attributes['width']) && $attributes['width'] > 0 ? (int) $attributes['width'] : $asset['width'];
1✔
649
                            $srcset = Image::buildHtmlSrcsetX($assetConverted, $width1x, $this->config->getAssetsImagesDensities());
1✔
650
                            $source .= \sprintf("\n  <source type=\"image/$format\" srcset=\"%s\">", $srcset);
1✔
651
                            continue;
1✔
652
                        }
653
                        $source .= \sprintf("\n  <source type=\"image/$format\" srcset=\"%s\">", $assetConverted);
1✔
UNCOV
654
                    } catch (\Exception $e) {
×
655
                        $this->builder->getLogger()->warning($e->getMessage());
×
656
                        continue;
×
657
                    }
658
                }
659
            }
UNCOV
660
        } catch (\Exception $e) {
×
661
            $this->builder->getLogger()->warning($e->getMessage());
×
662
        }
663

664
        // create `<img>` element
665
        if (isset($attributes['width']) && $attributes['width'] > 0) {
1✔
666
            $asset = $asset->resize((int) $attributes['width']);
1✔
667
        }
668
        if (!isset($attributes['width'])) {
1✔
669
            $htmlAttributes .= \sprintf(' width="%s"', $asset['width'] ?: '');
1✔
670
        }
671
        $htmlAttributes .= \sprintf(' height="%s"', $asset['height'] ?: '');
1✔
672
        $img = \sprintf('<img src="%s"%s>', $this->url($context, $asset, $options), $htmlAttributes);
1✔
673

674
        // put `<source>` elements in `<picture>` if exists
675
        if (!empty($source)) {
1✔
676
            return \sprintf("<picture>%s\n  %s\n</picture>", $source, $img);
1✔
677
        }
678

679
        return $img;
1✔
680
    }
681

682
    /**
683
     * Builds the HTML img `srcset` (responsive) attribute of an image Asset, based on configured widths.
684
     *
685
     * @throws RuntimeException
686
     */
687
    public function imageSrcset(Asset $asset): string
688
    {
689
        return Image::buildHtmlSrcsetW($asset, $this->config->getAssetsImagesWidths(), true);
1✔
690
    }
691

692
    /**
693
     * Returns the HTML img `sizes` attribute based on a CSS class name.
694
     */
695
    public function imageSizes(string $class): string
696
    {
697
        return Image::getHtmlSizes($class, $this->config->getAssetsImagesSizes());
1✔
698
    }
699

700
    /**
701
     * Converts an image Asset to WebP format.
702
     */
703
    public function webp(Asset $asset, ?int $quality = null): Asset
704
    {
705
        return $this->convert($asset, 'webp', $quality);
×
706
    }
707

708
    /**
709
     * Converts an image Asset to AVIF format.
710
     */
711
    public function avif(Asset $asset, ?int $quality = null): Asset
712
    {
713
        return $this->convert($asset, 'avif', $quality);
×
714
    }
715

716
    /**
717
     * Converts an image Asset to the given format.
718
     *
719
     * @throws RuntimeException
720
     */
721
    private function convert(Asset $asset, string $format, ?int $quality = null): Asset
722
    {
723
        if ($asset['subtype'] == "image/$format") {
×
724
            return $asset;
×
725
        }
726
        if (Image::isAnimatedGif($asset)) {
×
727
            throw new RuntimeException(\sprintf('Unable to convert the animated GIF "%s" to %s.', $asset['path'], $format));
×
728
        }
729

730
        try {
731
            return $asset->$format($quality);
×
732
        } catch (\Exception $e) {
×
733
            throw new RuntimeException(\sprintf('Unable to convert "%s" to %s (%s).', $asset['path'], $format, $e->getMessage()));
×
734
        }
735
    }
736

737
    /**
738
     * Returns the content of an asset.
739
     */
740
    public function inline(Asset $asset): string
741
    {
742
        return $asset['content'];
1✔
743
    }
744

745
    /**
746
     * Reads $length first characters of a string and adds a suffix.
747
     */
748
    public function excerpt(?string $string, int $length = 450, string $suffix = ' …'): string
749
    {
750
        $string = $string ?? '';
1✔
751

752
        $string = str_replace('</p>', '<br><br>', $string);
1✔
753
        $string = trim(strip_tags($string, '<br>'));
1✔
754
        if (mb_strlen($string) > $length) {
1✔
755
            $string = mb_substr($string, 0, $length);
1✔
756
            $string .= $suffix;
1✔
757
        }
758

759
        return $string;
1✔
760
    }
761

762
    /**
763
     * Reads characters before or after '<!-- separator -->'.
764
     * Options:
765
     *  - separator: string to use as separator (`excerpt|break` by default)
766
     *  - capture: part to capture, `before` or `after` the separator (`before` by default).
767
     */
768
    public function excerptHtml(?string $string, array $options = []): string
769
    {
770
        $string = $string ?? '';
1✔
771

772
        $separator = (string) $this->config->get('pages.body.excerpt.separator');
1✔
773
        $capture = (string) $this->config->get('pages.body.excerpt.capture');
1✔
774
        extract($options, EXTR_IF_EXISTS);
1✔
775

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

780
        if (empty($matches)) {
1✔
781
            return $string;
×
782
        }
783
        $result = trim($matches[1]);
1✔
784
        if ($capture == 'after') {
1✔
785
            $result = trim($matches[3]);
1✔
786
        }
787
        // removes footnotes and returns result
788
        return preg_replace('/<sup[^>]*>[^u]*<\/sup>/', '', $result);
1✔
789
    }
790

791
    /**
792
     * Converts a Markdown string to HTML.
793
     *
794
     * @throws RuntimeException
795
     */
796
    public function markdownToHtml(?string $markdown): ?string
797
    {
798
        $markdown = $markdown ?? '';
1✔
799

800
        try {
801
            $parsedown = new Parsedown($this->builder);
1✔
802
            $html = $parsedown->text($markdown);
1✔
803
        } catch (\Exception $e) {
×
804
            throw new RuntimeException(
×
805
                '"markdown_to_html" filter can not convert supplied Markdown.',
×
806
                previous: $e
×
807
            );
×
808
        }
809

810
        return $html;
1✔
811
    }
812

813
    /**
814
     * Extract table of content of a Markdown string,
815
     * in the given format ("html" or "json", "html" by default).
816
     *
817
     * @throws RuntimeException
818
     */
819
    public function markdownToToc(?string $markdown, $format = 'html', ?array $selectors = null, string $url = ''): ?string
820
    {
821
        $markdown = $markdown ?? '';
1✔
822
        $selectors = $selectors ?? (array) $this->config->get('pages.body.toc');
1✔
823

824
        try {
825
            $parsedown = new Parsedown($this->builder, ['selectors' => $selectors, 'url' => $url]);
1✔
826
            $parsedown->body($markdown);
1✔
827
            $return = $parsedown->contentsList($format);
1✔
828
        } catch (\Exception) {
×
829
            throw new RuntimeException('"toc" filter can not convert supplied Markdown.');
×
830
        }
831

832
        return $return;
1✔
833
    }
834

835
    /**
836
     * Converts a JSON string to an array.
837
     *
838
     * @throws RuntimeException
839
     */
840
    public function jsonDecode(?string $json): ?array
841
    {
842
        $json = $json ?? '';
1✔
843

844
        try {
845
            $array = json_decode($json, true);
1✔
846
            if ($array === null && json_last_error() !== JSON_ERROR_NONE) {
1✔
847
                throw new \Exception('JSON error.');
1✔
848
            }
849
        } catch (\Exception) {
×
850
            throw new RuntimeException('"json_decode" filter can not parse supplied JSON.');
×
851
        }
852

853
        return $array;
1✔
854
    }
855

856
    /**
857
     * Converts a YAML string to an array.
858
     *
859
     * @throws RuntimeException
860
     */
861
    public function yamlParse(?string $yaml): ?array
862
    {
863
        $yaml = $yaml ?? '';
1✔
864

865
        try {
866
            $array = Yaml::parse($yaml, Yaml::PARSE_DATETIME);
1✔
867
            if (!\is_array($array)) {
1✔
868
                throw new ParseException('YAML error.');
1✔
869
            }
870
        } catch (ParseException $e) {
×
871
            throw new RuntimeException(\sprintf('"yaml_parse" filter can not parse supplied YAML: %s', $e->getMessage()));
×
872
        }
873

874
        return $array;
1✔
875
    }
876

877
    /**
878
     * Split a string into an array using a regular expression.
879
     *
880
     * @throws RuntimeException
881
     */
882
    public function pregSplit(?string $value, string $pattern, int $limit = 0): ?array
883
    {
884
        $value = $value ?? '';
×
885

886
        try {
887
            $array = preg_split($pattern, $value, $limit);
×
888
            if ($array === false) {
×
889
                throw new RuntimeException('PREG split error.');
×
890
            }
891
        } catch (\Exception) {
×
892
            throw new RuntimeException('"preg_split" filter can not split supplied string.');
×
893
        }
894

895
        return $array;
×
896
    }
897

898
    /**
899
     * Perform a regular expression match and return the group for all matches.
900
     *
901
     * @throws RuntimeException
902
     */
903
    public function pregMatchAll(?string $value, string $pattern, int $group = 0): ?array
904
    {
905
        $value = $value ?? '';
×
906

907
        try {
908
            $array = preg_match_all($pattern, $value, $matches, PREG_PATTERN_ORDER);
×
909
            if ($array === false) {
×
910
                throw new RuntimeException('PREG match all error.');
×
911
            }
912
        } catch (\Exception) {
×
913
            throw new RuntimeException('"preg_match_all" filter can not match in supplied string.');
×
914
        }
915

916
        return $matches[$group];
×
917
    }
918

919
    /**
920
     * Calculates estimated time to read a text.
921
     */
922
    public function readtime(?string $text): string
923
    {
924
        $text = $text ?? '';
1✔
925

926
        $words = str_word_count(strip_tags($text));
1✔
927
        $min = floor($words / 200);
1✔
928
        if ($min === 0) {
1✔
929
            return '1';
×
930
        }
931

932
        return (string) $min;
1✔
933
    }
934

935
    /**
936
     * Gets the value of an environment variable.
937
     */
938
    public function getEnv(?string $var): ?string
939
    {
940
        $var = $var ?? '';
1✔
941

942
        return getenv($var) ?: null;
1✔
943
    }
944

945
    /**
946
     * Dump variable (or Twig context).
947
     */
948
    public function varDump(\Twig\Environment $env, array $context, $var = null, ?array $options = null): void
949
    {
950
        if (!$env->isDebug()) {
1✔
951
            return;
×
952
        }
953

954
        if ($var === null) {
1✔
955
            $var = array();
×
956
            foreach ($context as $key => $value) {
×
957
                if (!$value instanceof \Twig\Template && !$value instanceof \Twig\TemplateWrapper) {
×
958
                    $var[$key] = $value;
×
959
                }
960
            }
961
        }
962

963
        $cloner = new VarCloner();
1✔
964
        $cloner->setMinDepth(3);
1✔
965
        $dumper = new HtmlDumper();
1✔
966
        $dumper->setTheme($options['theme'] ?? 'light');
1✔
967

968
        $data = $cloner->cloneVar($var)->withMaxDepth(3);
1✔
969
        $dumper->dump($data, null, ['maxDepth' => 3]);
1✔
970
    }
971

972
    /**
973
     * Tests if a variable is an Asset.
974
     */
975
    public function isAsset($variable): bool
976
    {
977
        return $variable instanceof Asset;
1✔
978
    }
979

980
    /**
981
     * Tests if an image Asset is large enough to be used as a cover image.
982
     * A large image is defined as having a width >= 600px and height >= 315px.
983
     */
984
    public function isImageLarge(Asset $asset): bool
985
    {
986
        return $asset['type'] == 'image' && $asset['width'] > $asset['height'] && $asset['width'] >= 600 && $asset['height'] >= 315;
1✔
987
    }
988

989
    /**
990
     * Tests if an image Asset is square.
991
     * A square image is defined as having the same width and height.
992
     */
993
    public function isImageSquare(Asset $asset): bool
994
    {
995
        return $asset['type'] == 'image' && $asset['width'] == $asset['height'];
1✔
996
    }
997

998
    /**
999
     * Returns the dominant hex color of an image asset.
1000
     *
1001
     * @param string|Asset $asset
1002
     *
1003
     * @return string
1004
     */
1005
    public function dominantColor($asset): string
1006
    {
1007
        if (!$asset instanceof Asset) {
1✔
1008
            $asset = new Asset($this->builder, $asset);
×
1009
        }
1010

1011
        return Image::getDominantColor($asset);
1✔
1012
    }
1013

1014
    /**
1015
     * Returns a Low Quality Image Placeholder (LQIP) as data URL.
1016
     *
1017
     * @param string|Asset $asset
1018
     *
1019
     * @return string
1020
     */
1021
    public function lqip($asset): string
1022
    {
1023
        if (!$asset instanceof Asset) {
1✔
1024
            $asset = new Asset($this->builder, $asset);
×
1025
        }
1026

1027
        return Image::getLqip($asset);
1✔
1028
    }
1029

1030
    /**
1031
     * Converts an hexadecimal color to RGB.
1032
     *
1033
     * @throws RuntimeException
1034
     */
1035
    public function hexToRgb(?string $variable): array
1036
    {
1037
        $variable = $variable ?? '';
1✔
1038

1039
        if (!self::isHex($variable)) {
1✔
1040
            throw new RuntimeException(\sprintf('"%s" is not a valid hexadecimal value.', $variable));
×
1041
        }
1042
        $hex = ltrim($variable, '#');
1✔
1043
        if (\strlen($hex) == 3) {
1✔
1044
            $hex = $hex[0] . $hex[0] . $hex[1] . $hex[1] . $hex[2] . $hex[2];
×
1045
        }
1046
        $c = hexdec($hex);
1✔
1047

1048
        return [
1✔
1049
            'red'   => $c >> 16 & 0xFF,
1✔
1050
            'green' => $c >> 8 & 0xFF,
1✔
1051
            'blue'  => $c & 0xFF,
1✔
1052
        ];
1✔
1053
    }
1054

1055
    /**
1056
     * Split a string in multiple lines.
1057
     */
1058
    public function splitLine(?string $variable, int $max = 18): array
1059
    {
1060
        $variable = $variable ?? '';
1✔
1061

1062
        return preg_split("/.{0,{$max}}\K(\s+|$)/", $variable, 0, PREG_SPLIT_NO_EMPTY);
1✔
1063
    }
1064

1065
    /**
1066
     * Hashing an object, an array or a string (with algo, md5 by default).
1067
     */
1068
    public function hash(object|array|string $data, $algo = 'md5'): string
1069
    {
1070
        switch (\gettype($data)) {
1✔
1071
            case 'object':
1✔
1072
                return spl_object_hash($data);
1✔
1073
            case 'array':
×
1074
                return hash($algo, serialize($data));
×
1075
        }
1076

1077
        return hash($algo, $data);
×
1078
    }
1079

1080
    /**
1081
     * Converts a variable to an iterable (array).
1082
     */
1083
    public function iterable($value): array
1084
    {
1085
        if (\is_array($value)) {
1✔
1086
            return $value;
1✔
1087
        }
1088
        if (\is_string($value)) {
×
1089
            return [$value];
×
1090
        }
1091
        if ($value instanceof \Traversable) {
×
1092
            return iterator_to_array($value);
×
1093
        }
1094
        if ($value instanceof \stdClass) {
×
1095
            return (array) $value;
×
1096
        }
1097
        if (\is_object($value)) {
×
1098
            return [$value];
×
1099
        }
1100
        if (\is_int($value) || \is_float($value)) {
×
1101
            return [$value];
×
1102
        }
1103
        return [$value];
×
1104
    }
1105

1106
    /**
1107
     * Highlights a code snippet.
1108
     */
1109
    public function highlight(string $code, string $language): string
1110
    {
1111
        return (new Highlighter())->highlight($language, $code)->value;
×
1112
    }
1113

1114
    /**
1115
     * Returns an array with unique values.
1116
     */
1117
    public function unique(array $array): array
1118
    {
1119
        return array_intersect_key($array, array_unique(array_map('strtolower', $array), SORT_STRING));
1✔
1120
    }
1121

1122
    /**
1123
     * Is a hexadecimal color is valid?
1124
     */
1125
    private static function isHex(string $hex): bool
1126
    {
1127
        $valid = \is_string($hex);
1✔
1128
        $hex = ltrim($hex, '#');
1✔
1129
        $length = \strlen($hex);
1✔
1130
        $valid = $valid && ($length === 3 || $length === 6);
1✔
1131
        $valid = $valid && ctype_xdigit($hex);
1✔
1132

1133
        return $valid;
1✔
1134
    }
1135

1136
    /**
1137
     * Builds the HTML attributes string from an array.
1138
     */
1139
    private static function htmlAttributes(array $attributes): string
1140
    {
1141
        $htmlAttributes = '';
1✔
1142
        foreach ($attributes as $name => $value) {
1✔
1143
            $attribute = \sprintf(' %s="%s"', $name, $value);
1✔
1144
            if (!isset($value)) {
1✔
1145
                $attribute = \sprintf(' %s', $name);
×
1146
            }
1147
            $htmlAttributes .= $attribute;
1✔
1148
        }
1149

1150
        return $htmlAttributes;
1✔
1151
    }
1152
}
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