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

Cecilapp / Cecil / 26377409135

25 May 2026 12:41AM UTC coverage: 81.588%. First build
26377409135

Pull #2377

github

web-flow
Merge 28db52086 into c413588cf
Pull Request #2377: feat: add dark-mode image variant support

78 of 137 new or added lines in 2 files covered. (56.93%)

3483 of 4269 relevant lines covered (81.59%)

0.82 hits per line

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

72.91
/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 Highlight\Highlighter;
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
use Twig\Extension\AbstractExtension;
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 AbstractExtension
48
{
49
    /** @var Builder */
50
    protected $builder;
51

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

55
    public function __construct(Builder $builder)
56
    {
57
        $this->builder = $builder;
1✔
58
        $this->config = $builder->getConfig();
1✔
59
    }
60

61
    public function getFunctions()
62
    {
63
        return [
1✔
64
            new \Twig\TwigFunction('url', [$this, 'url'], ['needs_context' => true]),
1✔
65
            // assets
66
            new \Twig\TwigFunction('asset', [$this, 'asset']),
1✔
67
            new \Twig\TwigFunction('integrity', [$this, 'integrity']),
1✔
68
            new \Twig\TwigFunction('html', [$this, 'html'], ['needs_context' => true]),
1✔
69
            new \Twig\TwigFunction('css', [$this, 'htmlCss'], ['needs_context' => true]),
1✔
70
            new \Twig\TwigFunction('js', [$this, 'htmlJs'], ['needs_context' => true]),
1✔
71
            new \Twig\TwigFunction('image', [$this, 'htmlImage'], ['needs_context' => true]),
1✔
72
            new \Twig\TwigFunction('audio', [$this, 'htmlAudio'], ['needs_context' => true]),
1✔
73
            new \Twig\TwigFunction('video', [$this, 'htmlVideo'], ['needs_context' => true]),
1✔
74
            new \Twig\TwigFunction('image_srcset', [$this, 'imageSrcset']),
1✔
75
            new \Twig\TwigFunction('image_sizes', [$this, 'imageSizes']),
1✔
76
            new \Twig\TwigFunction('image_from_website', [$this, 'htmlImageFromWebsite'], ['needs_context' => true]),
1✔
77
            // content
78
            new \Twig\TwigFunction('readtime', [$this, 'readtime']),
1✔
79
            new \Twig\TwigFunction('hash', [$this, 'hash']),
1✔
80
            new \Twig\TwigFunction('cache_key', [$this, 'cacheKey'], ['needs_context' => true]),
1✔
81
            // others
82
            new \Twig\TwigFunction('getenv', [$this, 'getEnv']),
1✔
83
            new \Twig\TwigFunction('d', [$this, 'varDump'], ['needs_context' => true, 'needs_environment' => true]),
1✔
84
            // deprecated
85
            new \Twig\TwigFunction(
1✔
86
                'minify',
1✔
87
                [$this, 'minify'],
1✔
88
                ['deprecation_info' => new DeprecatedCallableInfo('', '', 'minify filter')]
1✔
89
            ),
1✔
90
            new \Twig\TwigFunction(
1✔
91
                'toCSS',
1✔
92
                [$this, 'toCss'],
1✔
93
                ['deprecation_info' => new DeprecatedCallableInfo('', '', 'to_css filter')]
1✔
94
            ),
1✔
95
            new \Twig\TwigFunction(
1✔
96
                'image_from_url',
1✔
97
                [$this, 'htmlImageFromWebsite'],
1✔
98
                ['deprecation_info' => new DeprecatedCallableInfo('', '', 'image_from_website function')]
1✔
99
            ),
1✔
100
        ];
1✔
101
    }
102

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

165
    public function getTests()
166
    {
167
        return [
1✔
168
            new \Twig\TwigTest('asset', [$this, 'isAsset']),
1✔
169
            new \Twig\TwigTest('image_large', [$this, 'isImageLarge']),
1✔
170
            new \Twig\TwigTest('image_square', [$this, 'isImageSquare']),
1✔
171
        ];
1✔
172
    }
173

174
    public function slugifyFilter(string $string): string
175
    {
176
        return Page::slugify($string);
×
177
    }
178

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

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

204
        return $filteredPages;
1✔
205
    }
206

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

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

217
        return $collection;
1✔
218
    }
219

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

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

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

246
        return $collection;
1✔
247
    }
248

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

261
                return 0;
1✔
262
            }
263

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

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

270
        return $collection;
1✔
271
    }
272

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

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

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

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

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

325
        return $asset->compile();
1✔
326
    }
327

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

341
        return $asset->minify();
1✔
342
    }
343

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

357
        return $asset->fingerprint();
1✔
358
    }
359

360
    /**
361
     * Resizes an image Asset to the given width or/and height.
362
     *
363
     * - If only the width is specified, the height is calculated to preserve the aspect ratio
364
     * - If only the height is specified, the width is calculated to preserve the aspect ratio
365
     * - If both width and height are specified, the image is resized to fit within the given dimensions, image is cropped and centered if necessary
366
     * - If remove_animation is true, any animation in the image (e.g., GIF) will be removed.
367
     *
368
     * @param string|Asset $asset
369
     *
370
     * @return Asset
371
     */
372
    public function resize($asset, ?int $width = null, ?int $height = null, bool $remove_animation = false): Asset
