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

Cecilapp / Cecil / 13765664699

10 Mar 2025 01:18PM UTC coverage: 82.998% (-0.4%) from 83.394%
13765664699

Pull #2133

github

web-flow
Merge d6653d3b5 into a9fd56ab7
Pull Request #2133: refactor: better cache

106 of 124 new or added lines in 11 files covered. (85.48%)

23 existing lines in 6 files now uncovered.

2973 of 3582 relevant lines covered (83.0%)

0.83 hits per line

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

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

3
declare(strict_types=1);
4

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

14
namespace Cecil\Renderer\Extension;
15

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

40
/**
41
 * Class Renderer\Extension\Core.
42
 */
43
class Core extends SlugifyExtension
44
{
45
    /** @var Builder */
46
    protected $builder;
47

48
    /** @var Config */
49
    protected $config;
50

51
    /** @var Slugify */
52
    private static $slugifier;
53

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

60
        parent::__construct(self::$slugifier);
1✔
61

62
        $this->builder = $builder;
1✔
63
        $this->config = $builder->getConfig();
1✔
64
    }
65

66
    /**
67
     * {@inheritdoc}
68
     */
69
    public function getName(): string
70
    {
71
        return 'CoreExtension';
×
72
    }
73

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

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

155
    /**
156
     * {@inheritdoc}
157
     */
158
    public function getTests()
159
    {
160
        return [
1✔
161
            new \Twig\TwigTest('asset', [$this, 'isAsset']),
1✔
162
        ];
1✔
163
    }
164

165
    /**
166
     * Filters by Section.
167
     */
168
    public function filterBySection(PagesCollection $pages, string $section): CollectionInterface
169
    {
170
        return $this->filterBy($pages, 'section', $section);
×
171
    }
172

173
    /**
174
     * Filters a pages collection by variable's name/value.
175
     */
176
    public function filterBy(PagesCollection $pages, string $variable, string $value): CollectionInterface
177
    {
178
        $filteredPages = $pages->filter(function (Page $page) use ($variable, $value) {
1✔
179
            // is a dedicated getter exists?
180
            $method = 'get' . ucfirst($variable);
1✔
181
            if (method_exists($page, $method) && $page->$method() == $value) {
1✔
182
                return $page->getType() == Type::PAGE->value && !$page->isVirtual() && true;
×
183
            }
184
            // or a classic variable
185
            if ($page->getVariable($variable) == $value) {
1✔
186
                return $page->getType() == Type::PAGE->value && !$page->isVirtual() && true;
1✔
187
            }
188
        });
1✔
189

190
        return $filteredPages;
1✔
191
    }
192

193
    /**
194
     * Sorts a collection by title.
195
     */
196
    public function sortByTitle(\Traversable $collection): array
197
    {
198
        $sort = \SORT_ASC;
1✔
199

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

203
        return $collection;
1✔
204
    }
205

206
    /**
207
     * Sorts a collection by weight.
208
     *
209
     * @param \Traversable|array $collection
210
     */
211
    public function sortByWeight($collection): array
212
    {
213
        $callback = function ($a, $b) {
1✔
214
            if (!isset($a['weight'])) {
1✔
215
                $a['weight'] = 0;
1✔
216
            }
217
            if (!isset($b['weight'])) {
1✔
218
                $a['weight'] = 0;
×
219
            }
220
            if ($a['weight'] == $b['weight']) {
1✔
221
                return 0;
1✔
222
            }
223

224
            return $a['weight'] < $b['weight'] ? -1 : 1;
1✔
225
        };
1✔
226

227
        if (!\is_array($collection)) {
1✔
228
            $collection = iterator_to_array($collection);
1✔
229
        }
230
        usort(/** @scrutinizer ignore-type */ $collection, $callback);
1✔
231

232
        return $collection;
1✔
233
    }
234

235
    /**
236
     * Sorts by creation date (or 'updated' date): the most recent first.
237
     */
