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

Cecilapp / Cecil / 19859909440

02 Dec 2025 01:16PM UTC coverage: 82.119%. First build
19859909440

Pull #2256

github

web-flow
Merge 10bbce255 into c57e63463
Pull Request #2256: feat: image_from_url Twig function

28 of 33 new or added lines in 2 files covered. (84.85%)

3256 of 3965 relevant lines covered (82.12%)

0.82 hits per line

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

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

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

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

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

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

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

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

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

80
    /**
81
     * {@inheritdoc}
82
     */
83
    public function getFunctions()
84
    {
85
        return [
1✔
86
            new \Twig\TwigFunction('url', [$this, 'url'], ['needs_context' => true]),
1✔
87
            // assets
88
            new \Twig\TwigFunction('asset', [$this, 'asset']),
1✔
89
            new \Twig\TwigFunction('html', [$this, 'html'], ['needs_context' => true]),
1✔
90
            new \Twig\TwigFunction('css', [$this, 'htmlCss'], ['needs_context' => true]),
1✔
91
            new \Twig\TwigFunction('js', [$this, 'htmlJs'], ['needs_context' => true]),
1✔
92
            new \Twig\TwigFunction('image', [$this, 'htmlImage'], ['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_url', [$this, 'htmlImageFromUrl'], ['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
        ];
1✔
116
    }
117

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

176
    /**
177
     * {@inheritdoc}
178
     */
179
    public function getTests()
180
    {
181
        return [
1✔
182
            new \Twig\TwigTest('asset', [$this, 'isAsset']),
1✔
183
            new \Twig\TwigTest('image_large', [$this, 'isImageLarge']),
1✔
184
            new \Twig\TwigTest('image_square', [$this, 'isImageSquare']),
1✔
185
        ];
1✔
186
    }
187

188
    /**
189
     * Filters by Section.
190
     */
191
    public function filterBySection(PagesCollection $pages, string $section): CollectionInterface
192
    {
193
        return $this->filterBy($pages, 'section', $section);
×
194
    }
195

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

213
        return $filteredPages;
1✔
214
    }
215

216
    /**
217
     * Sorts a collection by title.
218
     */
219
    public function sortByTitle(\Traversable $collection): array
220
    {
221
        $sort = \SORT_ASC;
1✔
222

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

226
        return $collection;
1✔
227
    }
228

229
    /**
230
     * Sorts a collection by weight.
231
     *
232
     * @param \Traversable|array $collection
233
     */
234
    public function sortByWeight($collection): array
235
    {
236
        $callback = function ($a, $b) {
1✔
237
            if (!isset($a['weight'])) {
1✔
238
                $a['weight'] = 0;
1✔
239
            }
240
            if (!isset($b['weight'])) {
1✔
241
                $a['weight'] = 0;
×
242
            }
243
            if ($a['weight'] == $b['weight']) {
1✔
244
                return 0;
1✔
245
            }
246

247
            return $a['weight'] < $b['weight'] ? -1 : 1;
1✔
248
        };
1✔
249

250
        if (!\is_array($collection)) {
1✔
251
            $collection = iterator_to_array($collection);
1✔
252
        }
253
        usort(/** @scrutinizer ignore-type */ $collection, $callback);
1✔
254

255
        return $collection;
1✔
256
    }
257

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

270
                return 0;
1✔
271
            }
272

273
            return $a[$variable] > $b[$variable] ? -1 : 1;
1✔
274
        };
1✔
275

276
        $collection = iterator_to_array($collection);
1✔
277
        usort(/** @scrutinizer ignore-type */ $collection, $callback);
1✔
278

279
        return $collection;
1✔
280
    }
281

282
    /**
283
     * Creates an URL.
284
     *
285
     * $options[
286
     *     'canonical' => false,
287
     *     'format'    => 'html',
288
     *     'language'  => null,
289
     * ];
290
     *
291
     * @param array                  $context
292
     * @param Page|Asset|string|null $value
293
     * @param array|null             $options
294
     */
295
    public function url(array $context, $value = null, ?array $options = null): string
