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

Cecilapp / Cecil / 16418665341

21 Jul 2025 01:42PM UTC coverage: 81.954% (-0.7%) from 82.623%
16418665341

push

github

web-flow
Apply fixes from StyleCI (#2203)

0 of 2 new or added lines in 1 file covered. (0.0%)

184 existing lines in 3 files now uncovered.

3120 of 3807 relevant lines covered (81.95%)

0.82 hits per line

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

73.16
/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\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
 * Core Twig extension.
42
 *
43
 * This extension provides various utility functions and filters for use in Twig templates,
44
 * including URL generation, asset management, content processing, and more.
45
 */
46
class Core extends SlugifyExtension
47
{
48
    /** @var Builder */
49
    protected $builder;
50

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

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

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

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

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

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

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

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

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

176
    /**
177
     * Filters by Section.
178
     */
179
    public function filterBySection(PagesCollection $pages, string $section): CollectionInterface
180
    {
UNCOV
181
        return $this->filterBy($pages, 'section', $section);
×
182
    }
183

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

201
        return $filteredPages;
1✔
202
    }
203

204
    /**
205
     * Sorts a collection by title.
206
     */
207
    public function sortByTitle(\Traversable $collection): array
208
    {
209
        $sort = \SORT_ASC;
1✔
210

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

214
        return $collection;
1✔
215
    }
216

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

235
            return $a['weight'] < $b['weight'] ? -1 : 1;
1✔
236
        };
1✔
237

238
        if (!\is_array($collection)) {
1✔
239
            $collection = iterator_to_array($collection);
1✔
240
        }
241
        usort(/** @scrutinizer ignore-type */ $collection, $callback);
1✔
242

243
        return $collection;
1✔
244
    }
245

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

258
                return 0;
1✔
259
            }
260

261
            return $a[$variable] > $b[$variable] ? -1 : 1;
1✔
262
        };
1✔
263

264
        $collection = iterator_to_array($collection);
1✔
265
        usort(/** @scrutinizer ignore-type */ $collection, $callback);
1✔
266

267
        return $collection;
1✔
268
    }
269

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

289
        return (new Url($this->builder, $value, $options))->getUrl();
1✔
290
    }
291

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

306
        return new Asset($this->builder, $path, $options);
1✔
307
    }
308

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

322
        return $asset->compile();
1✔
323
    }
324

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

338
        return $asset->minify();
1✔
339
    }
340

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

354
        return $asset->fingerprint();
1✔
355
    }
356

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

370
        return $asset->resize($size);
1✔
371
    }
372

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

389
        return $asset->cover($width, $height, $position);
1✔
390
    }
391

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

UNCOV
406
        return $asset->maskable();
×
407
    }
408

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

422
        return $asset->dataurl();
1✔
423
    }
424

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

439
        return $asset->getIntegrity($algo);
1✔
440
    }
441

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

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

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

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

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

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

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

UNCOV
483
        return $cache->get($cacheKey, $value);
×
484
    }
485

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

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

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

517
    /**
518
     * Creates the HTML element of an asset.
519
     *
520
     * $options[
521
     *     'preload'    => false,
522
     *     'responsive' => false,
523
     *     'formats'    => [],
524
     * ];
525
     *
526
     * @throws RuntimeException
527
     */
528
    public function html(array $context, Asset $asset, array $attributes = [], array $options = []): string