238
    public function sortByDate(\Traversable $collection, string $variable = 'date', bool $descTitle = false): array
239
    {
240
        $callback = function ($a, $b) use ($variable, $descTitle) {
1✔
241
            if ($a[$variable] == $b[$variable]) {
1✔
242
                // if dates are equal and "descTitle" is true
243
                if ($descTitle && (isset($a['title']) && isset($b['title']))) {
1✔
244
                    return strnatcmp($b['title'], $a['title']);
×
245
                }
246

247
                return 0;
1✔
248
            }
249

250
            return $a[$variable] > $b[$variable] ? -1 : 1;
1✔
251
        };
1✔
252

253
        $collection = iterator_to_array($collection);
1✔
254
        usort(/** @scrutinizer ignore-type */ $collection, $callback);
1✔
255

256
        return $collection;
1✔
257
    }
258

259
    /**
260
     * Creates an URL.
261
     *
262
     * $options[
263
     *     'canonical' => false,
264
     *     'format'    => 'html',
265
     *     'language'  => null,
266
     * ];
267
     *
268
     * @param array                  $context
269
     * @param Page|Asset|string|null $value
270
     * @param array|null             $options
271
     */
272
    public function url(array $context, $value = null, ?array $options = null): string
273
    {
274
        $optionsLang = [];
1✔
275
        $optionsLang['language'] = (string) $context['site']['language'];
1✔
276
        $options = array_merge($optionsLang, $options ?? []);
1✔
277

278
        return (new Url($this->builder, $value, $options))->getUrl();
1✔
279
    }
280

281
    /**
282
     * Creates an Asset (CSS, JS, images, etc.) from a path or an array of paths.
283
     *
284
     * @param string|array $path    File path or array of files path (relative from `assets/` or `static/` dir).
285
     * @param array|null   $options
286
     *
287
     * @return Asset
288
     */
289
    public function asset($path, array|null $options = null): Asset
290
    {
291
        if (!\is_string($path) && !\is_array($path)) {
1✔
292
            throw new RuntimeException(\sprintf('Argument of "%s()" must a string or an array.', \Cecil\Util::formatMethodName(__METHOD__)));
×
293
        }
294

295
        return new Asset($this->builder, $path, $options);
1✔
296
    }
297

298
    /**
299
     * Compiles a SCSS asset.
300
     *
301
     * @param string|Asset $asset
302
     *
303
     * @return Asset
304
     */
305
    public function toCss($asset): Asset
306
    {
307
        if (!$asset instanceof Asset) {
1✔
308
            $asset = new Asset($this->builder, $asset);
×
309
        }
310

311
        return $asset->compile();
1✔
312
    }
313

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

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

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

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

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

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

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

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

378
    /**
379
     * Hashing an asset with algo (sha384 by default).
380
     *
381
     * @param string|Asset $asset
382
     * @param string       $algo
383
     *
384
     * @return string
385
     */
386
    public function integrity($asset, string $algo = 'sha384'): string
387
    {
388
        if (!$asset instanceof Asset) {
1✔
389
            $asset = new Asset($this->builder, $asset);
1✔
390
        }
391

392
        return $asset->getIntegrity($algo);
1✔
393
    }
394

395
    /**
396
     * Minifying a CSS string.
397
     */
398
    public function minifyCss(?string $value): string
399
    {
400
        $value = $value ?? '';
1✔
401

402
        if ($this->builder->isDebug()) {
1✔
403
            return $value;
1✔
404
        }
405

NEW
406
        $cache = new Cache($this->builder, 'assets');
×
NEW
407
        $cacheKey = $cache->createKeyFromString($value, 'css');
×
408
        if (!$cache->has($cacheKey)) {
×
409
            $minifier = new Minify\CSS($value);
×
410
            $value = $minifier->minify();
×
411
            $cache->set($cacheKey, $value);
×
412
        }
413

414
        return $cache->get($cacheKey, $value);
×
415
    }
416

417
    /**
418
     * Minifying a JavaScript string.
419
     */