373
    {
374
        if (!$asset instanceof Asset) {
1✔
375
            $asset = new Asset($this->builder, $asset);
×
376
        }
377

378
        return $asset->resize(width: $width, height: $height, rmAnimation: $remove_animation);
1✔
379
    }
380

381
    /**
382
     * Creates a maskable icon from an image asset.
383
     * The maskable icon is used for Progressive Web Apps (PWAs).
384
     *
385
     * @param string|Asset $asset
386
     *
387
     * @return Asset
388
     */
389
    public function maskable($asset, ?int $padding = null): Asset
390
    {
391
        if (!$asset instanceof Asset) {
×
392
            $asset = new Asset($this->builder, $asset);
×
393
        }
394

395
        return $asset->maskable($padding);
×
396
    }
397

398
    /**
399
     * Returns the data URL of an image.
400
     *
401
     * @param string|Asset $asset
402
     *
403
     * @return string
404
     */
405
    public function dataurl($asset): string
406
    {
407
        if (!$asset instanceof Asset) {
1✔
408
            $asset = new Asset($this->builder, $asset);
×
409
        }
410

411
        return $asset->dataurl();
1✔
412
    }
413

414
    /**
415
     * Hashing an asset with algo (sha384 by default).
416
     *
417
     * @param string|Asset $asset
418
     * @param string       $algo
419
     *
420
     * @return string
421
     */
422
    public function integrity($asset, string $algo = 'sha384'): string
423
    {
424
        if (!$asset instanceof Asset) {
1✔
425
            $asset = new Asset($this->builder, $asset);
1✔
426
        }
427

428
        return $asset->integrity($algo);
1✔
429
    }
430

431
    /**
432
     * Minifying a CSS string.
433
     */
434
    public function minifyCss(?string $value): string
435
    {
436
        $value = $value ?? '';
1✔
437

438
        if ($this->builder->isDebug()) {
1✔
439
            return $value;
1✔
440
        }
441

442
        $cache = new Cache($this->builder, 'assets');
×
443
        $cacheKey = $cache->createKey($value, name: 'css');
×
444
        if (!$cache->has($cacheKey)) {
×
445
            $minifier = new Minify\CSS($value);
×
446
            $value = $minifier->minify();
×
447
            $cache->set($cacheKey, $value, $this->config->get('cache.assets.ttl'));
×
448
        }
449

450
        return $cache->get($cacheKey, $value);
×
451
    }
452

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

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

464
        $cache = new Cache($this->builder, 'assets');
×
465
        $cacheKey = $cache->createKey($value, name: 'js');
×
466
        if (!$cache->has($cacheKey)) {
×
467
            $minifier = new Minify\JS($value);
×
468
            $value = $minifier->minify();
×
469
            $cache->set($cacheKey, $value, $this->config->get('cache.assets.ttl'));
×
470
        }
471

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

475
    /**
476
     * Compiles a SCSS string.
477
     *
478
     * @throws RuntimeException
479
     */
480
    public function scssToCss(?string $value): string
481
    {
482
        $value = $value ?? '';
1✔
483

484
        $cache = new Cache($this->builder, 'assets');
1✔
485
        $cacheKey = $cache->createKey($value, name: 'css');
1✔
486
        if (!$cache->has($cacheKey)) {
1✔
487
            $scssPhp = new Compiler();
1✔
488
            $outputStyles = ['expanded', 'compressed'];
1✔
489
            $outputStyle = strtolower((string) $this->config->get('assets.compile.style'));
1✔
490
            if (!\in_array($outputStyle, $outputStyles)) {
1✔
491
                throw new ConfigException(\sprintf('"%s" value must be "%s".', 'assets.compile.style', implode('" or "', $outputStyles)));
×
492
            }
493
            $scssPhp->setOutputStyle($outputStyle == 'compressed' ? OutputStyle::COMPRESSED : OutputStyle::EXPANDED);
1✔
494
            $variables = $this->config->get('assets.compile.variables');
1✔
495
            if (!empty($variables)) {
1✔
496
                $variables = array_map('ScssPhp\ScssPhp\ValueConverter::parseValue', $variables);
1✔
497
                $scssPhp->replaceVariables($variables);
1✔
498
            }
499
            $value = $scssPhp->compileString($value)->getCss();
1✔
500
            $cache->set($cacheKey, $value, $this->config->get('cache.assets.ttl'));
1✔
501
        }
502

503
        return $cache->get($cacheKey, $value);
1✔
504
    }
505

506
    /**
507
     * Creates the HTML element of an asset.
508
     *
509
     * @param array                                                                $context    Twig context
510
     * @param Asset|array<int,array{asset:Asset,attributes:?array<string,string>}> $assets     Asset or array of assets + attributes
511
     * @param array                                                                $attributes HTML attributes to add to the element
512
     * @param array                                                                $options    Options:
513
     * [
514
     *     'preload'    => false,
515
     *     'responsive' => false,
516
     *     'formats'    => [],
517
     * ];
518
     *
519
     * @return string HTML element
520
     *
521
     * @throws RuntimeException
522
     */
523
    public function html(array $context, Asset|array $assets, array $attributes = [], array $options = []): string
