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

Cecilapp / Cecil / 10080147305

24 Jul 2024 04:07PM UTC coverage: 83.47%. First build
10080147305

Pull #2017

github

web-flow
Merge 626ba7463 into a8f2266d1
Pull Request #2017: feat: multiple image formats support (webp, avif)

49 of 64 new or added lines in 4 files covered. (76.56%)

2954 of 3539 relevant lines covered (83.47%)

0.83 hits per line

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

76.32
/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 Symfony\Component\VarDumper\Cloner\VarCloner;
34
use Symfony\Component\VarDumper\Dumper\HtmlDumper;
35
use Symfony\Component\Yaml\Exception\ParseException;
36
use Symfony\Component\Yaml\Yaml;
37

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

46
    /** @var Config */
47
    protected $config;
48

49
    /** @var Slugify */
50
    private static $slugifier;
51

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

58
        parent::__construct(self::$slugifier);
1✔
59

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

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

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

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

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

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

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

186
        return $filteredPages;
1✔
187
    }
188

189
    /**
190
     * Sorts a collection by title.
191
     */
192
    public function sortByTitle(\Traversable $collection): array
193
    {
194
        $sort = \SORT_ASC;
1✔
195

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

199
        return $collection;
1✔
200
    }
201

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

220
            return $a['weight'] < $b['weight'] ? -1 : 1;
1✔
221
        };
1✔
222

223
        if (!\is_array($collection)) {
1✔
224
            $collection = iterator_to_array($collection);
1✔
225
        }
226
        usort(/** @scrutinizer ignore-type */ $collection, $callback);
1✔
227

228
        return $collection;
1✔
229
    }
230

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

243
                return 0;
1✔
244
            }
245

246
            return $a[$variable] > $b[$variable] ? -1 : 1;
1✔
247
        };
1✔
248

249
        $collection = iterator_to_array($collection);
1✔
250
        usort(/** @scrutinizer ignore-type */ $collection, $callback);
1✔
251

252
        return $collection;
1✔
253
    }
254

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

274
        return (new Url($this->builder, $value, $options))->getUrl();
1✔
275
    }
276

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

291
        return new Asset($this->builder, $path, $options);
1✔
292
    }
293

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

307
        return $asset->compile();
1✔
308
    }
309

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

323
        return $asset->minify();
1✔
324
    }
325

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

339
        return $asset->fingerprint();
1✔
340
    }
341

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

355
        return $asset->resize($size);
1✔
356
    }
357

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

371
        return $asset->dataurl();
1✔
372
    }
373

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

388
        return $asset->getIntegrity($algo);
1✔
389
    }
390

391
    /**
392
     * Minifying a CSS string.
393
     */
394
    public function minifyCss(?string $value): string
395
    {
396
        $value = $value ?? '';
1✔
397

398
        if ($this->builder->isDebug()) {
1✔
399
            return $value;
1✔
400
        }
401

402
        $cache = new Cache($this->builder);
×
403
        $cacheKey = $cache->createKeyFromString($value);
×
404
        if (!$cache->has($cacheKey)) {
×
405
            $minifier = new Minify\CSS($value);
×
406
            $value = $minifier->minify();
×
407
            $cache->set($cacheKey, $value);
×
408
        }
409

410
        return $cache->get($cacheKey, $value);
×
411
    }
412

413
    /**
414
     * Minifying a JavaScript string.
415
     */
416
    public function minifyJs(?string $value): string
417
    {
418
        $value = $value ?? '';
1✔
419

420
        if ($this->builder->isDebug()) {
1✔
421
            return $value;
1✔
422
        }
423

424
        $cache = new Cache($this->builder);
×
425
        $cacheKey = $cache->createKeyFromString($value);
×
426
        if (!$cache->has($cacheKey)) {
×
427
            $minifier = new Minify\JS($value);
×
428
            $value = $minifier->minify();
×
429
            $cache->set($cacheKey, $value);
×
430
        }
431

432
        return $cache->get($cacheKey, $value);
×
433
    }
434

435
    /**
436
     * Compiles a SCSS string.
437
     *
438
     * @throws RuntimeException
439
     */