529
    {
530
        $htmlAttributes = '';
1✔
531
        $preload = false;
1✔
532
        $responsive = $this->config->isEnabled('layouts.images.responsive');
1✔
533
        $formats = (array) $this->config->get('layouts.images.formats');
1✔
534
        extract($options, EXTR_IF_EXISTS);
1✔
535

536
        // builds HTML attributes
537
        foreach ($attributes as $name => $value) {
1✔
538
            $attribute = \sprintf(' %s="%s"', $name, $value);
1✔
539
            if (!isset($value)) {
1✔
UNCOV
540
                $attribute = \sprintf(' %s', $name);
×
541
            }
542
            $htmlAttributes .= $attribute;
1✔
543
        }
544

545
        // be sure Asset file is saved
546
        $asset->save();
1✔
547

548
        // CSS or JavaScript
549
        switch ($asset['ext']) {
1✔
550
            case 'css':
1✔
551
                if ($preload) {
1✔
UNCOV
552
                    return \sprintf(
×
UNCOV
553
                        '<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>',
×
UNCOV
554
                        $this->url($context, $asset, $options),
×
UNCOV
555
                        $htmlAttributes
×
UNCOV
556
                    );
×
557
                }
558

559
                return \sprintf('<link rel="stylesheet" href="%s"%s>', $this->url($context, $asset, $options), $htmlAttributes);
1✔
560
            case 'js':
1✔
561
                return \sprintf('<script src="%s"%s></script>', $this->url($context, $asset, $options), $htmlAttributes);
1✔
562
        }
563
        // image
564
        if ($asset['type'] == 'image') {
1✔
565
            // responsive
566
            $sizes = '';
1✔
567
            if (
568
                $responsive && $srcset = Image::buildSrcset(
1✔
569
                    $asset,
1✔
570
                    $this->config->getAssetsImagesWidths()
1✔
571
                )
1✔
572
            ) {
573
                $htmlAttributes .= \sprintf(' srcset="%s"', $srcset);
1✔
574
                $sizes = Image::getSizes($attributes['class'] ?? '', $this->config->getAssetsImagesSizes());
1✔
575
                $htmlAttributes .= \sprintf(' sizes="%s"', $sizes);
1✔
576
                if ($asset['width'] > max($this->config->getAssetsImagesWidths())) {
1✔
UNCOV
577
                    $asset = $asset->resize(max($this->config->getAssetsImagesWidths()));
×
578
                }
579
            }
580

581
            // <img> element
582
            $img = \sprintf(
1✔
583
                '<img src="%s" width="' . ($asset['width'] ?: '') . '" height="' . ($asset['height'] ?: '') . '"%s>',
1✔
584
                $this->url($context, $asset, $options),
1✔
585
                $htmlAttributes
1✔
586
            );
1✔
587

588
            // multiple <source>?
589
            if (\count($formats) > 0) {
1✔
590
                $source = '';
1✔
591
                foreach ($formats as $format) {
1✔
592
                    if ($asset['subtype'] != "image/$format" && !Image::isAnimatedGif($asset)) {
1✔
593
                        try {
594
                            $assetConverted = $asset->convert($format);
1✔
595
                            // responsive?
596
                            if ($responsive && $srcset = Image::buildSrcset($assetConverted, $this->config->getAssetsImagesWidths())) {
1✔
597
                                // <source> element
598
                                $source .= \sprintf(
1✔
599
                                    "\n  <source type=\"image/$format\" srcset=\"%s\" sizes=\"%s\">",
1✔
600
                                    $srcset,
1✔
601
                                    $sizes
1✔
602
                                );
1✔
603
                                continue;
1✔
604
                            }
605
                            // <source> element
UNCOV
606
                            $source .= \sprintf("\n  <source type=\"image/$format\" srcset=\"%s\">", $assetConverted);
×
UNCOV
607
                        } catch (\Exception $e) {
×
UNCOV
608
                            $this->builder->getLogger()->error($e->getMessage());
×
UNCOV
609
                            continue;
×
610
                        }
611
                    }
612
                }
613
                if (!empty($source)) {
1✔
614
                    return \sprintf("<picture>%s\n  %s\n</picture>", $source, $img);
1✔
615
                }
616
            }
617

UNCOV
618
            return $img;
×
619
        }
620

UNCOV
621
        throw new RuntimeException(\sprintf('%s is available for CSS, JavaScript and images files only.', '"html" filter'));
×
622
    }
623

624
    /**
625
     * Builds the HTML img `srcset` (responsive) attribute of an image Asset.
626
     *
627
     * @throws RuntimeException
628
     */
629
    public function imageSrcset(Asset $asset): string
630
    {
631
        return Image::buildSrcset($asset, $this->config->getAssetsImagesWidths());
1✔
632
    }
633

634
    /**
635
     * Returns the HTML img `sizes` attribute based on a CSS class name.
636
     */
637
    public function imageSizes(string $class): string
638
    {
639
        return Image::getSizes($class, $this->config->getAssetsImagesSizes());
1✔
640
    }
641

642
    /**
643
     * Converts an image Asset to WebP format.
644
     */
645
    public function webp(Asset $asset, ?int $quality = null): Asset
646
    {
647
        return $this->convert($asset, 'webp', $quality);
×
648
    }
649

650
    /**
651
     * Converts an image Asset to AVIF format.
652
     */
653
    public function avif(Asset $asset, ?int $quality = null): Asset