420
    public function minifyJs(?string $value): string
421
    {
422
        $value = $value ?? '';
1✔
423

424
        if ($this->builder->isDebug()) {
1✔
425
            return $value;
1✔
426
        }
427

NEW
428
        $cache = new Cache($this->builder, 'assets');
×
NEW
429
        $cacheKey = $cache->createKeyFromString($value, 'js');
×
430
        if (!$cache->has($cacheKey)) {
×
431
            $minifier = new Minify\JS($value);
×
432
            $value = $minifier->minify();
×
433
            $cache->set($cacheKey, $value);
×
434
        }
435

436
        return $cache->get($cacheKey, $value);
×
437
    }
438

439
    /**
440
     * Compiles a SCSS string.
441
     *
442
     * @throws RuntimeException
443
     */
444
    public function scssToCss(?string $value): string
445
    {
446
        $value = $value ?? '';
1✔
447

448
        $cache = new Cache($this->builder, 'assets');
1✔
449
        $cacheKey = $cache->createKeyFromString($value, 'css');
1✔
450
        if (!$cache->has($cacheKey)) {
1✔
451
            $scssPhp = new Compiler();
1✔
452
            $outputStyles = ['expanded', 'compressed'];
1✔
453
            $outputStyle = strtolower((string) $this->config->get('assets.compile.style'));
1✔
454
            if (!\in_array($outputStyle, $outputStyles)) {
1✔
455
                throw new ConfigException(\sprintf('"%s" value must be "%s".', 'assets.compile.style', implode('" or "', $outputStyles)));
×
456
            }
457
            $scssPhp->setOutputStyle($outputStyle == 'compressed' ? OutputStyle::COMPRESSED : OutputStyle::EXPANDED);
1✔
458
            $variables = $this->config->get('assets.compile.variables');
1✔
459
            if (!empty($variables)) {
1✔
460
                $variables = array_map('ScssPhp\ScssPhp\ValueConverter::parseValue', $variables);
1✔
461
                $scssPhp->replaceVariables($variables);
1✔
462
            }
463
            $value = $scssPhp->compileString($value)->getCss();
1✔
464
            $cache->set($cacheKey, $value);
1✔
465
        }
466

467
        return $cache->get($cacheKey, $value);
1✔
468
    }
469

470
    /**
471
     * Creates the HTML element of an asset.
472
     *
473
     * $options[
474
     *     'preload'    => false,
475
     *     'responsive' => false,
476
     *     'formats'    => [],
477
     * ];
478
     *
479
     * @throws RuntimeException
480
     */
481
    public function html(array $context, Asset $asset, array $attributes = [], array $options = []): string