296
    {
297
        $optionsLang = [];
1✔
298
        $optionsLang['language'] = (string) $context['site']['language'];
1✔
299
        $options = array_merge($optionsLang, $options ?? []);
1✔
300

301
        return (new Url($this->builder, $value, $options))->getUrl();
1✔
302
    }
303

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

318
        return new Asset($this->builder, $path, $options);
1✔
319
    }
320

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

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

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

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

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

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

369
    /**
370
     * Resizes an image.
371
     *
372
     * @param string|Asset $asset
373
     *
374
     * @return Asset
375
     */
376
    public function resize($asset, int $size): Asset
377
    {
378
        if (!$asset instanceof Asset) {
1✔
379
            $asset = new Asset($this->builder, $asset);
×
380
        }
381

382
        return $asset->resize($size);
1✔
383
    }
384

385
    /**
386
     * Crops an image Asset to the given width and height, keeping the aspect ratio.
387
     *
388
     * @param string|Asset $asset
389
     *
390
     * @return Asset
391
     */
392
    public function cover($asset, int $width, int $height): Asset
393
    {
394
        if (!$asset instanceof Asset) {
1✔
395
            $asset = new Asset($this->builder, $asset);
×
396
        }
397

398
        return $asset->cover($width, $height);
1✔
399
    }
400

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

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

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

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

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

448
        return $asset->getIntegrity($algo);
1✔
449
    }
450

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

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

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

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

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

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

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

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

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

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

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

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

597
        return implode("\n    ", $html);
1✔
598
    }
599

600
    /**
601
     * Builds the HTML link element of a CSS Asset.
602
     */
603
    public function htmlCss(array $context, Asset $asset, array $attributes = [], array $options = []): string
604
    {
605
        // simulate "defer" by using "preload" and "onload"
606
        if (isset($attributes['defer'])) {
1✔
607
            unset($attributes['defer']);
×
608
            return \sprintf(
×
609
                '<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>',
×
610
                $this->url($context, $asset, $options),
×
611
                self::htmlAttributes($attributes)
×
612
            );
×
613
        }
614

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

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

626
    /**
627
     * Builds the HTML img element of an image Asset.
628
     */
629
    public function htmlImage(array $context, Asset $asset, array $attributes = [], array $options = []): string
630
    {
631
        $htmlAttributes = self::htmlAttributes($attributes);
1✔
632
        if (!isset($attributes['alt'])) {
1✔
633
            $htmlAttributes .= ' alt=""';
1✔
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
                $htmlAttributes .= \sprintf(' srcset="%s" sizes="%s"', $srcset, Image::getHtmlSizes($attributes['class'] ?? '', $this->config->getAssetsImagesSizes()));
1✔
642
                // prevent oversized images
643
                if ($asset['width'] > max($this->config->getAssetsImagesWidths())) {
1✔
644
                    $asset = $asset->resize(max($this->config->getAssetsImagesWidths()));
×
645
                }
646
            }
647
            if ($responsive == 'density') {
1✔
648
                $width1x = isset($attributes['width']) && $attributes['width'] > 0 ? (int) $attributes['width'] : $asset['width'];
1✔
649
                $srcset = Image::buildHtmlSrcsetX($asset, $width1x, $this->config->getAssetsImagesDensities());
1✔
650
                $htmlAttributes .= \sprintf(' srcset="%s"', $srcset);
1✔
651
            }
652
        } catch (\Exception $e) {
×
653
            $this->builder->getLogger()->warning($e->getMessage());
×
654
        }
655

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

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

697
        // put `<source>` elements in `<picture>` if exists
698
        if (!empty($source)) {
1✔
699
            return \sprintf("<picture>%s\n  %s\n</picture>", $source, $img);
1✔
700
        }
701

702
        return $img;
1✔
703
    }
704

705
    /**
706
     * Builds the HTML video element of a video Asset.
707
     */
708
    public function htmlVideo(array $context, Asset $asset, array $attributes = [], array $options = []): string