654
    {
655
        return $this->convert($asset, 'avif', $quality);
×
656
    }
657

658
    /**
659
     * Converts an image Asset to the given format.
660
     *
661
     * @throws RuntimeException
662
     */
663
    private function convert(Asset $asset, string $format, ?int $quality = null): Asset
664
    {
UNCOV
665
        if ($asset['subtype'] == "image/$format") {
×
UNCOV
666
            return $asset;
×
667
        }
UNCOV
668
        if (Image::isAnimatedGif($asset)) {
×
UNCOV
669
            throw new RuntimeException(\sprintf('Can\'t convert the animated GIF "%s" to %s.', $asset['path'], $format));
×
670
        }
671

672
        try {
UNCOV
673
            return $asset->$format($quality);
×
UNCOV
674
        } catch (\Exception $e) {
×
UNCOV
675
            throw new RuntimeException(\sprintf('Can\'t convert "%s" to %s (%s).', $asset['path'], $format, $e->getMessage()));
×
676
        }
677
    }
678

679
    /**
680
     * Returns the content of an asset.
681
     */
682
    public function inline(Asset $asset): string
683
    {
684
        return $asset['content'];
1✔
685
    }
686

687
    /**
688
     * Reads $length first characters of a string and adds a suffix.
689
     */
690
    public function excerpt(?string $string, int $length = 450, string $suffix = ' …'): string
691
    {
692
        $string = $string ?? '';
1✔
693

694
        $string = str_replace('</p>', '<br><br>', $string);
1✔
695
        $string = trim(strip_tags($string, '<br>'));
1✔
696
        if (mb_strlen($string) > $length) {
1✔
697
            $string = mb_substr($string, 0, $length);
1✔
698
            $string .= $suffix;
1✔
699
        }
700

701
        return $string;
1✔
702
    }
703

704
    /**
705
     * Reads characters before or after '<!-- separator -->'.
706
     * Options:
707
     *  - separator: string to use as separator (`excerpt|break` by default)
708
     *  - capture: part to capture, `before` or `after` the separator (`before` by default).
709
     */
710
    public function excerptHtml(?string $string, array $options = []): string
711
    {
712
        $string = $string ?? '';
1✔
713

714
        $separator = (string) $this->config->get('pages.body.excerpt.separator');
1✔
715
        $capture = (string) $this->config->get('pages.body.excerpt.capture');
1✔
716
        extract($options, EXTR_IF_EXISTS);
1✔
717

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

722
        if (empty($matches)) {
1✔
UNCOV
723
            return $string;
×
724
        }
725
        $result = trim($matches[1]);
1✔
726
        if ($capture == 'after') {
1✔
727
            $result = trim($matches[3]);
1✔
728
        }
729
        // removes footnotes and returns result
730
        return preg_replace('/<sup[^>]*>[^u]*<\/sup>/', '', $result);
1✔
731
    }
732

733
    /**
734
     * Converts a Markdown string to HTML.
735
     *
736
     * @throws RuntimeException
737
     */
738
    public function markdownToHtml(?string $markdown): ?string
739
    {
740
        $markdown = $markdown ?? '';
1✔
741

742
        try {
743
            $parsedown = new Parsedown($this->builder);
1✔
744
            $html = $parsedown->text($markdown);
1✔
UNCOV
745
        } catch (\Exception $e) {
×
UNCOV
746
            throw new RuntimeException(
×
UNCOV
747
                '"markdown_to_html" filter can not convert supplied Markdown.',
×
UNCOV
748
                previous: $e
×
UNCOV
749
            );
×
750
        }
751

752
        return $html;
1✔
753
    }
754

755
    /**
756
     * Extract table of content of a Markdown string,
757
     * in the given format ("html" or "json", "html" by default).
758
     *
759
     * @throws RuntimeException
760
     */
761
    public function markdownToToc(?string $markdown, $format = 'html', ?array $selectors = null, string $url = ''): ?string
762
    {
763
        $markdown = $markdown ?? '';
1✔
764
        $selectors = $selectors ?? (array) $this->config->get('pages.body.toc');
1✔
765

766
        try {
767
            $parsedown = new Parsedown($this->builder, ['selectors' => $selectors, 'url' => $url]);
1✔
768
            $parsedown->body($markdown);
1✔
769
            $return = $parsedown->contentsList($format);
1✔
UNCOV
770
        } catch (\Exception) {
×
UNCOV
771
            throw new RuntimeException('"toc" filter can not convert supplied Markdown.');
×
772
        }
773

774
        return $return;
1✔
775
    }