482
    {
483
        $htmlAttributes = '';
1✔
484
        $preload = false;
1✔
485
        $responsive = (bool) $this->config->get('assets.images.responsive.enabled');
1✔
486
        $formats = (array) $this->config->get('assets.images.formats');
1✔
487
        extract($options, EXTR_IF_EXISTS);
1✔
488

489
        // builds HTML attributes
490
        foreach ($attributes as $name => $value) {
1✔
491
            $attribute = \sprintf(' %s="%s"', $name, $value);
1✔
492
            if (!isset($value)) {
1✔
493
                $attribute = \sprintf(' %s', $name);
×
494
            }
495
            $htmlAttributes .= $attribute;
1✔
496
        }
497

498
        // be sure Asset file is saved
499
        $asset->save();
1✔
500

501
        // CSS or JavaScript
502
        switch ($asset['ext']) {
1✔
503
            case 'css':
1✔
504
                if ($preload) {
1✔
505
                    return \sprintf(
×
506
                        '<link href="%s" rel="preload" as="style" onload="this.onload=null;this.rel=\'stylesheet\'"%s><noscript><link rel="stylesheet" href="%1$s"%2$s></noscript>',
×
507
                        $this->url($context, $asset, $options),
×
508
                        $htmlAttributes
×
509
                    );
×
510
                }
511

512
                return \sprintf('<link rel="stylesheet" href="%s"%s>', $this->url($context, $asset, $options), $htmlAttributes);
1✔
513
            case 'js':
1✔
514
                return \sprintf('<script src="%s"%s></script>', $this->url($context, $asset, $options), $htmlAttributes);
1✔
515
        }
516
        // image
517
        if ($asset['type'] == 'image') {
1✔
518
            // responsive
519
            $sizes = '';
1✔
520
            if (
521
                $responsive && $srcset = Image::buildSrcset(
1✔
522
                    $asset,
1✔
523
                    $this->config->getAssetsImagesWidths()
1✔
524
                )
1✔
525
            ) {
UNCOV
526
                $htmlAttributes .= \sprintf(' srcset="%s"', $srcset);
×
UNCOV
527
                $sizes = Image::getSizes($attributes['class'] ?? '', $this->config->getAssetsImagesSizes());
×
UNCOV
528
                $htmlAttributes .= \sprintf(' sizes="%s"', $sizes);
×
UNCOV
529
                if ($asset['width'] > max($this->config->getAssetsImagesWidths())) {
×
530
                    $asset = $asset->resize(max($this->config->getAssetsImagesWidths()));
×
531
                }
532
            }
533

534
            // <img> element
535
            $img = \sprintf(
1✔
536
                '<img src="%s" width="' . ($asset['width'] ?: '') . '" height="' . ($asset['height'] ?: '') . '"%s>',
1✔
537
                $this->url($context, $asset, $options),
1✔
538
                $htmlAttributes
1✔
539
            );
1✔
540

541
            // multiple <source>?
542
            if (\count($formats) > 0) {
1✔
543
                $source = '';
1✔
544
                foreach ($formats as $format) {
1✔
545
                    if ($asset['subtype'] != "image/$format" && !Image::isAnimatedGif($asset)) {
1✔
546
                        try {
547
                            $assetConverted = $asset->convert($format);
1✔
548
                            // responsive?
549
                            if ($responsive && $srcset = Image::buildSrcset($assetConverted, $this->config->getAssetsImagesWidths())) {
1✔
550
                                // <source> element
UNCOV
551
                                $source .= \sprintf(
×
UNCOV
552
                                    "\n  <source type=\"image/$format\" srcset=\"%s\" sizes=\"%s\">",
×
UNCOV
553
                                    $srcset,
×
UNCOV
554
                                    $sizes
×
UNCOV
555
                                );
×
UNCOV
556
                                continue;
×
557
                            }
558
                            // <source> element
559
                            $source .= \sprintf("\n  <source type=\"image/$format\" srcset=\"%s\">", $assetConverted);
1✔
560
                        } catch (\Exception $e) {
×
561
                            $this->builder->getLogger()->error($e->getMessage());
×
562
                        }
563
                    }
564
                }
565

566
                return \sprintf("<picture>%s\n  %s\n</picture>", $source, $img);
1✔
567
            }
568

569
            return $img;
×
570
        }
571

572
        throw new RuntimeException(\sprintf('%s is available for CSS, JavaScript and images files only.', '"html" filter'));
×
573
    }
574

575
    /**
576
     * Builds the HTML img `srcset` (responsive) attribute of an image Asset.
577
     *
578
     * @throws RuntimeException
579
     */
580
    public function imageSrcset(Asset $asset): string
581
    {
582
        return Image::buildSrcset($asset, $this->config->getAssetsImagesWidths());
1✔
583
    }
584

585
    /**
586
     * Returns the HTML img `sizes` attribute based on a CSS class name.
587
     */
588
    public function imageSizes(string $class): string
589
    {
590
        return Image::getSizes($class, $this->config->getAssetsImagesSizes());
1✔
591
    }
592

593
    /**
594
     * Converts an image Asset to WebP format.
595
     */
596
    public function webp(Asset $asset, ?int $quality = null): Asset
