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

Cecilapp / Cecil / 21143795213

19 Jan 2026 03:54PM UTC coverage: 82.274%. First build
21143795213

Pull #2285

github

web-flow
Merge 40c08ca9d into 878eab640
Pull Request #2285: Integrate PHP-DI for dependency injection

58 of 83 new or added lines in 16 files covered. (69.88%)

3328 of 4045 relevant lines covered (82.27%)

0.82 hits per line

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

77.25
/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 Cecil\Util;
30
use Cocur\Slugify\Bridge\Twig\SlugifyExtension;
31
use Cocur\Slugify\Slugify;
32
use Highlight\Highlighter;
33
use MatthiasMullie\Minify;
34
use ScssPhp\ScssPhp\Compiler;
35
use ScssPhp\ScssPhp\OutputStyle;
36
use Symfony\Component\VarDumper\Cloner\VarCloner;
37
use Symfony\Component\VarDumper\Dumper\HtmlDumper;
38
use Symfony\Component\Yaml\Exception\ParseException;
39
use Symfony\Component\Yaml\Yaml;
40
use Twig\DeprecatedCallableInfo;
41

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

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

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

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

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

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

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

79
    /**
80
     * {@inheritdoc}
81
     */
82
    public function getFunctions()
83
    {
84
        return [
1✔
85
            new \Twig\TwigFunction('url', [$this, 'url'], ['needs_context' => true]),
1✔
86
            // assets
87
            new \Twig\TwigFunction('asset', [$this, 'asset']),
1✔
88
            new \Twig\TwigFunction('html', [$this, 'html'], ['needs_context' => true]),
1✔
89
            new \Twig\TwigFunction('css', [$this, 'htmlCss'], ['needs_context' => true]),
1✔
90
            new \Twig\TwigFunction('js', [$this, 'htmlJs'], ['needs_context' => true]),
1✔
91
            new \Twig\TwigFunction('image', [$this, 'htmlImage'], ['needs_context' => true]),
1✔
92
            new \Twig\TwigFunction('audio', [$this, 'htmlAudio'], ['needs_context' => true]),
1✔
93
            new \Twig\TwigFunction('video', [$this, 'htmlVideo'], ['needs_context' => true]),
1✔
94
            new \Twig\TwigFunction('integrity', [$this, 'integrity']),
1✔
95
            new \Twig\TwigFunction('image_srcset', [$this, 'imageSrcset']),
1✔
96
            new \Twig\TwigFunction('image_sizes', [$this, 'imageSizes']),
1✔
97
            new \Twig\TwigFunction('image_from_website', [$this, 'htmlImageFromWebsite'], ['needs_context' => true]),
1✔
98
            // content
99
            new \Twig\TwigFunction('readtime', [$this, 'readtime']),
1✔
100
            new \Twig\TwigFunction('hash', [$this, 'hash']),
1✔
101
            // others
102
            new \Twig\TwigFunction('getenv', [$this, 'getEnv']),
1✔
103
            new \Twig\TwigFunction('d', [$this, 'varDump'], ['needs_context' => true, 'needs_environment' => true]),
1✔
104
            // deprecated
105
            new \Twig\TwigFunction(
1✔
106
                'minify',
1✔
107
                [$this, 'minify'],
1✔
108
                ['deprecation_info' => new DeprecatedCallableInfo('', '', 'minify filter')]
1✔
109
            ),
1✔
110
            new \Twig\TwigFunction(
1✔
111
                'toCSS',
1✔
112
                [$this, 'toCss'],
1✔
113
                ['deprecation_info' => new DeprecatedCallableInfo('', '', 'to_css filter')]
1✔
114
            ),
1✔
115
            new \Twig\TwigFunction(
1✔
116
                'image_from_url',
1✔
117
                [$this, 'htmlImageFromWebsite'],
1✔
118
                ['deprecation_info' => new DeprecatedCallableInfo('', '', 'image_from_website function')]
1✔
119
            ),
1✔
120
        ];
1✔
121
    }
122

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

188
    /**
189
     * {@inheritdoc}
190
     */
191
    public function getTests()
192
    {
193
        return [
1✔
194
            new \Twig\TwigTest('asset', [$this, 'isAsset']),
1✔
195
            new \Twig\TwigTest('image_large', [$this, 'isImageLarge']),
1✔
196
            new \Twig\TwigTest('image_square', [$this, 'isImageSquare']),
1✔
197
        ];
1✔
198
    }
199

200
    /**
201
     * Filters by Section.
202
     */
203
    public function filterBySection(PagesCollection $pages, string $section): CollectionInterface
204
    {
205
        return $this->filterBy($pages, 'section', $section);
×
206
    }
207

208
    /**
209
     * Filters a pages collection by variable's name/value.
210
     */
211
    public function filterBy(PagesCollection $pages, string $variable, string $value): CollectionInterface
212
    {
213
        $filteredPages = $pages->filter(function (Page $page) use ($variable, $value) {
1✔
214
            // is a dedicated getter exists?
215
            $method = 'get' . ucfirst($variable);
1✔
216
            if (method_exists($page, $method) && $page->$method() == $value) {
1✔
217
                return $page->getType() == Type::PAGE->value && !$page->isVirtual() && true;
×
218
            }
219
            // or a classic variable
220
            if ($page->getVariable($variable) == $value) {
1✔
221
                return $page->getType() == Type::PAGE->value && !$page->isVirtual() && true;
1✔
222
            }
223
        });
1✔
224

225
        return $filteredPages;
1✔
226
    }