709
    {
710
        if (empty($attributes)) {
1✔
711
            $attributes['controls'] = '';
1✔
712
        }
713

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

717
    /**
718
     * Builds the HTML img `srcset` (responsive) attribute of an image Asset, based on configured widths.
719
     *
720
     * @throws RuntimeException
721
     */
722
    public function imageSrcset(Asset $asset): string
723
    {
724
        return Image::buildHtmlSrcsetW($asset, $this->config->getAssetsImagesWidths(), true);
1✔
725
    }
726

727
    /**
728
     * Returns the HTML img `sizes` attribute based on a CSS class name.
729
     */
730
    public function imageSizes(string $class): string
731
    {
732
        return Image::getHtmlSizes($class, $this->config->getAssetsImagesSizes());
1✔
733
    }
734

735
    /**
736
     * Builds the HTML img element from a URL by extracting the image from meta tags.
737
     * Returns null if no image found.
738
     *
739
     * @throws RuntimeException
740
     */
741
    public function htmlImageFromUrl(array $context, string $url, array $attributes = [], array $options = []): ?string
742
    {
743
        if (false !== $html = Util\File::fileGetContents($url)) {
1✔
744
            $imageUrl = Util\Html::getImageFromMetaTags($html);
1✔
745
            if ($imageUrl === null) {
1✔
746
                return null;
1✔
747
            }
748
            $asset = new Asset($this->builder, $imageUrl);
1✔
749
        } else {
NEW
750
            return null;
×
751
        }
752

753
        return $this->htmlImage($context, $asset, $attributes, $options);
1✔
754
    }
755

756
    /**
757
     * Converts an image Asset to WebP format.
758
     */
759
    public function webp(Asset $asset, ?int $quality = null): Asset
760
    {
761
        return $this->convert($asset, 'webp', $quality);
×
762
    }
763

764
    /**
765
     * Converts an image Asset to AVIF format.
766
     */
767
    public function avif(Asset $asset, ?int $quality = null): Asset
768
    {
769
        return $this->convert($asset, 'avif', $quality);
×
770
    }
771

772
    /**
773
     * Converts an image Asset to the given format.
774
     *
775
     * @throws RuntimeException
776
     */
777
    private function convert(Asset $asset, string $format, ?int $quality = null): Asset
778
    {
779
        if ($asset['subtype'] == "image/$format") {
×
780
            return $asset;
×
781
        }
782
        if (Image::isAnimatedGif($asset)) {
×
783
            throw new RuntimeException(\sprintf('Unable to convert the animated GIF "%s" to %s.', $asset['path'], $format));
×
784
        }
785

786
        try {
787
            return $asset->$format($quality);
×
788
        } catch (\Exception $e) {
×
789
            throw new RuntimeException(\sprintf('Unable to convert "%s" to %s (%s).', $asset['path'], $format, $e->getMessage()));
×
790
        }
791
    }
792

793
    /**
794
     * Returns the content of an asset.
795
     */
796
    public function inline(Asset $asset): string
797
    {
798
        return $asset['content'];
1✔
799
    }
800

801
    /**
802
     * Reads $length first characters of a string and adds a suffix.
803
     */
804
    public function excerpt(?string $string, int $length = 450, string $suffix = ' …'): string
805
    {
806
        $string = $string ?? '';
1✔
807

808
        $string = str_replace('</p>', '<br><br>', $string);
1✔
809
        $string = trim(strip_tags($string, '<br>'));
1✔
810
        if (mb_strlen($string) > $length) {
1✔
811
            $string = mb_substr($string, 0, $length);
1✔
812
            $string .= $suffix;
1✔
813
        }
814

815
        return $string;
1✔
816
    }
817

818
    /**
819
     * Reads characters before or after '<!-- separator -->'.
820
     * Options:
821
     *  - separator: string to use as separator (`excerpt|break` by default)
822
     *  - capture: part to capture, `before` or `after` the separator (`before` by default).
823
     */
824
    public function excerptHtml(?string $string, array $options = []): string
825
    {
826
        $string = $string ?? '';
1✔
827

828
        $separator = (string) $this->config->get('pages.body.excerpt.separator');
1✔
829
        $capture = (string) $this->config->get('pages.body.excerpt.capture');
1✔
830
        extract($options, EXTR_IF_EXISTS);
1✔
831

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

836
        if (empty($matches)) {
1✔
837
            return $string;
×
838
        }
839
        $result = trim($matches[1]);
1✔
840
        if ($capture == 'after') {
1✔
841
            $result = trim($matches[3]);
1✔
842
        }
843
        // removes footnotes and returns result
844
        return preg_replace('/<sup[^>]*>[^u]*<\/sup>/', '', $result);
1✔
845
    }
846

847
    /**
848
     * Converts a Markdown string to HTML.
849
     *
850
     * @throws RuntimeException
851
     */
852
    public function markdownToHtml(?string $markdown): ?string
853
    {
854
        $markdown = $markdown ?? '';
1✔
855

856
        try {
857
            $parsedown = new Parsedown($this->builder);
1✔
858
            $html = $parsedown->text($markdown);
1✔
859
        } catch (\Exception $e) {
×
860
            throw new RuntimeException(
×
861
                '"markdown_to_html" filter can not convert supplied Markdown.',
×
862
                previous: $e
×
863
            );
×
864
        }
865

866
        return $html;
1✔
867
    }
868

869
    /**
870
     * Extract table of content of a Markdown string,
871
     * in the given format ("html" or "json", "html" by default).
872
     *
873
     * @throws RuntimeException
874
     */
875
    public function markdownToToc(?string $markdown, $format = 'html', ?array $selectors = null, string $url = ''): ?string
876
    {
877
        $markdown = $markdown ?? '';
1✔
878
        $selectors = $selectors ?? (array) $this->config->get('pages.body.toc');
1✔
879

880
        try {
881
            $parsedown = new Parsedown($this->builder, ['selectors' => $selectors, 'url' => $url]);
1✔
882
            $parsedown->body($markdown);
1✔
883
            $return = $parsedown->contentsList($format);
1✔
884
        } catch (\Exception) {
×
885
            throw new RuntimeException('"toc" filter can not convert supplied Markdown.');
×
886
        }
887

888
        return $return;
1✔
889
    }
890

891
    /**
892
     * Converts a JSON string to an array.
893
     *
894
     * @throws RuntimeException
895
     */
896
    public function jsonDecode(?string $json): ?array
897
    {
898
        $json = $json ?? '';
1✔
899

900
        try {
901
            $array = json_decode($json, true);
1✔
902
            if ($array === null && json_last_error() !== JSON_ERROR_NONE) {
1✔
903
                throw new \Exception('JSON error.');
1✔
904
            }
905
        } catch (\Exception) {
×
906
            throw new RuntimeException('"json_decode" filter can not parse supplied JSON.');
×
907
        }
908

909
        return $array;
1✔
910
    }
911

912
    /**
913
     * Converts a YAML string to an array.
914
     *
915
     * @throws RuntimeException
916
     */
917
    public function yamlParse(?string $yaml): ?array
918
    {
919
        $yaml = $yaml ?? '';
1✔
920

921
        try {
922
            $array = Yaml::parse($yaml, Yaml::PARSE_DATETIME);
1✔
923
            if (!\is_array($array)) {
1✔
924
                throw new ParseException('YAML error.');
1✔
925
            }
926
        } catch (ParseException $e) {
×
927
            throw new RuntimeException(\sprintf('"yaml_parse" filter can not parse supplied YAML: %s', $e->getMessage()));
×
928
        }
929

930
        return $array;
1✔
931
    }
932

933
    /**
934
     * Split a string into an array using a regular expression.
935
     *
936
     * @throws RuntimeException
937
     */
938
    public function pregSplit(?string $value, string $pattern, int $limit = 0): ?array
939
    {
940
        $value = $value ?? '';
×
941

942
        try {
943
            $array = preg_split($pattern, $value, $limit);
×
944
            if ($array === false) {
×
945
                throw new RuntimeException('PREG split error.');
×
946
            }
947
        } catch (\Exception) {
×
948
            throw new RuntimeException('"preg_split" filter can not split supplied string.');
×
949
        }
950

951
        return $array;
×
952
    }
953

954
    /**
955
     * Perform a regular expression match and return the group for all matches.
956
     *
957
     * @throws RuntimeException
958
     */
959
    public function pregMatchAll(?string $value, string $pattern, int $group = 0): ?array
960
    {
961
        $value = $value ?? '';
×
962

963
        try {
964
            $array = preg_match_all($pattern, $value, $matches, PREG_PATTERN_ORDER);
×
965
            if ($array === false) {
×
966
                throw new RuntimeException('PREG match all error.');
×
967
            }
968
        } catch (\Exception) {
×
969
            throw new RuntimeException('"preg_match_all" filter can not match in supplied string.');
×
970
        }
971

972
        return $matches[$group];
×
973
    }
974

975
    /**
976
     * Calculates estimated time to read a text.
977
     */
978
    public function readtime(?string $text): string
979
    {
980
        $text = $text ?? '';
1✔
981

982
        $words = str_word_count(strip_tags($text));
1✔
983
        $min = floor($words / 200);
1✔
984
        if ($min === 0) {
1✔
985
            return '1';
×
986
        }
987

988
        return (string) $min;
1✔
989
    }
990

991
    /**
992
     * Gets the value of an environment variable.
993
     */
994
    public function getEnv(?string $var): ?string
995
    {
996
        $var = $var ?? '';
1✔
997

998
        return getenv($var) ?: null;
1✔
999
    }
1000

1001
    /**
1002
     * Dump variable (or Twig context).
1003
     */
1004
    public function varDump(\Twig\Environment $env, array $context, $var = null, ?array $options = null): void
1005
    {
1006
        if (!$env->isDebug()) {
1✔
1007
            return;
×
1008
        }
1009

1010
        if ($var === null) {
1✔
1011
            $var = array();
×
1012
            foreach ($context as $key => $value) {
×
1013
                if (!$value instanceof \Twig\Template && !$value instanceof \Twig\TemplateWrapper) {
×
1014
                    $var[$key] = $value;
×
1015
                }
1016
            }
1017
        }
1018

1019
        $cloner = new VarCloner();
1✔
1020
        $cloner->setMinDepth(3);
1✔
1021
        $dumper = new HtmlDumper();
1✔
1022
        $dumper->setTheme($options['theme'] ?? 'light');
1✔
1023

1024
        $data = $cloner->cloneVar($var)->withMaxDepth(3);
1✔
1025
        $dumper->dump($data, null, ['maxDepth' => 3]);
1✔
1026
    }
1027

1028
    /**
1029
     * Tests if a variable is an Asset.
1030
     */
1031
    public function isAsset($variable): bool
1032
    {
1033
        return $variable instanceof Asset;
1✔
1034
    }
1035

1036
    /**
1037
     * Tests if an image Asset is large enough to be used as a cover image.
1038
     * A large image is defined as having a width >= 600px and height >= 315px.
1039
     */
1040
    public function isImageLarge(Asset $asset): bool
1041
    {
1042
        return $asset['type'] == 'image' && $asset['width'] > $asset['height'] && $asset['width'] >= 600 && $asset['height'] >= 315;
1✔
1043
    }
1044

1045
    /**
1046
     * Tests if an image Asset is square.
1047
     * A square image is defined as having the same width and height.
1048
     */
1049
    public function isImageSquare(Asset $asset): bool
1050
    {
1051
        return $asset['type'] == 'image' && $asset['width'] == $asset['height'];
1✔
1052
    }
1053

1054
    /**
1055
     * Returns the dominant hex color of an image asset.
1056
     *
1057
     * @param string|Asset $asset
1058
     *
1059
     * @return string
1060
     */
1061
    public function dominantColor($asset): string
1062
    {
1063
        if (!$asset instanceof Asset) {
1✔
1064
            $asset = new Asset($this->builder, $asset);
×
1065
        }
1066

1067
        return Image::getDominantColor($asset);
1✔
1068
    }
1069

1070
    /**
1071
     * Returns a Low Quality Image Placeholder (LQIP) as data URL.
1072
     *
1073
     * @param string|Asset $asset
1074
     *
1075
     * @return string
1076
     */
1077
    public function lqip($asset): string
1078
    {
1079
        if (!$asset instanceof Asset) {
1✔
1080
            $asset = new Asset($this->builder, $asset);
×
1081
        }
1082

1083
        return Image::getLqip($asset);
1✔
1084
    }
1085

1086
    /**
1087
     * Converts an hexadecimal color to RGB.
1088
     *
1089
     * @throws RuntimeException
1090
     */
1091
    public function hexToRgb(?string $variable): array
1092
    {
1093
        $variable = $variable ?? '';
1✔
1094

1095
        if (!self::isHex($variable)) {
1✔
1096
            throw new RuntimeException(\sprintf('"%s" is not a valid hexadecimal value.', $variable));
×
1097
        }
1098
        $hex = ltrim($variable, '#');
1✔
1099
        if (\strlen($hex) == 3) {
1✔
1100
            $hex = $hex[0] . $hex[0] . $hex[1] . $hex[1] . $hex[2] . $hex[2];
×
1101
        }
1102
        $c = hexdec($hex);
1✔
1103

1104
        return [
1✔
1105
            'red'   => $c >> 16 & 0xFF,
1✔
1106
            'green' => $c >> 8 & 0xFF,
1✔
1107
            'blue'  => $c & 0xFF,
1✔
1108
        ];
1✔
1109
    }
1110

1111
    /**
1112
     * Split a string in multiple lines.
1113
     */
1114
    public function splitLine(?string $variable, int $max = 18): array
1115
    {
1116
        $variable = $variable ?? '';
1✔
1117

1118
        return preg_split("/.{0,{$max}}\K(\s+|$)/", $variable, 0, PREG_SPLIT_NO_EMPTY);
1✔
1119
    }
1120

1121
    /**
1122
     * Hashing an object, an array or a string (with algo, md5 by default).
1123
     */
1124
    public function hash(object|array|string $data, $algo = 'md5'): string
1125
    {
1126
        switch (\gettype($data)) {
1✔
1127
            case 'object':
1✔
1128
                return spl_object_hash($data);
1✔
1129
            case 'array':
×
1130
                return hash($algo, serialize($data));
×
1131
        }
1132

1133
        return hash($algo, $data);
×
1134
    }
1135

1136
    /**
1137
     * Converts a variable to an iterable (array).
1138
     */
1139
    public function iterable($value): array
1140
    {
1141
        if (\is_array($value)) {
1✔
1142
            return $value;
1✔
1143
        }
1144
        if (\is_string($value)) {
×
1145
            return [$value];
×
1146
        }
1147
        if ($value instanceof \Traversable) {
×
1148
            return iterator_to_array($value);
×
1149
        }
1150
        if ($value instanceof \stdClass) {
×
1151
            return (array) $value;
×
1152
        }
1153
        if (\is_object($value)) {
×
1154
            return [$value];
×
1155
        }
1156
        if (\is_int($value) || \is_float($value)) {
×
1157
            return [$value];
×
1158
        }
1159
        return [$value];
×
1160
    }
1161

1162
    /**
1163
     * Highlights a code snippet.
1164
     */
1165
    public function highlight(string $code, string $language): string
1166
    {
1167
        return (new Highlighter())->highlight($language, $code)->value;
×
1168
    }
1169

1170
    /**
1171
     * Returns an array with unique values.
1172
     */
1173
    public function unique(array $array): array
1174
    {
1175
        return array_intersect_key($array, array_unique(array_map('strtolower', $array), SORT_STRING));
1✔
1176
    }
1177

1178
    /**
1179
     * Is a hexadecimal color is valid?
1180
     */
1181
    private static function isHex(string $hex): bool
1182
    {
1183
        $valid = \is_string($hex);
1✔
1184
        $hex = ltrim($hex, '#');
1✔
1185
        $length = \strlen($hex);
1✔
1186
        $valid = $valid && ($length === 3 || $length === 6);
1✔
1187
        $valid = $valid && ctype_xdigit($hex);
1✔
1188

1189
        return $valid;
1✔
1190
    }
1191

1192
    /**
1193
     * Builds the HTML attributes string from an array.
1194
     */
1195
    private static function htmlAttributes(array $attributes): string
1196
    {
1197
        $htmlAttributes = '';
1✔
1198
        foreach ($attributes as $name => $value) {
1✔
1199
            $attribute = \sprintf(' %s="%s"', $name, $value);
1✔
1200
            if (empty($value)) {
1✔
1201
                $attribute = \sprintf(' %s', $name);
1✔
1202
            }
1203
            $htmlAttributes .= $attribute;
1✔
1204
        }
1205

1206
        return $htmlAttributes;
1✔
1207
    }
1208
}
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