597
    {
598
        return $this->convert($asset, 'webp', $quality);
×
599
    }
600

601
    /**
602
     * Converts an image Asset to AVIF format.
603
     */
604
    public function avif(Asset $asset, ?int $quality = null): Asset
605
    {
606
        return $this->convert($asset, 'avif', $quality);
×
607
    }
608

609
    /**
610
     * Converts an image Asset to the given format.
611
     *
612
     * @throws RuntimeException
613
     */
614
    private function convert(Asset $asset, string $format, ?int $quality = null): Asset
615
    {
616
        if ($asset['subtype'] == "image/$format") {
×
617
            return $asset;
×
618
        }
619
        if (Image::isAnimatedGif($asset)) {
×
620
            throw new RuntimeException(\sprintf('Can\'t convert the animated GIF "%s" to %s.', $asset['path'], $format));
×
621
        }
622

623
        try {
624
            return $asset->$format($quality);
×
625
        } catch (\Exception $e) {
×
626
            throw new RuntimeException(\sprintf('Can\'t convert "%s" to %s (%s).', $asset['path'], $format, $e->getMessage()));
×
627
        }
628
    }
629

630
    /**
631
     * Returns the content of an asset.
632
     */
633
    public function inline(Asset $asset): string
634
    {
635
        return $asset['content'];
1✔
636
    }
637

638
    /**
639
     * Reads $length first characters of a string and adds a suffix.
640
     */
641
    public function excerpt(?string $string, int $length = 450, string $suffix = ' …'): string
642
    {
643
        $string = $string ?? '';
1✔
644

645
        $string = str_replace('</p>', '<br><br>', $string);
1✔
646
        $string = trim(strip_tags($string, '<br>'));
1✔
647
        if (mb_strlen($string) > $length) {
1✔
648
            $string = mb_substr($string, 0, $length);
1✔
649
            $string .= $suffix;
1✔
650
        }
651

652
        return $string;
1✔
653
    }
654

655
    /**
656
     * Reads characters before or after '<!-- separator -->'.
657
     * Options:
658
     *  - separator: string to use as separator (`excerpt|break` by default)
659
     *  - capture: part to capture, `before` or `after` the separator (`before` by default).
660
     */
661
    public function excerptHtml(?string $string, array $options = []): string
662
    {
663
        $string = $string ?? '';
1✔
664

665
        $separator = (string) $this->config->get('pages.body.excerpt.separator');
1✔
666
        $capture = (string) $this->config->get('pages.body.excerpt.capture');
1✔
667
        extract($options, EXTR_IF_EXISTS);
1✔
668

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

673
        if (empty($matches)) {
1✔
674
            return $string;
×
675
        }
676
        $result = trim($matches[1]);
1✔
677
        if ($capture == 'after') {
1✔
678
            $result = trim($matches[3]);
1✔
679
        }
680
        // removes footnotes and returns result
681
        return preg_replace('/<sup[^>]*>[^u]*<\/sup>/', '', $result);
1✔
682
    }
683

684
    /**
685
     * Converts a Markdown string to HTML.
686
     *
687
     * @throws RuntimeException
688
     */
689
    public function markdownToHtml(?string $markdown): ?string
690
    {
691
        $markdown = $markdown ?? '';
1✔
692

693
        try {
694
            $parsedown = new Parsedown($this->builder);
1✔
695
            $html = $parsedown->text($markdown);
1✔
696
        } catch (\Exception) {
×
697
            throw new RuntimeException('"markdown_to_html" filter can not convert supplied Markdown.');
×
698
        }
699

700
        return $html;
1✔
701
    }
702

703
    /**
704
     * Extract table of content of a Markdown string,
705
     * in the given format ("html" or "json", "html" by default).
706
     *
707
     * @throws RuntimeException
708
     */
709
    public function markdownToToc(?string $markdown, $format = 'html', ?array $selectors = null, string $url = ''): ?string