524
    {
525
        $html = array();
1✔
526
        if (!\is_array($assets)) {
1✔
527
            $assets = [['asset' => $assets, 'attributes' => null]];
1✔
528
        }
529
        foreach ($assets as $assetData) {
1✔
530
            $asset = $assetData['asset'];
1✔
531
            if (!$asset instanceof Asset) {
1✔
532
                $asset = new Asset($this->builder, $asset);
×
533
            }
534
            $asset->save(); // be sure Asset file is saved
1✔
535
            // merge attributes
536
            $attr = $attributes;
1✔
537
            if ($assetData['attributes'] !== null) {
1✔
538
                $attr = $attributes + $assetData['attributes'];
1✔
539
            }
540
            // process by extension
541
            $attributes['as'] = $asset['type'];
1✔
542
            switch ($asset['ext']) {
1✔
543
                case 'css':
1✔
544
                    $html[] = $this->htmlCss($context, $asset, $attr, $options);
1✔
545
                    $attributes['as'] = 'style';
1✔
546
                    unset($attributes['defer']);
1✔
547
                    break;
1✔
548
                case 'js':
1✔
549
                    $html[] = $this->htmlJs($context, $asset, $attr, $options);
1✔
550
                    $attributes['as'] = $asset['script'];
1✔
551
                    break;
1✔
552
            }
553
            // preload
554
            if ($options['preload'] ?? false) {
1✔
555
                $attributes['type'] = $asset['subtype'];
1✔
556
                if (empty($attributes['crossorigin'])) {
1✔
557
                    $attributes['crossorigin'] = 'anonymous';
1✔
558
                }
559
                $preloadLink = \sprintf('<link rel="preload" href="%s"%s>', $this->url($context, $asset, $options), self::htmlAttributes($attributes));
1✔
560
                // if image asset with a specified width, preload the right size
561
                if (null !== $width = isset($attributes['width']) && $attributes['width'] > 0 ? (int) $attributes['width'] : null) {
1✔
562
                    $preloadLink = \sprintf('<link rel="preload" href="%s"%s>', $this->url($context, $asset->resize($width), $options), self::htmlAttributes($attributes));
×
563
                }
564
                array_unshift($html, $preloadLink);
1✔
565
                // only CSS and JS can be preloaded this way
566
                if (!\in_array($asset['ext'], ['css', 'js'])) {
1✔
567
                    break;
×
568
                }
569
            }
570
            // process by MIME type
571
            switch ($asset['type']) {
1✔
572
                case 'image':
1✔
573
                    $html[] = $this->htmlImage($context, $asset, $attr, $options);
1✔
574
                    break;
1✔
575
                case 'audio':
1✔
576
                    $html[] = $this->htmlAudio($context, $asset, $attr, $options);
1✔
577
                    break;
1✔
578
                case 'video':
1✔
579
                    $html[] = $this->htmlVideo($context, $asset, $attr, $options);
1✔
580
                    break;
1✔
581
            }
582
            unset($attr);
1✔
583
        }
584
        if (empty($html)) {
1✔
585
            throw new RuntimeException(\sprintf('%s failed to generate HTML element(s) for file(s) provided.', '"html" function'));
×
586
        }
587

588
        return implode("\n    ", $html);
1✔
589
    }
590

591
    /**
592
     * Builds the HTML link element of a CSS Asset.
593
     */
594
    public function htmlCss(array $context, Asset $asset, array $attributes = [], array $options = []): string