227

228
    /**
229
     * Sorts a collection by title.
230
     */
231
    public function sortByTitle(\Traversable $collection): array
232
    {
233
        $sort = \SORT_ASC;
1✔
234

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

238
        return $collection;
1✔
239
    }
240

241
    /**
242
     * Sorts a collection by weight.
243
     *
244
     * @param \Traversable|array $collection
245
     */
246
    public function sortByWeight($collection): array
247
    {
248
        $callback = function ($a, $b) {
1✔
249
            if (!isset($a['weight'])) {
1✔
250
                $a['weight'] = 0;
1✔
251
            }
252
            if (!isset($b['weight'])) {
1✔
253
                $a['weight'] = 0;
×
254
            }
255
            if ($a['weight'] == $b['weight']) {
1✔
256
                return 0;
1✔
257
            }
258

259
            return $a['weight'] < $b['weight'] ? -1 : 1;
1✔
260
        };
1✔
261

262
        if (!\is_array($collection)) {
1✔
263
            $collection = iterator_to_array($collection);
1✔
264
        }
265
        usort(/** @scrutinizer ignore-type */ $collection, $callback);
1✔
266

267
        return $collection;
1✔
268
    }
269

270
    /**
271
     * Sorts by creation date (or 'updated' date): the most recent first.
272
     */
273
    public function sortByDate(\Traversable $collection, string $variable = 'date', bool $descTitle = false): array
274
    {
275
        $callback = function ($a, $b) use ($variable, $descTitle) {
1✔
276
            if ($a[$variable] == $b[$variable]) {
1✔
277
                // if dates are equal and "descTitle" is true
278
                if ($descTitle && (isset($a['title']) && isset($b['title']))) {
1✔
279
                    return strnatcmp($b['title'], $a['title']);
×
280
                }
281

282
                return 0;
1✔
283
            }
284

285
            return $a[$variable] > $b[$variable] ? -1 : 1;
1✔
286
        };
1✔
287

288
        $collection = iterator_to_array($collection);
1✔
289
        usort(/** @scrutinizer ignore-type */ $collection, $callback);
1✔
290

291
        return $collection;
1✔
292
    }
293

294
    /**
295
     * Creates an URL.
296
     *
297
     * $options[
298
     *     'canonical' => false,
299
     *     'format'    => 'html',
300
     *     'language'  => null,
301
     * ];
302
     *
303
     * @param array                  $context
304
     * @param Page|Asset|string|null $value
305
     * @param array|null             $options
306
     */
307
    public function url(array $context, $value = null, ?array $options = null): string
308
    {
309
        $optionsLang = [];
1✔
310
        $optionsLang['language'] = (string) $context['site']['language'];
1✔
311
        $options = array_merge($optionsLang, $options ?? []);
1✔
312

313
        return (new Url($this->builder, $value, $options))->getUrl();
1✔
314
    }
315

316
    /**
317
     * Creates an Asset (CSS, JS, images, etc.) from a path or an array of paths.
318
     *
319
     * @param string|array $path    File path or array of files path (relative from `assets/` or `static/` dir).
320
     * @param array|null   $options
321
     *
322
     * @return Asset
323
     */
324
    public function asset($path, array|null $options = null): Asset
325
    {
326
        if (!\is_string($path) && !\is_array($path)) {
1✔
327
            throw new RuntimeException(\sprintf('Argument of "%s()" must a string or an array.', \Cecil\Util::formatMethodName(__METHOD__)));
×
328
        }
329

330
        return new Asset($this->builder, $path, $options);
1✔
331
    }
332

333
    /**
334
     * Compiles a SCSS asset.
335
     *
336
     * @param string|Asset $asset
337
     *
338
     * @return Asset
339
     */
340
    public function toCss($asset): Asset
341
    {
342
        if (!$asset instanceof Asset) {
1✔
343
            $asset = new Asset($this->builder, $asset);
×
344
        }
345

346
        return $asset->compile();
1✔
347
    }
348

349
    /**
350
     * Minifying an asset (CSS or JS).
351
     *
352
     * @param string|Asset $asset
353
     *
354
     * @return Asset
355
     */
356
    public function minify($asset): Asset
357
    {
358
        if (!$asset instanceof Asset) {
1✔
359
            $asset = new Asset($this->builder, $asset);
×
360
        }
361

362
        return $asset->minify();
1✔
363
    }
364

365
    /**
366
     * Fingerprinting an asset.
367
     *
368
     * @param string|Asset $asset
369
     *
370
     * @return Asset
371
     */
372
    public function fingerprint($asset): Asset
373
    {
374
        if (!$asset instanceof Asset) {
1✔
375
            $asset = new Asset($this->builder, $asset);
×
376
        }
377

378
        return $asset->fingerprint();
1✔
379
    }
380