710
    {
711
        $markdown = $markdown ?? '';
1✔
712
        $selectors = $selectors ?? (array) $this->config->get('pages.body.toc');
1✔
713

714
        try {
715
            $parsedown = new Parsedown($this->builder, ['selectors' => $selectors, 'url' => $url]);
1✔
716
            $parsedown->body($markdown);
1✔
717
            $return = $parsedown->contentsList($format);
1✔
718
        } catch (\Exception) {
×
719
            throw new RuntimeException('"toc" filter can not convert supplied Markdown.');
×
720
        }
721

722
        return $return;
1✔
723
    }
724

725
    /**
726
     * Converts a JSON string to an array.
727
     *
728
     * @throws RuntimeException
729
     */
730
    public function jsonDecode(?string $json): ?array
731
    {
732
        $json = $json ?? '';
1✔
733

734
        try {
735
            $array = json_decode($json, true);
1✔
736
            if ($array === null && json_last_error() !== JSON_ERROR_NONE) {
1✔
737
                throw new \Exception('JSON error.');
1✔
738
            }
739
        } catch (\Exception) {
×
740
            throw new RuntimeException('"json_decode" filter can not parse supplied JSON.');
×
741
        }
742

743
        return $array;
1✔
744
    }
745

746
    /**
747
     * Converts a YAML string to an array.
748
     *
749
     * @throws RuntimeException
750
     */
751
    public function yamlParse(?string $yaml): ?array
752
    {
753
        $yaml = $yaml ?? '';
1✔
754

755
        try {
756
            $array = Yaml::parse($yaml, Yaml::PARSE_DATETIME);
1✔
757
            if (!\is_array($array)) {
1✔
758
                throw new ParseException('YAML error.');
1✔
759
            }
760
        } catch (ParseException $e) {
×
761
            throw new RuntimeException(\sprintf('"yaml_parse" filter can not parse supplied YAML: %s', $e->getMessage()));
×
762
        }
763

764
        return $array;
1✔
765
    }
766

767
    /**
768
     * Split a string into an array using a regular expression.
769
     *
770
     * @throws RuntimeException
771
     */
772
    public function pregSplit(?string $value, string $pattern, int $limit = 0): ?array
773
    {
774
        $value = $value ?? '';
×
775

776
        try {
777
            $array = preg_split($pattern, $value, $limit);
×
778
            if ($array === false) {
×
779
                throw new RuntimeException('PREG split error.');
×
780
            }
781
        } catch (\Exception) {
×
782
            throw new RuntimeException('"preg_split" filter can not split supplied string.');
×
783
        }
784

785
        return $array;
×
786
    }
787

788
    /**
789
     * Perform a regular expression match and return the group for all matches.
790
     *
791
     * @throws RuntimeException
792
     */
793
    public function pregMatchAll(?string $value, string $pattern, int $group = 0): ?array
794
    {
795
        $value = $value ?? '';
×
796

797
        try {
798
            $array = preg_match_all($pattern, $value, $matches, PREG_PATTERN_ORDER);
×
799
            if ($array === false) {
×
800
                throw new RuntimeException('PREG match all error.');
×
801
            }
802
        } catch (\Exception) {
×
803
            throw new RuntimeException('"preg_match_all" filter can not match in supplied string.');
×
804
        }
805

806
        return $matches[$group];
×
807
    }
808

809
    /**
810
     * Calculates estimated time to read a text.
811
     */
812
    public function readtime(?string $text): string
813
    {
814
        $text = $text ?? '';
1✔
815

816
        $words = str_word_count(strip_tags($text));
1✔
817
        $min = floor($words / 200);
1✔
818
        if ($min === 0) {
1✔
819
            return '1';
×
820
        }
821

822
        return (string) $min;
1✔
823
    }
824

825
    /**
826
     * Gets the value of an environment variable.
827
     */
828
    public function getEnv(?string $var): ?string
829
    {
830
        $var = $var ?? '';
1✔
831

832
        return getenv($var) ?: null;
1✔
833
    }
834