776

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

786
        try {
787
            $array = json_decode($json, true);
1✔
788
            if ($array === null && json_last_error() !== JSON_ERROR_NONE) {
1✔
789
                throw new \Exception('JSON error.');
1✔
790
            }
UNCOV
791
        } catch (\Exception) {
×
UNCOV
792
            throw new RuntimeException('"json_decode" filter can not parse supplied JSON.');
×
793
        }
794

795
        return $array;
1✔
796
    }
797

798
    /**
799
     * Converts a YAML string to an array.
800
     *
801
     * @throws RuntimeException
802
     */
803
    public function yamlParse(?string $yaml): ?array
804
    {
805
        $yaml = $yaml ?? '';
1✔
806

807
        try {
808
            $array = Yaml::parse($yaml, Yaml::PARSE_DATETIME);
1✔
809
            if (!\is_array($array)) {
1✔
810
                throw new ParseException('YAML error.');
1✔
811
            }
812
        } catch (ParseException $e) {
×
813
            throw new RuntimeException(\sprintf('"yaml_parse" filter can not parse supplied YAML: %s', $e->getMessage()));
×
814
        }
815

816
        return $array;
1✔
817
    }
818

819
    /**
820
     * Split a string into an array using a regular expression.
821
     *
822
     * @throws RuntimeException
823
     */
824
    public function pregSplit(?string $value, string $pattern, int $limit = 0): ?array
825
    {
UNCOV
826
        $value = $value ?? '';
×
827

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

837
        return $array;
×
838
    }
839

840
    /**
841
     * Perform a regular expression match and return the group for all matches.
842
     *
843
     * @throws RuntimeException
844
     */
845
    public function pregMatchAll(?string $value, string $pattern, int $group = 0): ?array
846
    {
UNCOV
847
        $value = $value ?? '';
×
848

849
        try {
UNCOV
850
            $array = preg_match_all($pattern, $value, $matches, PREG_PATTERN_ORDER);
×
UNCOV
851
            if ($array === false) {
×
UNCOV
852
                throw new RuntimeException('PREG match all error.');
×
853
            }
UNCOV
854
        } catch (\Exception) {
×
UNCOV
855
            throw new RuntimeException('"preg_match_all" filter can not match in supplied string.');
×
856
        }
857

UNCOV
858
        return $matches[$group];
×
859
    }
860

861
    /**
862
     * Calculates estimated time to read a text.
863
     */
864
    public function readtime(?string $text): string
865
    {
866
        $text = $text ?? '';
1✔
867

868
        $words = str_word_count(strip_tags($text));
1✔
869
        $min = floor($words / 200);
1✔
870
        if ($min === 0) {
1✔
UNCOV
871
            return '1';
×
872
        }
873

874
        return (string) $min;
1✔
875
    }
876

877
    /**
878
     * Gets the value of an environment variable.
879
     */
880
    public function getEnv(?string $var): ?string
881
    {
882
        $var = $var ?? '';
1✔
883

884
        return getenv($var) ?: null;
1✔
885
    }
886

887
    /**
888
     * Dump variable (or Twig context).
889
     */
890
    public function varDump(\Twig\Environment $env, array $context, $var = null, ?array $options = null): void
891
    {
892
        if (!$env->isDebug()) {
1✔
UNCOV
893
            return;
×
894
        }
895

896
        if ($var === null) {
1✔
UNCOV
897
            $var = array();
×
UNCOV
898
            foreach ($context as $key => $value) {
×
UNCOV
899
                if (!$value instanceof \Twig\Template && !$value instanceof \Twig\TemplateWrapper) {
×
UNCOV
900
                    $var[$key] = $value;
×
901
                }
902
            }
903
        }
904

905
        $cloner = new VarCloner();
1✔
906
        $cloner->setMinDepth(3);
1✔
907
        $dumper = new HtmlDumper();
1✔
908
        $dumper->setTheme($options['theme'] ?? 'light');
1✔
909

910
        $data = $cloner->cloneVar($var)->withMaxDepth(3);
1✔
911
        $dumper->dump($data, null, ['maxDepth' => 3]);
1✔
912
    }
913

914
    /**
915
     * Tests if a variable is an Asset.
916
     */