381
    /**
382
     * Resizes an image Asset to the given width or/and height.
383
     *
384
     * - If only the width is specified, the height is calculated to preserve the aspect ratio
385
     * - If only the height is specified, the width is calculated to preserve the aspect ratio
386
     * - If both width and height are specified, the image is resized to fit within the given dimensions, image is cropped and centered if necessary
387
     * - If remove_animation is true, any animation in the image (e.g., GIF) will be removed.
388
     *
389
     * @param string|Asset $asset
390
     *
391
     * @return Asset
392
     */
393
    public function resize($asset, ?int $width = null, ?int $height = null, bool $remove_animation = false): Asset
394
    {
395
        if (!$asset instanceof Asset) {
1✔
396
            $asset = new Asset($this->builder, $asset);
×
397
        }
398

399
        return $asset->resize(width: $width, height: $height, rmAnimation: $remove_animation);
1✔
400
    }
401

402
    /**
403
     * Creates a maskable icon from an image asset.
404
     * The maskable icon is used for Progressive Web Apps (PWAs).
405
     *
406
     * @param string|Asset $asset
407
     *
408
     * @return Asset
409
     */
410
    public function maskable($asset, ?int $padding = null): Asset
411
    {
412
        if (!$asset instanceof Asset) {
×
413
            $asset = new Asset($this->builder, $asset);
×
414
        }
415

416
        return $asset->maskable($padding);
×
417
    }
418

419
    /**
420
     * Returns the data URL of an image.
421
     *
422
     * @param string|Asset $asset
423
     *
424
     * @return string
425
     */
426
    public function dataurl($asset): string
427
    {
428
        if (!$asset instanceof Asset) {
1✔
429
            $asset = new Asset($this->builder, $asset);
×
430
        }
431

432
        return $asset->dataurl();
1✔
433
    }
434

435
    /**
436
     * Hashing an asset with algo (sha384 by default).
437
     *
438
     * @param string|Asset $asset
439
     * @param string       $algo
440
     *
441
     * @return string
442
     */
443
    public function integrity($asset, string $algo = 'sha384'): string
444
    {
445
        if (!$asset instanceof Asset) {
1✔
446
            $asset = new Asset($this->builder, $asset);
1✔
447
        }
448

449
        return $asset->integrity($algo);
1✔
450
    }
451

452
    /**
453
     * Minifying a CSS string.
454
     */
455
    public function minifyCss(?string $value): string
456
    {
457
        $value = $value ?? '';
1✔
458

459
        if ($this->builder->isDebug()) {
1✔
460
            return $value;
1✔
461
        }
462

NEW
463
        $cache = $this->builder->getCache('assets');
×
464
        $cacheKey = $cache->createKeyFromValue(null, $value);
×
465
        if (!$cache->has($cacheKey)) {
×
466
            $minifier = new Minify\CSS($value);
×
467
            $value = $minifier->minify();
×
468
            $cache->set($cacheKey, $value, $this->config->get('cache.assets.ttl'));
×
469
        }
470

471
        return $cache->get($cacheKey, $value);
×
472
    }
473

474
    /**
475
     * Minifying a JavaScript string.
476
     */
477
    public function minifyJs(?string $value): string