835
    /**
836
     * Dump variable (or Twig context).
837
     */
838
    public function varDump(\Twig\Environment $env, array $context, $var = null, ?array $options = null): void
839
    {
840
        if (!$env->isDebug()) {
1✔
841
            return;
×
842
        }
843

844
        if ($var === null) {
1✔
845
            $var = array();
×
846
            foreach ($context as $key => $value) {
×
847
                if (!$value instanceof \Twig\Template && !$value instanceof \Twig\TemplateWrapper) {
×
848
                    $var[$key] = $value;
×
849
                }
850
            }
851
        }
852

853
        $cloner = new VarCloner();
1✔
854
        $cloner->setMinDepth(3);
1✔
855
        $dumper = new HtmlDumper();
1✔
856
        $dumper->setTheme($options['theme'] ?? 'light');
1✔
857

858
        $data = $cloner->cloneVar($var)->withMaxDepth(3);
1✔
859
        $dumper->dump($data, null, ['maxDepth' => 3]);
1✔
860
    }
861

862
    /**
863
     * Tests if a variable is an Asset.
864
     */
865
    public function isAsset($variable): bool
866
    {
867
        return $variable instanceof Asset;
1✔
868
    }
869

870
    /**
871
     * Returns the dominant hex color of an image asset.
872
     *
873
     * @param string|Asset $asset
874
     *
875
     * @return string
876
     */
877
    public function dominantColor($asset): string
878
    {
879
        if (!$asset instanceof Asset) {
1✔
880
            $asset = new Asset($this->builder, $asset);
×
881
        }
882

883
        return Image::getDominantColor($asset);
1✔
884
    }
885

886
    /**
887
     * Returns a Low Quality Image Placeholder (LQIP) as data URL.
888
     *
889
     * @param string|Asset $asset
890
     *
891
     * @return string
892
     */
893
    public function lqip($asset): string
894
    {
895
        if (!$asset instanceof Asset) {
1✔
896
            $asset = new Asset($this->builder, $asset);
×
897
        }
898

899
        return Image::getLqip($asset);
1✔
900
    }
901

902
    /**
903
     * Converts an hexadecimal color to RGB.
904
     *
905
     * @throws RuntimeException
906
     */
907
    public function hexToRgb(?string $variable): array
908
    {
909
        $variable = $variable ?? '';
1✔
910

911
        if (!self::isHex($variable)) {
1✔
912
            throw new RuntimeException(\sprintf('"%s" is not a valid hexadecimal value.', $variable));
×
913
        }
914
        $hex = ltrim($variable, '#');
1✔
915
        if (\strlen($hex) == 3) {
1✔
916
            $hex = $hex[0] . $hex[0] . $hex[1] . $hex[1] . $hex[2] . $hex[2];
×
917
        }
918
        $c = hexdec($hex);
1✔
919

920
        return [
1✔
921
            'red'   => $c >> 16 & 0xFF,
1✔
922
            'green' => $c >> 8 & 0xFF,
1✔
923
            'blue'  => $c & 0xFF,
1✔
924
        ];
1✔
925
    }
926

927
    /**
928
     * Split a string in multiple lines.
929
     */
930
    public function splitLine(?string $variable, int $max = 18): array
931
    {
932
        $variable = $variable ?? '';
1✔
933

934
        return preg_split("/.{0,{$max}}\K(\s+|$)/", $variable, 0, PREG_SPLIT_NO_EMPTY);
1✔
935
    }
936

937
    /**
938
     * Is a hexadecimal color is valid?
939
     */
940
    private static function isHex(string $hex): bool
941
    {
942
        $valid = \is_string($hex);
1✔
943
        $hex = ltrim($hex, '#');
1✔
944
        $length = \strlen($hex);
1✔
945
        $valid = $valid && ($length === 3 || $length === 6);
1✔
946
        $valid = $valid && ctype_xdigit($hex);
1✔
947

948
        return $valid;
1✔
949
    }
950
}
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