917
    public function isAsset($variable): bool
918
    {
919
        return $variable instanceof Asset;
1✔
920
    }
921

922
    /**
923
     * Returns the dominant hex color of an image asset.
924
     *
925
     * @param string|Asset $asset
926
     *
927
     * @return string
928
     */
929
    public function dominantColor($asset): string
930
    {
931
        if (!$asset instanceof Asset) {
1✔
UNCOV
932
            $asset = new Asset($this->builder, $asset);
×
933
        }
934

935
        return Image::getDominantColor($asset);
1✔
936
    }
937

938
    /**
939
     * Returns a Low Quality Image Placeholder (LQIP) as data URL.
940
     *
941
     * @param string|Asset $asset
942
     *
943
     * @return string
944
     */
945
    public function lqip($asset): string
946
    {
947
        if (!$asset instanceof Asset) {
1✔
UNCOV
948
            $asset = new Asset($this->builder, $asset);
×
949
        }
950

951
        return Image::getLqip($asset);
1✔
952
    }
953

954
    /**
955
     * Converts an hexadecimal color to RGB.
956
     *
957
     * @throws RuntimeException
958
     */
959
    public function hexToRgb(?string $variable): array
960
    {
961
        $variable = $variable ?? '';
1✔
962

963
        if (!self::isHex($variable)) {
1✔
UNCOV
964
            throw new RuntimeException(\sprintf('"%s" is not a valid hexadecimal value.', $variable));
×
965
        }
966
        $hex = ltrim($variable, '#');
1✔
967
        if (\strlen($hex) == 3) {
1✔
UNCOV
968
            $hex = $hex[0] . $hex[0] . $hex[1] . $hex[1] . $hex[2] . $hex[2];
×
969
        }
970
        $c = hexdec($hex);
1✔
971

972
        return [
1✔
973
            'red'   => $c >> 16 & 0xFF,
1✔
974
            'green' => $c >> 8 & 0xFF,
1✔
975
            'blue'  => $c & 0xFF,
1✔
976
        ];
1✔
977
    }
978

979
    /**
980
     * Split a string in multiple lines.
981
     */
982
    public function splitLine(?string $variable, int $max = 18): array
983
    {
984
        $variable = $variable ?? '';
1✔
985

986
        return preg_split("/.{0,{$max}}\K(\s+|$)/", $variable, 0, PREG_SPLIT_NO_EMPTY);
1✔
987
    }
988

989
    /**
990
     * Hashing an object, an array or a string (with algo, md5 by default).
991
     */
992
    public function hash(object|array|string $data, $algo = 'md5'): string
993
    {
994
        switch (\gettype($data)) {
1✔
995
            case 'object':
1✔
996
                return spl_object_hash($data);
1✔
997
            case 'array':
×
998
                return hash($algo, serialize($data));
×
999
        }
1000

1001
        return hash($algo, $data);
×
1002
    }
1003

1004
    /**
1005
     * Converts a variable to an iterable (array).
1006
     */
1007
    public function iterable($value): array
1008
    {
1009
        if (\is_array($value)) {
1✔
1010
            return $value;
1✔
1011
        }
UNCOV
1012
        if (\is_string($value)) {
×
UNCOV
1013
            return [$value];
×
1014
        }
UNCOV
1015
        if ($value instanceof \Traversable) {
×
UNCOV
1016
            return iterator_to_array($value);
×
1017
        }
UNCOV
1018
        if ($value instanceof \stdClass) {
×
UNCOV
1019
            return (array) $value;
×
1020
        }
UNCOV
1021
        if (\is_object($value)) {
×
UNCOV
1022
            return [$value];
×
1023
        }
UNCOV
1024
        if (\is_int($value) || \is_float($value)) {
×
UNCOV
1025
            return [$value];
×
1026
        }
UNCOV
1027
        return [$value];
×
1028
    }
1029

1030
    /**
1031
     * Is a hexadecimal color is valid?
1032
     */
1033
    private static function isHex(string $hex): bool
1034
    {
1035
        $valid = \is_string($hex);
1✔
1036
        $hex = ltrim($hex, '#');
1✔
1037
        $length = \strlen($hex);
1✔
1038
        $valid = $valid && ($length === 3 || $length === 6);
1✔
1039
        $valid = $valid && ctype_xdigit($hex);
1✔
1040

1041
        return $valid;
1✔
1042
    }
1043
}
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