440
    public function scssToCss(?string $value): string
441
    {
442
        $value = $value ?? '';
1✔
443

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

463
        return $cache->get($cacheKey, $value);
1✔
464
    }
465

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

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

494
        // be sure Asset file is saved
495
        $asset->save();
1✔
496

497
        // CSS or JavaScript
498
        switch ($asset['ext']) {
1✔
499
            case 'css':
1✔
500
                if ($preload) {
1✔
501
                    return sprintf(
×
502
                        '<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>',
×
503
                        $this->url($context, $asset, $options),
×
504
                        $htmlAttributes
×
505
                    );
×
506
                }
507

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

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

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

562
                return sprintf("<picture>%s\n  %s\n</picture>", $source, $img);
1✔
563
            }
564

565
            return $img;
×
566
        }
567

568
        throw new RuntimeException(sprintf('%s is available for CSS, JavaScript and images files only.', '"html" filter'));
×
569
    }
570

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

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

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

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

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

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

626
    /**
627
     * Returns the content of an asset.
628
     */
629
    public function inline(Asset $asset): string
630
    {
631
        return $asset['content'];
1✔
632
    }
633

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

641
        $string = str_replace('</p>', '<br /><br />', $string);
1✔
642
        $string = trim(strip_tags($string, '<br>'), '<br />');
1✔
643
        if (mb_strlen($string) > $length) {
1✔
644
            $string = mb_substr($string, 0, $length);
1✔
645
            $string .= $suffix;
1✔
646
        }
647

648
        return $string;
1✔
649
    }
650

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

661
        $separator = (string) $this->config->get('pages.body.excerpt.separator');
1✔
662
        $capture = (string) $this->config->get('pages.body.excerpt.capture');
1✔
663
        extract($options, EXTR_IF_EXISTS);
1✔
664

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

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

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

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

696
        return $html;
1✔
697
    }
698

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

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

718
        return $return;
1✔
719
    }
720

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

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

739
        return $array;
1✔
740
    }
741

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

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

760
        return $array;
1✔
761
    }
762

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

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

781
        return $array;
×
782
    }
783

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

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

802
        return $matches[$group];
×
803
    }
804

805
    /**
806
     * Calculates estimated time to read a text.
807
     */
808
    public function readtime(?string $text): string
809
    {
810
        $text = $text ?? '';
1✔
811

812
        $words = str_word_count(strip_tags($text));
1✔
813
        $min = floor($words / 200);
1✔
814
        if ($min === 0) {
1✔
815
            return '1';
×
816
        }
817

818
        return (string) $min;
1✔
819
    }
820

821
    /**
822
     * Gets the value of an environment variable.
823
     */
824
    public function getEnv(?string $var): ?string
825
    {
826
        $var = $var ?? '';
1✔
827

828
        return getenv($var) ?: null;
1✔
829
    }
830

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

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

849
        $cloner = new VarCloner();
1✔
850
        $cloner->setMinDepth(3);
1✔
851
        $dumper = new HtmlDumper();
1✔
852
        $dumper->setTheme($options['theme'] ?? 'light');
1✔
853

854
        $data = $cloner->cloneVar($var)->withMaxDepth(3);
1✔
855
        $dumper->dump($data, null, ['maxDepth' => 3]);
1✔
856
    }
857

858
    /**
859
     * Tests if a variable is an Asset.
860
     */
861
    public function isAsset($variable): bool
862
    {
863
        return $variable instanceof Asset;
×
864
    }
865

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

879
        return Image::getDominantColor($asset);
1✔
880
    }
881

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

895
        return Image::getLqip($asset);
1✔
896
    }
897

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

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

916
        return [
1✔
917
            'red'   => $c >> 16 & 0xFF,
1✔
918
            'green' => $c >> 8 & 0xFF,
1✔
919
            'blue'  => $c & 0xFF,
1✔
920
        ];
1✔
921
    }
922

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

930
        return preg_split("/.{0,{$max}}\K(\s+|$)/", $variable, 0, PREG_SPLIT_NO_EMPTY);
1✔
931
    }
932

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

944
        return $valid;
1✔
945
    }
946
}
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