478
    {
479
        $value = $value ?? '';
1✔
480

481
        if ($this->builder->isDebug()) {
1✔
482
            return $value;
1✔
483
        }
484

NEW
485
        $cache = $this->builder->getCache('assets');
×
486
        $cacheKey = $cache->createKeyFromValue(null, $value);
×
487
        if (!$cache->has($cacheKey)) {
×
488
            $minifier = new Minify\JS($value);
×
489
            $value = $minifier->minify();
×
490
            $cache->set($cacheKey, $value, $this->config->get('cache.assets.ttl'));
×
491
        }
492

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

496
    /**
497
     * Compiles a SCSS string.
498
     *
499
     * @throws RuntimeException
500
     */
501
    public function scssToCss(?string $value): string
502
    {
503
        $value = $value ?? '';
1✔
504

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

524
        return $cache->get($cacheKey, $value);
1✔
525
    }
526

527
    /**
528
     * Creates the HTML element of an asset.
529
     *
530
     * @param array                                                                $context    Twig context
531
     * @param Asset|array<int,array{asset:Asset,attributes:?array<string,string>}> $assets     Asset or array of assets + attributes
532
     * @param array                                                                $attributes HTML attributes to add to the element
533
     * @param array                                                                $options    Options:
534
     * [
535
     *     'preload'    => false,
536
     *     'responsive' => false,
537
     *     'formats'    => [],
538
     * ];
539
     *
540
     * @return string HTML element
541
     *
542
     * @throws RuntimeException
543
     */
544
    public function html(array $context, Asset|array $assets, array $attributes = [], array $options = []): string
545
    {
546
        $html = array();
1✔
547
        if (!\is_array($assets)) {
1✔
548
            $assets = [['asset' => $assets, 'attributes' => null]];
1✔
549
        }
550
        foreach ($assets as $assetData) {
1✔
551
            $asset = $assetData['asset'];
1✔
552
            if (!$asset instanceof Asset) {
1✔
553
                $asset = new Asset($this->builder, $asset);
×
554
            }
555
            // be sure Asset file is saved
556
            $asset->save();
1✔
557
            // merge attributes
558
            $attr = $attributes;
1✔
559
            if ($assetData['attributes'] !== null) {
1✔
560
                $attr = $attributes + $assetData['attributes'];
1✔
561
            }
562
            // process by extension
563
            $attributes['as'] = $asset['type'];
1✔
564
            switch ($asset['ext']) {
1✔
565
                case 'css':
1✔
566
                    $html[] = $this->htmlCss($context, $asset, $attr, $options);
1✔
567
                    $attributes['as'] = 'style';
1✔
568
                    unset($attributes['defer']);
1✔
569
                    break;
1✔
570
                case 'js':
1✔
571
                    $html[] = $this->htmlJs($context, $asset, $attr, $options);
1✔
572
                    $attributes['as'] = $asset['script'];
1✔
573
                    break;
1✔
574
            }
575
            // process by MIME type
576
            switch ($asset['type']) {
1✔
577
                case 'image':
1✔
578
                    $html[] = $this->htmlImage($context, $asset, $attr, $options);
1✔
579
                    break;
1✔
580
                case 'audio':
1✔
581
                    $html[] = $this->htmlAudio($context, $asset, $attr, $options);
1✔
582
                    break;
1✔
583
                case 'video':
1✔
584
                    $html[] = $this->htmlVideo($context, $asset, $attr, $options);
1✔
585
                    break;
1✔
586
            }
587
            // preload
588
            if ($options['preload'] ?? false) {
1✔
589
                $attributes['type'] = $asset['subtype'];
1✔
590
                if (empty($attributes['crossorigin'])) {
1✔
591
                    $attributes['crossorigin'] = 'anonymous';
1✔
592
                }
593
                array_unshift($html, \sprintf('<link rel="preload" href="%s"%s>', $this->url($context, $asset, $options), self::htmlAttributes($attributes)));
1✔
594
            }
595
            unset($attr);
1✔
596
        }
597
        if (empty($html)) {
1✔
598
            throw new RuntimeException(\sprintf('%s failed to generate HTML element(s) for file(s) provided.', '"html" function'));
×
599
        }
600

601
        return implode("\n    ", $html);
1✔
602
    }
603

604
    /**
605
     * Builds the HTML link element of a CSS Asset.
606
     */
607
    public function htmlCss(array $context, Asset $asset, array $attributes = [], array $options = []): string
608
    {
609
        // simulate "defer" by using "preload" and "onload"
610
        if (isset($attributes['defer'])) {
1✔
611
            unset($attributes['defer']);
×
612
            return \sprintf(
×
613
                '<link rel="preload" href="%s" as="style" onload="this.onload=null;this.rel=\'stylesheet\'"%s><noscript><link rel="stylesheet" href="%1$s"%2$s></noscript>',
×
614
                $this->url($context, $asset, $options),
×
615
                self::htmlAttributes($attributes)
×
616
            );
×
617
        }
618

619
        return \sprintf('<link rel="stylesheet" href="%s"%s>', $this->url($context, $asset, $options), self::htmlAttributes($attributes));
1✔
620
    }
621

622
    /**
623
     * Builds the HTML script element of a JS Asset.
624
     */
625
    public function htmlJs(array $context, Asset $asset, array $attributes = [], array $options = []): string
626
    {
627
        return \sprintf('<script src="%s"%s></script>', $this->url($context, $asset, $options), self::htmlAttributes($attributes));
1✔
628
    }
629

630
    /**
631
     * Builds the HTML img element of an image Asset.
632
     */
633
    public function htmlImage(array $context, Asset $asset, array $attributes = [], array $options = []): string
634
    {
635
        $responsive = $options['responsive'] ?? $this->config->get('layouts.images.responsive');
1✔
636

637
        // build responsive attributes
638
        try {
639
            if ($responsive === true || $responsive == 'width') {
1✔
640
                $srcset = Image::buildHtmlSrcsetW($asset, $this->config->getAssetsImagesWidths());
1✔
641
                if (!empty($srcset)) {
1✔
642
                    $attributes['srcset'] = $srcset;
1✔
643
                }
644
                $attributes['sizes'] = Image::getHtmlSizes($attributes['class'] ?? '', $this->config->getAssetsImagesSizes());
1✔
645
                // prevent oversized images
646
                if ($asset['width'] > max($this->config->getAssetsImagesWidths())) {
1✔
647
                    $asset = $asset->resize(max($this->config->getAssetsImagesWidths()));
×
648
                }
649
            } elseif ($responsive == 'density') {
1✔
650
                $width1x = isset($attributes['width']) && $attributes['width'] > 0 ? (int) $attributes['width'] : $asset['width'];
1✔
651
                $srcset = Image::buildHtmlSrcsetX($asset, $width1x, $this->config->getAssetsImagesDensities());
1✔
652
                if (!empty($srcset)) {
1✔
653
                    $attributes['srcset'] = $srcset;
1✔
654
                }
655
            }
656
        } catch (\Exception $e) {
×
657
            $this->builder->getLogger()->warning($e->getMessage());
×
658
        }
659

660
        // create alternative formats (`<source>`)
661
        try {
662
            $formats = $options['formats'] ?? (array) $this->config->get('layouts.images.formats');
1✔
663
            if (\count($formats) > 0) {
1✔
664
                $source = '';
1✔
665
                foreach ($formats as $format) {
1✔
666
                    try {
667
                        $assetConverted = $asset->convert($format);
1✔
668
                        // responsive
669
                        if ($responsive === true || $responsive == 'width') {
1✔
670
                            $srcset = Image::buildHtmlSrcsetW($assetConverted, $this->config->getAssetsImagesWidths());
1✔
671
                            if (empty($srcset)) {
1✔
672
                                $source .= \sprintf("\n  <source type=\"image/$format\" srcset=\"%s\">", (string) $assetConverted);
1✔
673
                                continue;
1✔
674
                            }
675
                            $source .= \sprintf("\n  <source type=\"image/$format\" srcset=\"%s\" sizes=\"%s\">", $srcset, Image::getHtmlSizes($attributes['class'] ?? '', $this->config->getAssetsImagesSizes()));
1✔
676
                            continue;
1✔
677
                        }
678
                        if ($responsive == 'density') {
1✔
679
                            $width1x = isset($attributes['width']) && $attributes['width'] > 0 ? (int) $attributes['width'] : $asset['width'];
1✔
680
                            $srcset = Image::buildHtmlSrcsetX($assetConverted, $width1x, $this->config->getAssetsImagesDensities());
1✔
681
                            if (empty($srcset)) {
1✔
682
                                $srcset = (string) $assetConverted;
×
683
                            }
684
                            $source .= \sprintf("\n  <source type=\"image/$format\" srcset=\"%s\">", $srcset);
1✔
685
                            continue;
1✔
686
                        }
687
                        $source .= \sprintf("\n  <source type=\"image/$format\" srcset=\"%s\">", $assetConverted);
1✔
688
                    } catch (\Exception $e) {
×
689
                        $this->builder->getLogger()->warning($e->getMessage());
×
690
                        continue;
×
691
                    }
692
                }
693
            }
694
        } catch (\Exception $e) {
×
695
            $this->builder->getLogger()->warning($e->getMessage());
×
696
        }
697

698
        // create `<img>` element
699
        if (!isset($attributes['alt'])) {
1✔
700
            $attributes['alt'] = '';
1✔
701
        }
702
        if (isset($attributes['width']) && $attributes['width'] > 0) {
1✔
703
            $asset = $asset->resize((int) $attributes['width']);
1✔
704
        }
705
        if (!isset($attributes['width'])) {
1✔
706
            $attributes['width'] = $asset['width'] ?: '';
1✔
707
        }
708
        if (!isset($attributes['height'])) {
1✔
709
            $attributes['height'] = $asset['height'] ?: '';
1✔
710
        }
711
        $img = \sprintf('<img src="%s"%s>', $this->url($context, $asset, $options), self::htmlAttributes($attributes));
1✔
712

713
        // put `<source>` elements in `<picture>` if exists
714
        if (!empty($source)) {
1✔
715
            return \sprintf("<picture>%s\n  %s\n</picture>", $source, $img);
1✔
716
        }
717

718
        return $img;
1✔
719
    }
720

721
    /**
722
     * Builds the HTML audio element of an audio Asset.
723
     */
724
    public function htmlAudio(array $context, Asset $asset, array $attributes = [], array $options = []): string
725
    {
726
        if (empty($attributes)) {
1✔
727
            $attributes['controls'] = '';
1✔
728
        }
729

730
        return \sprintf('<audio%s src="%s" type="%s"></audio>', self::htmlAttributes($attributes), $this->url($context, $asset, $options), $asset['subtype']);
1✔
731
    }
732

733
    /**
734
     * Builds the HTML video element of a video Asset.
735
     */
736
    public function htmlVideo(array $context, Asset $asset, array $attributes = [], array $options = []): string
737
    {
738
        if (empty($attributes)) {
1✔
739
            $attributes['controls'] = '';
1✔
740
        }
741

742
        return \sprintf('<video%s><source src="%s" type="%s"></video>', self::htmlAttributes($attributes), $this->url($context, $asset, $options), $asset['subtype']);
1✔
743
    }
744

745
    /**
746
     * Builds the HTML img `srcset` (responsive) attribute of an image Asset, based on configured widths.
747
     *
748
     * @throws RuntimeException
749
     */
750
    public function imageSrcset(Asset $asset): string
751
    {
752
        return Image::buildHtmlSrcsetW($asset, $this->config->getAssetsImagesWidths(), true);
1✔
753
    }
754

755
    /**
756
     * Returns the HTML img `sizes` attribute based on a CSS class name.
757
     */
758
    public function imageSizes(string $class): string
759
    {
760
        return Image::getHtmlSizes($class, $this->config->getAssetsImagesSizes());
1✔
761
    }
762

763
    /**
764
     * Builds the HTML img element from a website URL by extracting the image from meta tags.
765
     * Returns null if no image found.
766
     *
767
     * @todo enhance performance by caching results?
768
     *
769
     * @throws RuntimeException
770
     */
771
    public function htmlImageFromWebsite(array $context, string $url, array $attributes = [], array $options = []): ?string
772
    {
773
        if (false !== $html = Util\File::fileGetContents($url)) {
1✔
774
            $imageUrl = Util\Html::getImageFromMetaTags($html);
1✔
775
            if ($imageUrl !== null) {
1✔
776
                $asset = new Asset($this->builder, $imageUrl);
1✔
777

778
                return $this->htmlImage($context, $asset, $attributes, $options);
1✔
779
            }
780
        }
781

782
        return null;
1✔
783
    }
784

785
    /**
786
     * Converts an image Asset to WebP format.
787
     */
788
    public function webp(Asset $asset, ?int $quality = null): Asset
789
    {
790
        return $this->convert($asset, 'webp', $quality);
×
791
    }
792

793
    /**
794
     * Converts an image Asset to AVIF format.
795
     */
796
    public function avif(Asset $asset, ?int $quality = null): Asset
797
    {
798
        return $this->convert($asset, 'avif', $quality);
×
799
    }
800

801
    /**
802
     * Converts an image Asset to the given format.
803
     *
804
     * @throws RuntimeException
805
     */
806
    private function convert(Asset $asset, string $format, ?int $quality = null): Asset
807
    {
808
        if ($asset['subtype'] == "image/$format") {
×
809
            return $asset;
×
810
        }
811
        if (Image::isAnimatedGif($asset)) {
×
812
            throw new RuntimeException(\sprintf('Unable to convert the animated GIF "%s" to %s.', $asset['path'], $format));
×
813
        }
814

815
        try {
816
            return $asset->$format($quality);
×
817
        } catch (\Exception $e) {
×
818
            throw new RuntimeException(\sprintf('Unable to convert "%s" to %s (%s).', $asset['path'], $format, $e->getMessage()));
×
819
        }
820
    }
821

822
    /**
823
     * Returns the content of an asset.
824
     */
825
    public function inline(Asset $asset): string
826
    {
827
        return $asset['content'];
1✔
828
    }
829

830
    /**
831
     * Reads $length first characters of a string and adds a suffix.
832
     */
833
    public function excerpt(?string $string, int $length = 450, string $suffix = ' …'): string
834
    {
835
        $string = $string ?? '';
1✔
836

837
        $string = str_replace('</p>', '<br><br>', $string);
1✔
838
        $string = trim(strip_tags($string, '<br>'));
1✔
839
        if (mb_strlen($string) > $length) {
1✔
840
            $string = mb_substr($string, 0, $length);
1✔
841
            $string .= $suffix;
1✔
842
        }
843

844
        return $string;
1✔
845
    }
846

847
    /**
848
     * Reads characters before or after '<!-- separator -->'.
849
     * Options:
850
     *  - separator: string to use as separator (`excerpt|break` by default)
851
     *  - capture: part to capture, `before` or `after` the separator (`before` by default).
852
     */
853
    public function excerptHtml(?string $string, array $options = []): string
854
    {
855
        $string = $string ?? '';
1✔
856

857
        $separator = (string) $this->config->get('pages.body.excerpt.separator');
1✔
858
        $capture = (string) $this->config->get('pages.body.excerpt.capture');
1✔
859
        extract($options, EXTR_IF_EXISTS);
1✔
860

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

865
        if (empty($matches)) {
1✔
866
            return $string;
×
867
        }
868
        $result = trim($matches[1]);
1✔
869
        if ($capture == 'after') {
1✔
870
            $result = trim($matches[3]);
1✔
871
        }
872
        // removes footnotes and returns result
873
        return preg_replace('/<sup[^>]*>[^u]*<\/sup>/', '', $result);
1✔
874
    }
875

876
    /**
877
     * Converts a Markdown string to HTML.
878
     *
879
     * @throws RuntimeException
880
     */
881
    public function markdownToHtml(?string $markdown): ?string
882
    {
883
        $markdown = $markdown ?? '';
1✔
884

885
        try {
886
            $parsedown = new Parsedown($this->builder, $this->config);
1✔
887
            $html = $parsedown->text($markdown);
1✔
888
        } catch (\Exception $e) {
×
889
            throw new RuntimeException(
×
890
                '"markdown_to_html" filter can not convert supplied Markdown.',
×
891
                previous: $e
×
892
            );
×
893
        }
894

895
        return $html;
1✔
896
    }
897

898
    /**
899
     * Extracts only headings matching the given `selectors` (h2, h3, etc.),
900
     * or those defined in config `pages.body.toc` if not specified.
901
     * The `format` parameter defines the output format: `html` or `json`.
902
     * The `url` parameter is used to build links to headings.
903
     *
904
     * @throws RuntimeException
905
     */
906
    public function markdownToToc(?string $markdown, $format = 'html', ?array $selectors = null, string $url = ''): ?string
907
    {
908
        $markdown = $markdown ?? '';
1✔
909
        $selectors = $selectors ?? (array) $this->config->get('pages.body.toc');
1✔
910

911
        try {
912
            $parsedown = new Parsedown($this->builder, $this->config, ['selectors' => $selectors, 'url' => $url]);
1✔
913
            $parsedown->body($markdown);
1✔
914
            $return = $parsedown->contentsList($format);
1✔
915
        } catch (\Exception) {
×
916
            throw new RuntimeException('"toc" filter can not convert supplied Markdown.');
×
917
        }
918

919
        return $return;
1✔
920
    }
921

922
    /**
923
     * Converts a JSON string to an array.
924
     *
925
     * @throws RuntimeException
926
     */
927
    public function jsonDecode(?string $json): ?array
928
    {
929
        $json = $json ?? '';
1✔
930

931
        try {
932
            $array = json_decode($json, true);
1✔
933
            if ($array === null && json_last_error() !== JSON_ERROR_NONE) {
1✔
934
                throw new \Exception('JSON error.');
1✔
935
            }
936
        } catch (\Exception) {
×
937
            throw new RuntimeException('"json_decode" filter can not parse supplied JSON.');
×
938
        }
939

940
        return $array;
1✔
941
    }
942

943
    /**
944
     * Converts a YAML string to an array.
945
     *
946
     * @throws RuntimeException
947
     */
948
    public function yamlParse(?string $yaml): ?array
949
    {
950
        $yaml = $yaml ?? '';
1✔
951

952
        try {
953
            $array = Yaml::parse($yaml, Yaml::PARSE_DATETIME);
1✔
954
            if (!\is_array($array)) {
1✔
955
                throw new ParseException('YAML error.');
1✔
956
            }
957
        } catch (ParseException $e) {
×
958
            throw new RuntimeException(\sprintf('"yaml_parse" filter can not parse supplied YAML: %s', $e->getMessage()));
×
959
        }
960

961
        return $array;
1✔
962
    }
963

964
    /**
965
     * Split a string into an array using a regular expression.
966
     *
967
     * @throws RuntimeException
968
     */
969
    public function pregSplit(?string $value, string $pattern, int $limit = 0): ?array
970
    {
971
        $value = $value ?? '';
×
972

973
        try {
974
            $array = preg_split($pattern, $value, $limit);
×
975
            if ($array === false) {
×
976
                throw new RuntimeException('PREG split error.');
×
977
            }
978
        } catch (\Exception) {
×
979
            throw new RuntimeException('"preg_split" filter can not split supplied string.');
×
980
        }
981

982
        return $array;
×
983
    }
984

985
    /**
986
     * Perform a regular expression match and return the group for all matches.
987
     *
988
     * @throws RuntimeException
989
     */
990
    public function pregMatchAll(?string $value, string $pattern, int $group = 0): ?array
991
    {
992
        $value = $value ?? '';
×
993

994
        try {
995
            $array = preg_match_all($pattern, $value, $matches, PREG_PATTERN_ORDER);
×
996
            if ($array === false) {
×
997
                throw new RuntimeException('PREG match all error.');
×
998
            }
999
        } catch (\Exception) {
×
1000
            throw new RuntimeException('"preg_match_all" filter can not match in supplied string.');
×
1001
        }
1002

1003
        return $matches[$group];
×
1004
    }
1005

1006
    /**
1007
     * Calculates estimated time to read a text.
1008
     */
1009
    public function readtime(?string $text): string
1010
    {
1011
        $text = $text ?? '';
1✔
1012

1013
        $words = str_word_count(strip_tags($text));
1✔
1014
        $min = floor($words / 200);
1✔
1015
        if ($min === 0) {
1✔
1016
            return '1';
×
1017
        }
1018

1019
        return (string) $min;
1✔
1020
    }
1021

1022
    /**
1023
     * Gets the value of an environment variable.
1024
     */
1025
    public function getEnv(?string $var): ?string
1026
    {
1027
        $var = $var ?? '';
1✔
1028

1029
        return getenv($var) ?: null;
1✔
1030
    }
1031

1032
    /**
1033
     * Dump variable (or Twig context).
1034
     */
1035
    public function varDump(\Twig\Environment $env, array $context, $var = null, ?array $options = null): void
1036
    {
1037
        if (!$env->isDebug()) {
1✔
1038
            return;
×
1039
        }
1040

1041
        if ($var === null) {
1✔
1042
            $var = array();
×
1043
            foreach ($context as $key => $value) {
×
1044
                if (!$value instanceof \Twig\Template && !$value instanceof \Twig\TemplateWrapper) {
×
1045
                    $var[$key] = $value;
×
1046
                }
1047
            }
1048
        }
1049

1050
        $cloner = new VarCloner();
1✔
1051
        $cloner->setMinDepth(3);
1✔
1052
        $dumper = new HtmlDumper();
1✔
1053
        $dumper->setTheme($options['theme'] ?? 'light');
1✔
1054

1055
        $data = $cloner->cloneVar($var)->withMaxDepth(3);
1✔
1056
        $dumper->dump($data, null, ['maxDepth' => 3]);
1✔
1057
    }
1058

1059
    /**
1060
     * Tests if a variable is an Asset.
1061
     */
1062
    public function isAsset($variable): bool
1063
    {
1064
        return $variable instanceof Asset;
1✔
1065
    }
1066

1067
    /**
1068
     * Tests if an image Asset is large enough to be used as a cover image.
1069
     * A large image is defined as having a width >= 600px and height >= 315px.
1070
     */
1071
    public function isImageLarge(Asset $asset): bool
1072
    {
1073
        return $asset['type'] == 'image' && $asset['width'] > $asset['height'] && $asset['width'] >= 600 && $asset['height'] >= 315;
1✔
1074
    }
1075

1076
    /**
1077
     * Tests if an image Asset is square.
1078
     * A square image is defined as having the same width and height.
1079
     */
1080
    public function isImageSquare(Asset $asset): bool
1081
    {
1082
        return $asset['type'] == 'image' && $asset['width'] == $asset['height'];
1✔
1083
    }
1084

1085
    /**
1086
     * Returns the dominant hex color of an image asset.
1087
     *
1088
     * @param string|Asset $asset
1089
     *
1090
     * @return string
1091
     */
1092
    public function dominantColor($asset): string
1093
    {
1094
        if (!$asset instanceof Asset) {
1✔
1095
            $asset = new Asset($this->builder, $asset);
×
1096
        }
1097

1098
        return Image::getDominantColor($asset);
1✔
1099
    }
1100

1101
    /**
1102
     * Returns a Low Quality Image Placeholder (LQIP) as data URL.
1103
     *
1104
     * @param string|Asset $asset
1105
     *
1106
     * @return string
1107
     */
1108
    public function lqip($asset): string
1109
    {
1110
        if (!$asset instanceof Asset) {
1✔
1111
            $asset = new Asset($this->builder, $asset);
×
1112
        }
1113

1114
        return Image::getLqip($asset);
1✔
1115
    }
1116

1117
    /**
1118
     * Converts an hexadecimal color to RGB.
1119
     *
1120
     * @throws RuntimeException
1121
     */
1122
    public function hexToRgb(?string $variable): array
1123
    {
1124
        $variable = $variable ?? '';
1✔
1125

1126
        if (!self::isHex($variable)) {
1✔
1127
            throw new RuntimeException(\sprintf('"%s" is not a valid hexadecimal value.', $variable));
×
1128
        }
1129
        $hex = ltrim($variable, '#');
1✔
1130
        if (\strlen($hex) == 3) {
1✔
1131
            $hex = $hex[0] . $hex[0] . $hex[1] . $hex[1] . $hex[2] . $hex[2];
×
1132
        }
1133
        $c = hexdec($hex);
1✔
1134

1135
        return [
1✔
1136
            'red'   => $c >> 16 & 0xFF,
1✔
1137
            'green' => $c >> 8 & 0xFF,
1✔
1138
            'blue'  => $c & 0xFF,
1✔
1139
        ];
1✔
1140
    }
1141

1142
    /**
1143
     * Split a string in multiple lines.
1144
     */
1145
    public function splitLine(?string $variable, int $max = 18): array
1146
    {
1147
        $variable = $variable ?? '';
1✔
1148

1149
        return preg_split("/.{0,{$max}}\K(\s+|$)/", $variable, 0, PREG_SPLIT_NO_EMPTY);
1✔
1150
    }
1151

1152
    /**
1153
     * Hashing an object, an array or a string (with algo, md5 by default).
1154
     */
1155
    public function hash(object|array|string $data, $algo = 'md5'): string
1156
    {
1157
        switch (\gettype($data)) {
1✔
1158
            case 'object':
1✔
1159
                return spl_object_hash($data);
1✔
1160
            case 'array':
×
1161
                return hash($algo, serialize($data));
×
1162
        }
1163

1164
        return hash($algo, $data);
×
1165
    }
1166

1167
    /**
1168
     * Converts a variable to an iterable (array).
1169
     */
1170
    public function iterable($value): array
1171
    {
1172
        if (\is_array($value)) {
1✔
1173
            return $value;
1✔
1174
        }
1175
        if (\is_string($value)) {
×
1176
            return [$value];
×
1177
        }
1178
        if ($value instanceof \Traversable) {
×
1179
            return iterator_to_array($value);
×
1180
        }
1181
        if ($value instanceof \stdClass) {
×
1182
            return (array) $value;
×
1183
        }
1184
        if (\is_object($value)) {
×
1185
            return [$value];
×
1186
        }
1187
        if (\is_int($value) || \is_float($value)) {
×
1188
            return [$value];
×
1189
        }
1190
        return [$value];
×
1191
    }
1192

1193
    /**
1194
     * Highlights a code snippet.
1195
     */
1196
    public function highlight(string $code, string $language): string
1197
    {
1198
        return (new Highlighter())->highlight($language, $code)->value;
×
1199
    }
1200

1201
    /**
1202
     * Returns an array with unique values.
1203
     */
1204
    public function unique(array $array): array
1205
    {
1206
        return array_intersect_key($array, array_unique(array_map('strtolower', $array), SORT_STRING));
1✔
1207
    }
1208

1209
    /**
1210
     * Is a hexadecimal color is valid?
1211
     */
1212
    private static function isHex(string $hex): bool
1213
    {
1214
        $valid = \is_string($hex);
1✔
1215
        $hex = ltrim($hex, '#');
1✔
1216
        $length = \strlen($hex);
1✔
1217
        $valid = $valid && ($length === 3 || $length === 6);
1✔
1218
        $valid = $valid && ctype_xdigit($hex);
1✔
1219

1220
        return $valid;
1✔
1221
    }
1222

1223
    /**
1224
     * Builds the HTML attributes string from an array.
1225
     */
1226
    private static function htmlAttributes(array $attributes): string
1227
    {
1228
        $htmlAttributes = '';
1✔
1229
        foreach ($attributes as $name => $value) {
1✔
1230
            $attribute = \sprintf(' %s="%s"', $name, $value);
1✔
1231
            if (empty($value)) {
1✔
1232
                $attribute = \sprintf(' %s', $name);
1✔
1233
            }
1234
            $htmlAttributes .= $attribute;
1✔
1235
        }
1236

1237
        return $htmlAttributes;
1✔
1238
    }
1239
}
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