595
    {
596
        // simulate "defer" by using "preload" and "onload"
597
        if (isset($attributes['defer'])) {
1✔
598
            unset($attributes['defer']);
×
599
            return \sprintf(
×
600
                '<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>',
×
601
                $this->url($context, $asset, $options),
×
602
                self::htmlAttributes($attributes)
×
603
            );
×
604
        }
605

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

609
    /**
610
     * Builds the HTML script element of a JS Asset.
611
     */
612
    public function htmlJs(array $context, Asset $asset, array $attributes = [], array $options = []): string
613
    {
614
        return \sprintf('<script src="%s"%s></script>', $this->url($context, $asset, $options), self::htmlAttributes($attributes));
1✔
615
    }
616

617
    /**
618
     * Builds the HTML img element of an image Asset.
619
     */
620
    public function htmlImage(array $context, Asset $asset, array $attributes = [], array $options = []): string
621
    {
622
        $responsive = $options['responsive'] ?? $this->config->get('layouts.images.responsive');
1✔
623
        $source = '';
1✔
624
        // build responsive attributes
625
        try {
626
            if ($responsive === true || $responsive == 'width') {
1✔
627
                $srcset = Image::buildHtmlSrcsetW($asset, $this->config->getAssetsImagesWidths());
1✔
628
                if (!empty($srcset)) {
1✔
629
                    $attributes['srcset'] = $srcset;
1✔
630
                }
631
                $attributes['sizes'] = Image::getHtmlSizes($attributes['class'] ?? '', $this->config->getAssetsImagesSizes());
1✔
632
                // prevent oversized images
633
                if ($asset['width'] > max($this->config->getAssetsImagesWidths())) {
1✔
634
                    $asset = $asset->resize(max($this->config->getAssetsImagesWidths()));
×
635
                }
636
            } elseif ($responsive == 'density') {
1✔
637
                $width1x = isset($attributes['width']) && $attributes['width'] > 0 ? (int) $attributes['width'] : $asset['width'];
1✔
638
                $srcset = Image::buildHtmlSrcsetX($asset, $width1x, $this->config->getAssetsImagesDensities());
1✔
639
                if (!empty($srcset)) {
1✔
640
                    $attributes['srcset'] = $srcset;
1✔
641
                }
642
            }
643
        } catch (\Exception $e) {
×
644
            $this->builder->getLogger()->warning($e->getMessage());
×
645
        }
646

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

685
        // create `<img>` element
686
        if (!isset($attributes['alt'])) {
1✔
687
            $attributes['alt'] = '';
1✔
688
        }
689
        if (isset($attributes['width']) && $attributes['width'] > 0) {
1✔
690
            $asset = $asset->resize((int) $attributes['width']);
1✔
691
        }
692
        if (!isset($attributes['width'])) {
1✔
693
            $attributes['width'] = $asset['width'] ?: '';
1✔
694
        }
695
        if (!isset($attributes['height'])) {
1✔
696
            $attributes['height'] = $asset['height'] ?: '';
1✔
697
        }
698
        $img = \sprintf('<img src="%s"%s>', $this->url($context, $asset, $options), self::htmlAttributes($attributes));
1✔
699

700

701
        // dark color-scheme variant: auto-detect `{filename}{suffix}.{ext}` alongside the source image
702
        $darkSource = $this->buildDarkSourceHtml($asset, $formats, $responsive, $attributes);
1✔
703

704
        // put `<source>` elements in `<picture>` if exists
705
        if (!empty($darkSource) || !empty($source)) {
1✔
706
            return \sprintf("<picture>%s%s\n  %s\n</picture>", $darkSource, $source, $img);
1✔
707
        }
708

709
        return $img;
1✔
710
    }
711

712
    /**
713
     * Builds the HTML audio element of an audio Asset.
714
     */
715
    public function htmlAudio(array $context, Asset $asset, array $attributes = [], array $options = []): string
716
    {
717
        if (empty($attributes)) {
1✔
718
            $attributes['controls'] = '';
1✔
719
        }
720

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

724
    /**
725
     * Builds HTML dark "source" elements for the dark color-scheme variant of an image Asset.
726
     *
727
     * @param array $formats    Alternative formats (e.g. ['avif', 'webp'])
728
     * @param mixed $responsive Responsive mode (true, 'width', 'density' or false)
729
     * @param array $attributes Image attributes
730
     */
731
    private function buildDarkSourceHtml(Asset $asset, array $formats, mixed $responsive, array $attributes): string
732
    {
733
        $darkSuffix = (string) $this->config->get('layouts.images.dark_suffix');
1✔
734
        if (empty($darkSuffix)) {
1✔
NEW
735
            return '';
×
736
        }
737
        $pathInfo = pathinfo($asset['path']);
1✔
738
        $extension = empty($pathInfo['extension']) ? '' : '.' . $pathInfo['extension'];
1✔
739
        $darkAssetPath = rtrim($pathInfo['dirname'], '/') . '/' . $pathInfo['filename'] . $darkSuffix . $extension;
1✔
740
        $assetDark = new Asset($this->builder, $darkAssetPath, ['ignore_missing' => true]);
1✔
741
        if ($assetDark->isMissing()) {
1✔
742
            $this->builder->getLogger()->warning(\sprintf(
1✔
743
                'Dark variant "%s" not found for image "%s".',
1✔
744
                $darkAssetPath,
1✔
745
                $asset['path']
1✔
746
            ));
1✔
747

748
            return '';
1✔
749
        }
750
        $darkSource = '';
1✔
751
        foreach ($formats as $format) {
1✔
752
            try {
753
                $assetDarkConverted = $assetDark->convert($format);
1✔
754
                if ($responsive === true || $responsive == 'width') {
1✔
755
                    $darkSrcset = Image::buildHtmlSrcsetW($assetDarkConverted, $this->config->getAssetsImagesWidths());
1✔
756
                    if (empty($darkSrcset)) {
1✔
757
                        $darkSource .= \sprintf(
1✔
758
                            "\n  <source media=\"(prefers-color-scheme: dark)\" type=\"image/%s\" srcset=\"%s\">",
1✔
759
                            $format,
1✔
760
                            (string) $assetDarkConverted
1✔
761
                        );
1✔
762
                        continue;
1✔
763
                    }
NEW
764
                    $darkSource .= \sprintf(
×
NEW
765
                        "\n  <source media=\"(prefers-color-scheme: dark)\" type=\"image/%s\" srcset=\"%s\" sizes=\"%s\">",
×
NEW
766
                        $format,
×
NEW
767
                        $darkSrcset,
×
NEW
768
                        Image::getHtmlSizes($attributes['class'] ?? '', $this->config->getAssetsImagesSizes())
×
NEW
769
                    );
×
NEW
770
                    continue;
×
771
                }
NEW
772
                if ($responsive == 'density') {
×
NEW
773
                    $width1x = isset($attributes['width']) && $attributes['width'] > 0 ? (int) $attributes['width'] : $assetDark['width'];
×
NEW
774
                    $darkSrcset = Image::buildHtmlSrcsetX($assetDarkConverted, $width1x, $this->config->getAssetsImagesDensities());
×
NEW
775
                    $darkSource .= \sprintf(
×
NEW
776
                        "\n  <source media=\"(prefers-color-scheme: dark)\" type=\"image/%s\" srcset=\"%s\">",
×
NEW
777
                        $format,
×
NEW
778
                        empty($darkSrcset) ? (string) $assetDarkConverted : $darkSrcset
×
NEW
779
                    );
×
NEW
780
                    continue;
×
781
                }
NEW
782
                $darkSource .= \sprintf(
×
NEW
783
                    "\n  <source media=\"(prefers-color-scheme: dark)\" type=\"image/%s\" srcset=\"%s\">",
×
NEW
784
                    $format,
×
NEW
785
                    (string) $assetDarkConverted
×
NEW
786
                );
×
NEW
787
            } catch (\Exception $e) {
×
NEW
788
                $this->builder->getLogger()->warning($e->getMessage());
×
789
            }
790
        }
791
        if ($responsive === true || $responsive == 'width') {
1✔
792
            try {
793
                $darkFallbackSrcset = Image::buildHtmlSrcsetW($assetDark, $this->config->getAssetsImagesWidths());
1✔
794
                if (!empty($darkFallbackSrcset)) {
1✔
NEW
795
                    $darkSource .= \sprintf(
×
NEW
796
                        "\n  <source media=\"(prefers-color-scheme: dark)\" srcset=\"%s\" sizes=\"%s\">",
×
NEW
797
                        $darkFallbackSrcset,
×
NEW
798
                        Image::getHtmlSizes($attributes['class'] ?? '', $this->config->getAssetsImagesSizes())
×
NEW
799
                    );
×
800
                } else {
801
                    $darkSource .= \sprintf(
1✔
802
                        "\n  <source media=\"(prefers-color-scheme: dark)\" srcset=\"%s\">",
1✔
803
                        (string) $assetDark
1✔
804
                    );
1✔
805
                }
NEW
806
            } catch (\Exception $e) {
×
NEW
807
                $this->builder->getLogger()->warning($e->getMessage());
×
NEW
808
                $darkSource .= \sprintf(
×
NEW
809
                    "\n  <source media=\"(prefers-color-scheme: dark)\" srcset=\"%s\">",
×
NEW
810
                    (string) $assetDark
×
NEW
811
                );
×
812
            }
813
        } else {
NEW
814
            $darkSource .= \sprintf(
×
NEW
815
                "\n  <source media=\"(prefers-color-scheme: dark)\" srcset=\"%s\">",
×
NEW
816
                (string) $assetDark
×
NEW
817
            );
×
818
        }
819

820
        return $darkSource;
1✔
821
    }
822

823
    /**
824
     * Builds the HTML video element of a video Asset.
825
     */
826
    public function htmlVideo(array $context, Asset $asset, array $attributes = [], array $options = []): string
827
    {
828
        if (empty($attributes)) {
1✔
829
            $attributes['controls'] = '';
1✔
830
        }
831

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

835
    /**
836
     * Builds the HTML img `srcset` (responsive) attribute of an image Asset, based on configured widths.
837
     *
838
     * @throws RuntimeException
839
     */
840
    public function imageSrcset(Asset $asset): string
841
    {
842
        return Image::buildHtmlSrcsetW($asset, $this->config->getAssetsImagesWidths(), true);
1✔
843
    }
844

845
    /**
846
     * Returns the HTML img `sizes` attribute based on a CSS class name.
847
     */
848
    public function imageSizes(string $class): string
849
    {
850
        return Image::getHtmlSizes($class, $this->config->getAssetsImagesSizes());
1✔
851
    }
852

853
    /**
854
     * Builds the HTML img element from a website URL by extracting the image from meta tags.
855
     * Returns null if no image found.
856
     *
857
     * @throws RuntimeException
858
     */
859
    public function htmlImageFromWebsite(array $context, string $url, array $attributes = [], array $options = []): ?string
860
    {
861
        $htmlAsset = new Asset($this->builder, $url, ['ignore_missing' => true]);
1✔
862

863
        if ($htmlAsset->isMissing()) {
1✔
864
            $this->builder->getLogger()->warning(\sprintf('Unable to fetch "%s" to extract image.', $url));
×
865

866
            return null;
×
867
        }
868

869
        if (!empty($html = $htmlAsset['content'])) {
1✔
870
            $imageUrl = Util\Html::getImageFromMetaTags($html);
1✔
871
            if ($imageUrl !== null) {
1✔
872
                $asset = new Asset($this->builder, $imageUrl);
1✔
873

874
                return $this->htmlImage($context, $asset, $attributes, $options);
1✔
875
            }
876
        }
877

878
        return null;
1✔
879
    }
880

881
    /**
882
     * Converts an image Asset to WebP format.
883
     */
884
    public function webp(Asset $asset, ?int $quality = null): Asset
885
    {
886
        return $this->convert($asset, 'webp', $quality);
×
887
    }
888

889
    /**
890
     * Converts an image Asset to AVIF format.
891
     */
892
    public function avif(Asset $asset, ?int $quality = null): Asset
893
    {
894
        return $this->convert($asset, 'avif', $quality);
×
895
    }
896

897
    /**
898
     * Converts an image Asset to the given format.
899
     *
900
     * @throws RuntimeException
901
     */
902
    private function convert(Asset $asset, string $format, ?int $quality = null): Asset
903
    {
904
        if ($asset['subtype'] == "image/$format") {
×
905
            return $asset;
×
906
        }
907
        if (Image::isAnimatedGif($asset)) {
×
908
            throw new RuntimeException(\sprintf('Unable to convert the animated GIF "%s" to %s.', $asset['path'], $format));
×
909
        }
910

911
        try {
912
            return $asset->$format($quality);
×
913
        } catch (\Exception $e) {
×
914
            throw new RuntimeException(\sprintf('Unable to convert "%s" to %s (%s).', $asset['path'], $format, $e->getMessage()));
×
915
        }
916
    }
917

918
    /**
919
     * Returns the content of an asset.
920
     */
921
    public function inline(Asset $asset): string
922
    {
923
        return $asset['content'];
1✔
924
    }
925

926
    /**
927
     * Reads $length first characters of a string and adds a suffix.
928
     */
929
    public function excerpt(?string $string, int $length = 450, string $suffix = ' …'): string
930
    {
931
        $string = $string ?? '';
1✔
932

933
        $string = str_replace('</p>', '<br><br>', $string);
1✔
934
        $string = trim(strip_tags($string, '<br>'));
1✔
935
        if (mb_strlen($string) > $length) {
1✔
936
            $string = mb_substr($string, 0, $length);
1✔
937
            $string .= $suffix;
1✔
938
        }
939

940
        return $string;
1✔
941
    }
942

943
    /**
944
     * Reads characters before or after '<!-- separator -->'.
945
     * Options:
946
     *  - separator: string to use as separator (`excerpt|break` by default)
947
     *  - capture: part to capture, `before` or `after` the separator (`before` by default).
948
     */
949
    public function excerptHtml(?string $string, array $options = []): string
950
    {
951
        $string = $string ?? '';
1✔
952

953
        $separator = (string) $this->config->get('pages.body.excerpt.separator');
1✔
954
        $capture = (string) $this->config->get('pages.body.excerpt.capture');
1✔
955
        extract($options, EXTR_IF_EXISTS);
1✔
956

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

961
        if (empty($matches)) {
1✔
962
            return $string;
×
963
        }
964
        $result = trim($matches[1]);
1✔
965
        if ($capture == 'after') {
1✔
966
            $result = trim($matches[3]);
1✔
967
        }
968
        // removes footnotes and returns result
969
        return preg_replace('/<sup[^>]*>[^u]*<\/sup>/', '', $result);
1✔
970
    }
971

972
    /**
973
     * Converts a Markdown string to HTML.
974
     *
975
     * @throws RuntimeException
976
     */
977
    public function markdownToHtml(?string $markdown): ?string
978
    {
979
        $markdown = $markdown ?? '';
1✔
980

981
        try {
982
            $parsedown = new Parsedown($this->builder);
1✔
983
            $html = $parsedown->text($markdown);
1✔
984
        } catch (\Exception $e) {
×
985
            throw new RuntimeException(
×
986
                '"markdown_to_html" filter can not convert supplied Markdown.',
×
987
                previous: $e
×
988
            );
×
989
        }
990

991
        return $html;
1✔
992
    }
993

994
    /**
995
     * Extracts only headings matching the given `selectors` (h2, h3, etc.),
996
     * or those defined in config `pages.body.toc` if not specified.
997
     * The `format` parameter defines the output format: `html` or `json`.
998
     * The `url` parameter is used to build links to headings.
999
     *
1000
     * @throws RuntimeException
1001
     */
1002
    public function markdownToToc(?string $markdown, $format = 'html', ?array $selectors = null, string $url = ''): ?string
1003
    {
1004
        $markdown = $markdown ?? '';
1✔
1005
        $selectors = $selectors ?? (array) $this->config->get('pages.body.toc');
1✔
1006

1007
        try {
1008
            $parsedown = new Parsedown($this->builder, ['selectors' => $selectors, 'base_url' => $url]);
1✔
1009
            $parsedown->body($markdown);
1✔
1010
            $return = $parsedown->contentsList($format);
1✔
1011
        } catch (\Exception) {
×
1012
            throw new RuntimeException('"toc" filter can not convert supplied Markdown.');
×
1013
        }
1014

1015
        return $return;
1✔
1016
    }
1017

1018
    /**
1019
     * Converts a JSON string to an array.
1020
     *
1021
     * @throws RuntimeException
1022
     */
1023
    public function jsonDecode(?string $json): ?array
1024
    {
1025
        $json = $json ?? '';
1✔
1026

1027
        try {
1028
            $array = json_decode($json, true);
1✔
1029
            if ($array === null && json_last_error() !== JSON_ERROR_NONE) {
1✔
1030
                throw new \Exception('JSON error.');
1✔
1031
            }
1032
        } catch (\Exception) {
×
1033
            throw new RuntimeException('"json_decode" filter can not parse supplied JSON.');
×
1034
        }
1035

1036
        return $array;
1✔
1037
    }
1038

1039
    /**
1040
     * Converts a YAML string to an array.
1041
     *
1042
     * @throws RuntimeException
1043
     */
1044
    public function yamlParse(?string $yaml): ?array
1045
    {
1046
        $yaml = $yaml ?? '';
1✔
1047

1048
        try {
1049
            $array = Yaml::parse($yaml, Yaml::PARSE_DATETIME);
1✔
1050
            if (!\is_array($array)) {
1✔
1051
                throw new ParseException('YAML error.');
1✔
1052
            }
1053
        } catch (ParseException $e) {
×
1054
            throw new RuntimeException(\sprintf('"yaml_parse" filter can not parse supplied YAML: %s', $e->getMessage()));
×
1055
        }
1056

1057
        return $array;
1✔
1058
    }
1059

1060
    /**
1061
     * Split a string into an array using a regular expression.
1062
     *
1063
     * @throws RuntimeException
1064
     */
1065
    public function pregSplit(?string $value, string $pattern, int $limit = 0): ?array
1066
    {
1067
        $value = $value ?? '';
×
1068

1069
        try {
1070
            $array = preg_split($pattern, $value, $limit);
×
1071
            if ($array === false) {
×
1072
                throw new RuntimeException('PREG split error.');
×
1073
            }
1074
        } catch (\Exception) {
×
1075
            throw new RuntimeException('"preg_split" filter can not split supplied string.');
×
1076
        }
1077

1078
        return $array;
×
1079
    }
1080

1081
    /**
1082
     * Perform a regular expression match and return the group for all matches.
1083
     *
1084
     * @throws RuntimeException
1085
     */
1086
    public function pregMatchAll(?string $value, string $pattern, int $group = 0): ?array
1087
    {
1088
        $value = $value ?? '';
×
1089

1090
        try {
1091
            $array = preg_match_all($pattern, $value, $matches, PREG_PATTERN_ORDER);
×
1092
            if ($array === false) {
×
1093
                throw new RuntimeException('PREG match all error.');
×
1094
            }
1095
        } catch (\Exception) {
×
1096
            throw new RuntimeException('"preg_match_all" filter can not match in supplied string.');
×
1097
        }
1098

1099
        return $matches[$group];
×
1100
    }
1101

1102
    /**
1103
     * Calculates estimated time to read a text.
1104
     */
1105
    public function readtime(?string $text): string
1106
    {
1107
        $text = $text ?? '';
1✔
1108

1109
        $words = str_word_count(strip_tags($text));
1✔
1110
        $min = floor($words / 200);
1✔
1111
        if ($min === 0) {
1✔
1112
            return '1';
×
1113
        }
1114

1115
        return (string) $min;
1✔
1116
    }
1117

1118
    /**
1119
     * Gets the value of an environment variable.
1120
     */
1121
    public function getEnv(?string $var): ?string
1122
    {
1123
        $var = $var ?? '';
1✔
1124

1125
        return getenv($var) ?: null;
1✔
1126
    }
1127

1128
    /**
1129
     * Dump variable (or Twig context).
1130
     */
1131
    public function varDump(\Twig\Environment $env, array $context, $var = null, ?array $options = null): void
1132
    {
1133
        if (!$env->isDebug()) {
1✔
1134
            return;
×
1135
        }
1136

1137
        if ($var === null) {
1✔
1138
            $var = array();
×
1139
            foreach ($context as $key => $value) {
×
1140
                if (!$value instanceof \Twig\Template && !$value instanceof \Twig\TemplateWrapper) {
×
1141
                    $var[$key] = $value;
×
1142
                }
1143
            }
1144
        }
1145

1146
        $cloner = new VarCloner();
1✔
1147
        $cloner->setMinDepth(3);
1✔
1148
        $dumper = new HtmlDumper();
1✔
1149
        $dumper->setTheme($options['theme'] ?? 'light');
1✔
1150

1151
        $data = $cloner->cloneVar($var)->withMaxDepth(3);
1✔
1152
        $dumper->dump($data, null, ['maxDepth' => 3]);
1✔
1153
    }
1154

1155
    /**
1156
     * Tests if a variable is an Asset.
1157
     */
1158
    public function isAsset($variable): bool
1159
    {
1160
        return $variable instanceof Asset;
1✔
1161
    }
1162

1163
    /**
1164
     * Tests if an image Asset is large enough to be used as a cover image.
1165
     * A large image is defined as having a width >= 600px and height >= 315px.
1166
     */
1167
    public function isImageLarge(Asset $asset): bool
1168
    {
1169
        return $asset['type'] == 'image' && $asset['width'] > $asset['height'] && $asset['width'] >= 600 && $asset['height'] >= 315;
1✔
1170
    }
1171

1172
    /**
1173
     * Tests if an image Asset is square.
1174
     * A square image is defined as having the same width and height.
1175
     */
1176
    public function isImageSquare(Asset $asset): bool
1177
    {
1178
        return $asset['type'] == 'image' && $asset['width'] == $asset['height'];
1✔
1179
    }
1180

1181
    /**
1182
     * Returns the dominant hex color of an image asset.
1183
     *
1184
     * @param string|Asset $asset
1185
     *
1186
     * @return string
1187
     */
1188
    public function dominantColor($asset): string
1189
    {
1190
        if (!$asset instanceof Asset) {
1✔
1191
            $asset = new Asset($this->builder, $asset);
×
1192
        }
1193

1194
        return Image::getDominantColor($asset);
1✔
1195
    }
1196

1197
    /**
1198
     * Returns a Low Quality Image Placeholder (LQIP) as data URL.
1199
     *
1200
     * @param string|Asset $asset
1201
     *
1202
     * @return string
1203
     */
1204
    public function lqip($asset): string
1205
    {
1206
        if (!$asset instanceof Asset) {
1✔
1207
            $asset = new Asset($this->builder, $asset);
×
1208
        }
1209

1210
        return Image::getLqip($asset);
1✔
1211
    }
1212

1213
    /**
1214
     * Converts an hexadecimal color to RGB.
1215
     *
1216
     * @throws RuntimeException
1217
     */
1218
    public function hexToRgb(?string $variable): array
1219
    {
1220
        $variable = $variable ?? '';
1✔
1221

1222
        if (!self::isHex($variable)) {
1✔
1223
            throw new RuntimeException(\sprintf('"%s" is not a valid hexadecimal value.', $variable));
×
1224
        }
1225
        $hex = ltrim($variable, '#');
1✔
1226
        if (\strlen($hex) == 3) {
1✔
1227
            $hex = $hex[0] . $hex[0] . $hex[1] . $hex[1] . $hex[2] . $hex[2];
×
1228
        }
1229
        $c = hexdec($hex);
1✔
1230

1231
        return [
1✔
1232
            'red'   => $c >> 16 & 0xFF,
1✔
1233
            'green' => $c >> 8 & 0xFF,
1✔
1234
            'blue'  => $c & 0xFF,
1✔
1235
        ];
1✔
1236
    }
1237

1238
    /**
1239
     * Split a string in multiple lines.
1240
     */
1241
    public function splitLine(?string $variable, int $max = 18): array
1242
    {
1243
        $variable = $variable ?? '';
1✔
1244

1245
        return preg_split("/.{0,{$max}}\K(\s+|$)/", $variable, 0, PREG_SPLIT_NO_EMPTY);
1✔
1246
    }
1247

1248
    /**
1249
     * Hashing an object, an array or a string (with algo, xxh128 by default).
1250
     */
1251
    public function hash(object|array|string $data, $algo = 'xxh128'): string
1252
    {
1253
        switch (\gettype($data)) {
1✔
1254
            case 'object':
1✔
1255
                return hash($algo, $data::class . spl_object_id($data));
1✔
1256
            case 'array':
×
1257
                return hash($algo, serialize($data));
×
1258
        }
1259

1260
        return hash($algo, $data);
×
1261
    }
1262

1263
    /**
1264
     * Builds a cache key from a variable.
1265
     * The cache key is built from the name of the variable, its hash, the site language and build.
1266
     *
1267
     * @param array                    $context Twig context, used to get the site language and build.
1268
     * @param string                   $name    Name of the variable to build the cache key from.
1269
     * @param object|array|string|null $value   The variable to build the cache key from.
1270
     */
1271
    public function cacheKey(array $context, string $name, object|array|string|null $value = null): string
1272
    {
1273
        $key = $name . ($value ? '-' . $this->hash($value) : '');
1✔
1274
        $key = $key . '-' . $context['site']['language'] . '-' . $context['site']['build'];
1✔
1275

1276
        return preg_replace('/[{}()\/\\\@:]/', '-', $key); // replace any of the reserved characters
1✔
1277
    }
1278

1279
    /**
1280
     * Converts a variable to an iterable (array).
1281
     */
1282
    public function iterable($value): array
1283
    {
1284
        if (\is_array($value)) {
1✔
1285
            return $value;
1✔
1286
        }
1287
        if (\is_string($value)) {
×
1288
            return [$value];
×
1289
        }
1290
        if ($value instanceof \Traversable) {
×
1291
            return iterator_to_array($value);
×
1292
        }
1293
        if ($value instanceof \stdClass) {
×
1294
            return (array) $value;
×
1295
        }
1296
        if (\is_object($value)) {
×
1297
            return [$value];
×
1298
        }
1299
        if (\is_int($value) || \is_float($value)) {
×
1300
            return [$value];
×
1301
        }
1302
        return [$value];
×
1303
    }
1304

1305
    /**
1306
     * Highlights a code snippet.
1307
     */
1308
    public function highlight(string $code, string $language): string
1309
    {
1310
        return (new Highlighter())->highlight($language, $code)->value;
×
1311
    }
1312

1313
    /**
1314
     * Returns an array with unique values.
1315
     */
1316
    public function unique(array $array): array
1317
    {
1318
        return array_intersect_key($array, array_unique(array_map('strtolower', $array), SORT_STRING));
1✔
1319
    }
1320

1321
    /**
1322
     * Is a hexadecimal color is valid?
1323
     */
1324
    private static function isHex(string $hex): bool
1325
    {
1326
        $valid = \is_string($hex);
1✔
1327
        $hex = ltrim($hex, '#');
1✔
1328
        $length = \strlen($hex);
1✔
1329
        $valid = $valid && ($length === 3 || $length === 6);
1✔
1330
        $valid = $valid && ctype_xdigit($hex);
1✔
1331

1332
        return $valid;
1✔
1333
    }
1334

1335
    /**
1336
     * Builds the HTML attributes string from an array.
1337
     */
1338
    private static function htmlAttributes(array $attributes): string
1339
    {
1340
        $htmlAttributes = '';
1✔
1341
        foreach ($attributes as $name => $value) {
1✔
1342
            $attribute = \sprintf(' %s="%s"', $name, $value);
1✔
1343
            if (empty($value)) {
1✔
1344
                $attribute = \sprintf(' %s', $name);
1✔
1345
            }
1346
            $htmlAttributes .= $attribute;
1✔
1347
        }
1348

1349
        return $htmlAttributes;
1✔
1350
    }
1351
}
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