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

Cecilapp / Cecil / 7168486434

11 Dec 2023 01:57PM UTC coverage: 83.362% (+0.3%) from 83.077%
7168486434

push

github

ArnaudLigny
refactor: PHP 8 Exception

4 of 17 new or added lines in 8 files covered. (23.53%)

105 existing lines in 2 files now uncovered.

2866 of 3438 relevant lines covered (83.36%)

0.83 hits per line

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

76.97
/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\RuntimeException;
28
use Cocur\Slugify\Bridge\Twig\SlugifyExtension;
29
use Cocur\Slugify\Slugify;
30
use MatthiasMullie\Minify;
31
use ScssPhp\ScssPhp\Compiler;
32
use Symfony\Component\VarDumper\Cloner\VarCloner;
33
use Symfony\Component\VarDumper\Dumper\HtmlDumper;
34
use Symfony\Component\Yaml\Exception\ParseException;
35
use Symfony\Component\Yaml\Yaml;
36

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

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

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

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

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

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

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

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

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

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

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

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

184
        return $filteredPages;
1✔
185
    }
186

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

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

197
        return $collection;
1✔
198
    }
199

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

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

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

226
        return $collection;
1✔
227
    }
228

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

241
                return 0;
1✔
242
            }
243

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

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

250
        return $collection;
1✔
251
    }
252

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

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

275
    /**
276
     * Creates an Asset (CSS, JS, images, etc.) from a path or an array of paths.
277
     *
278
     * @param string|array $path    File path or array of files path (relative from `assets/` or `static/` dir).
279
     * @param array|null   $options
280
     *
281
     * @return Asset
282
     */
283
    public function asset($path, array $options = null): Asset
284
    {
285
        return new Asset($this->builder, $path, $options);
1✔
286
    }
287

288
    /**
289
     * Compiles a SCSS asset.
290
     *
291
     * @param string|Asset $asset
292
     *
293
     * @return Asset
294
     */
295
    public function toCss($asset): Asset
296
    {
297
        if (!$asset instanceof Asset) {
1✔
298
            $asset = new Asset($this->builder, $asset);
×
299
        }
300

301
        return $asset->compile();
1✔
302
    }
303

304
    /**
305
     * Minifying an asset (CSS or JS).
306
     *
307
     * @param string|Asset $asset
308
     *
309
     * @return Asset
310
     */
311
    public function minify($asset): Asset
312
    {
313
        if (!$asset instanceof Asset) {
1✔
314
            $asset = new Asset($this->builder, $asset);
×
315
        }
316

317
        return $asset->minify();
1✔
318
    }
319

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

333
        return $asset->fingerprint();
1✔
334
    }
335

336
    /**
337
     * Resizes an image.
338
     *
339
     * @param string|Asset $asset
340
     *
341
     * @return Asset
342
     */
343
    public function resize($asset, int $size): Asset
344
    {
345
        if (!$asset instanceof Asset) {
1✔
346
            $asset = new Asset($this->builder, $asset);
×
347
        }
348

349
        return $asset->resize($size);
1✔
350
    }
351

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

365
        return $asset->dataurl();
1✔
366
    }
367

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

382
        return $asset->getIntegrity($algo);
1✔
383
    }
384

385
    /**
386
     * Minifying a CSS string.
387
     */
388
    public function minifyCss(?string $value): string
389
    {
390
        $value = $value ?? '';
1✔
391

392
        if ($this->builder->isDebug()) {
1✔
393
            return $value;
1✔
394
        }
395

396
        $cache = new Cache($this->builder);
×
397
        $cacheKey = $cache->createKeyFromString($value);
×
398
        if (!$cache->has($cacheKey)) {
×
399
            $minifier = new Minify\CSS($value);
×
400
            $value = $minifier->minify();
×
401
            $cache->set($cacheKey, $value);
×
402
        }
403

404
        return $cache->get($cacheKey, $value);
×
405
    }
406

407
    /**
408
     * Minifying a JavaScript string.
409
     */
410
    public function minifyJs(?string $value): string
411
    {
412
        $value = $value ?? '';
1✔
413

414
        if ($this->builder->isDebug()) {
1✔
415
            return $value;
1✔
416
        }
417

418
        $cache = new Cache($this->builder);
×
419
        $cacheKey = $cache->createKeyFromString($value);
×
420
        if (!$cache->has($cacheKey)) {
×
421
            $minifier = new Minify\JS($value);
×
422
            $value = $minifier->minify();
×
423
            $cache->set($cacheKey, $value);
×
424
        }
425

426
        return $cache->get($cacheKey, $value);
×
427
    }
428

429
    /**
430
     * Compiles a SCSS string.
431
     *
432
     * @throws RuntimeException
433
     */
434
    public function scssToCss(?string $value): string
435
    {
436
        $value = $value ?? '';
1✔
437

438
        $cache = new Cache($this->builder);
1✔
439
        $cacheKey = $cache->createKeyFromString($value);
1✔
440
        if (!$cache->has($cacheKey)) {
1✔
441
            $scssPhp = new Compiler();
1✔
442
            $outputStyles = ['expanded', 'compressed'];
1✔
443
            $outputStyle = strtolower((string) $this->config->get('assets.compile.style'));
1✔
444
            if (!\in_array($outputStyle, $outputStyles)) {
1✔
445
                throw new RuntimeException(sprintf('Scss output style "%s" doesn\'t exists.', $outputStyle));
×
446
            }
447
            $scssPhp->setOutputStyle($outputStyle);
1✔
448
            $variables = $this->config->get('assets.compile.variables') ?? [];
1✔
449
            if (!empty($variables)) {
1✔
450
                $variables = array_map('ScssPhp\ScssPhp\ValueConverter::parseValue', $variables);
1✔
451
                $scssPhp->replaceVariables($variables);
1✔
452
            }
453
            $value = $scssPhp->compileString($value)->getCss();
1✔
454
            $cache->set($cacheKey, $value);
1✔
455
        }
456

457
        return $cache->get($cacheKey, $value);
1✔
458
    }
459

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

479
        // builds HTML attributes
480
        foreach ($attributes as $name => $value) {
1✔
481
            $attribute = sprintf(' %s="%s"', $name, $value);
1✔
482
            if (!isset($value)) {
1✔
483
                $attribute = sprintf(' %s', $name);
×
484
            }
485
            $htmlAttributes .= $attribute;
1✔
486
        }
487

488
        // be sure Asset file is saved
489
        $asset->save();
1✔
490

491
        // CSS or JavaScript
492
        switch ($asset['ext']) {
1✔
493
            case 'css':
1✔
494
                if ($preload) {
1✔
495
                    return sprintf(
×
496
                        '<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>',
×
497
                        $this->url($context, $asset, $options),
×
498
                        $htmlAttributes
×
499
                    );
×
500
                }
501

502
                return sprintf('<link rel="stylesheet" href="%s"%s>', $this->url($context, $asset, $options), $htmlAttributes);
1✔
503
            case 'js':
1✔
504
                return sprintf('<script src="%s"%s></script>', $this->url($context, $asset, $options), $htmlAttributes);
1✔
505
        }
506
        // image
507
        if ($asset['type'] == 'image') {
1✔
508
            // responsive
509
            $sizes = '';
1✔
510
            if (
511
                $responsive && $srcset = Image::buildSrcset(
1✔
512
                    $asset,
1✔
513
                    $this->config->getAssetsImagesWidths()
1✔
514
                )
1✔
515
            ) {
516
                $htmlAttributes .= sprintf(' srcset="%s"', $srcset);
1✔
517
                $sizes = Image::getSizes($attributes['class'] ?? '', $this->config->getAssetsImagesSizes());
1✔
518
                $htmlAttributes .= sprintf(' sizes="%s"', $sizes);
1✔
519
            }
520

521
            // <img> element
522
            $img = sprintf(
1✔
523
                '<img src="%s" width="' . ($asset['width'] ?: '') . '" height="' . ($asset['height'] ?: '') . '"%s>',
1✔
524
                $this->url($context, $asset, $options),
1✔
525
                $htmlAttributes
1✔
526
            );
1✔
527

528
            // WebP conversion?
529
            if ($webp && $asset['subtype'] != 'image/webp' && !Image::isAnimatedGif($asset)) {
1✔
530
                try {
531
                    $assetWebp = $asset->webp();
1✔
532
                    // <source> element
533
                    $source = sprintf('<source type="image/webp" srcset="%s">', $assetWebp);
1✔
534
                    // responsive
535
                    if ($responsive && $srcset = Image::buildSrcset($assetWebp, $this->config->getAssetsImagesWidths())) {
1✔
536
                        // <source> element
537
                        $source = sprintf(
1✔
538
                            '<source type="image/webp" srcset="%s" sizes="%s">',
1✔
539
                            $srcset,
1✔
540
                            $sizes
1✔
541
                        );
1✔
542
                    }
543

544
                    return sprintf("<picture>\n  %s\n  %s\n</picture>", $source, $img);
1✔
545
                } catch (\Exception $e) {
×
546
                    $this->builder->getLogger()->debug($e->getMessage());
×
547
                }
548
            }
549

550
            return $img;
×
551
        }
552

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

556
    /**
557
     * Builds the HTML img `srcset` (responsive) attribute of an image Asset.
558
     *
559
     * @throws RuntimeException
560
     */
561
    public function imageSrcset(Asset $asset): string
562
    {
563
        return Image::buildSrcset($asset, $this->config->getAssetsImagesWidths());
1✔
564
    }
565

566
    /**
567
     * Returns the HTML img `sizes` attribute based on a CSS class name.
568
     */
569
    public function imageSizes(string $class): string
570
    {
571
        return Image::getSizes($class, $this->config->getAssetsImagesSizes());
1✔
572
    }
573

574
    /**
575
     * Converts an image Asset to WebP format.
576
     *
577
     * @throws RuntimeException
578
     */
579
    public function webp(Asset $asset, ?int $quality = null): Asset
580
    {
581
        if ($asset['subtype'] == 'image/webp') {
×
582
            return $asset;
×
583
        }
584
        if (Image::isAnimatedGif($asset)) {
×
585
            throw new RuntimeException(sprintf('Can\'t convert the animated GIF "%s" to WebP.', $asset['path']));
×
586
        }
587

588
        try {
589
            return $asset->webp($quality);
×
590
        } catch (\Exception $e) {
×
591
            throw new RuntimeException(sprintf('Can\'t convert "%s" to WebP (%s).', $asset['path'], $e->getMessage()));
×
592
        }
593
    }
594

595
    /**
596
     * Returns the content of an asset.
597
     */
598
    public function inline(Asset $asset): string
599
    {
600
        return $asset['content'];
1✔
601
    }
602

603
    /**
604
     * Reads $length first characters of a string and adds a suffix.
605
     */
606
    public function excerpt(?string $string, int $length = 450, string $suffix = ' …'): string
607
    {
608
        $string = $string ?? '';
1✔
609

610
        $string = str_replace('</p>', '<br /><br />', $string);
1✔
611
        $string = trim(strip_tags($string, '<br>'), '<br />');
1✔
612
        if (mb_strlen($string) > $length) {
1✔
613
            $string = mb_substr($string, 0, $length);
1✔
614
            $string .= $suffix;
1✔
615
        }
616

617
        return $string;
1✔
618
    }
619

620
    /**
621
     * Reads characters before or after '<!-- separator -->'.
622
     * Options:
623
     *  - separator: string to use as separator (`excerpt|break` by default)
624
     *  - capture: part to capture, `before` or `after` the separator (`before` by default).
625
     */
626
    public function excerptHtml(?string $string, array $options = []): string
627
    {
628
        $string = $string ?? '';
1✔
629

630
        $separator = (string) $this->config->get('pages.body.excerpt.separator');
1✔
631
        $capture = (string) $this->config->get('pages.body.excerpt.capture');
1✔
632
        extract($options, EXTR_IF_EXISTS);
1✔
633

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

638
        if (empty($matches)) {
1✔
639
            return $string;
×
640
        }
641
        $result = trim($matches[1]);
1✔
642
        if ($capture == 'after') {
1✔
643
            $result = trim($matches[3]);
1✔
644
        }
645
        // removes footnotes and returns result
646
        return preg_replace('/<sup[^>]*>[^u]*<\/sup>/', '', $result);
1✔
647
    }
648

649
    /**
650
     * Converts a Markdown string to HTML.
651
     *
652
     * @throws RuntimeException
653
     */
654
    public function markdownToHtml(?string $markdown): ?string
655
    {
656
        $markdown = $markdown ?? '';
1✔
657

658
        try {
659
            $parsedown = new Parsedown($this->builder);
1✔
660
            $html = $parsedown->text($markdown);
1✔
NEW
661
        } catch (\Exception) {
×
662
            throw new RuntimeException('"markdown_to_html" filter can not convert supplied Markdown.');
×
663
        }
664

665
        return $html;
1✔
666
    }
667

668
    /**
669
     * Extract table of content of a Markdown string,
670
     * in the given format ("html" or "json", "html" by default).
671
     *
672
     * @throws RuntimeException
673
     */
674
    public function markdownToToc(?string $markdown, $format = 'html', $url = ''): ?string
675
    {
676
        $markdown = $markdown ?? '';
1✔
677

678
        try {
679
            $parsedown = new Parsedown($this->builder, ['selectors' => ['h2'], 'url' => $url]);
1✔
680
            $parsedown->body($markdown);
1✔
681
            $return = $parsedown->contentsList($format);
1✔
NEW
682
        } catch (\Exception) {
×
683
            throw new RuntimeException('"toc" filter can not convert supplied Markdown.');
×
684
        }
685

686
        return $return;
1✔
687
    }
688

689
    /**
690
     * Converts a JSON string to an array.
691
     *
692
     * @throws RuntimeException
693
     */
694
    public function jsonDecode(?string $json): ?array
695
    {
696
        $json = $json ?? '';
1✔
697

698
        try {
699
            $array = json_decode($json, true);
1✔
700
            if ($array === null && json_last_error() !== JSON_ERROR_NONE) {
1✔
701
                throw new \Exception('JSON error.');
1✔
702
            }
NEW
703
        } catch (\Exception) {
×
704
            throw new RuntimeException('"json_decode" filter can not parse supplied JSON.');
×
705
        }
706

707
        return $array;
1✔
708
    }
709

710
    /**
711
     * Converts a YAML string to an array.
712
     *
713
     * @throws RuntimeException
714
     */
715
    public function yamlParse(?string $yaml): ?array
716
    {
717
        $yaml = $yaml ?? '';
1✔
718

719
        try {
720
            $array = Yaml::parse($yaml);
1✔
721
            if (!\is_array($array)) {
1✔
722
                throw new ParseException('YAML error.');
1✔
723
            }
724
        } catch (ParseException $e) {
×
725
            throw new RuntimeException(sprintf('"yaml_parse" filter can not parse supplied YAML: %s', $e->getMessage()));
×
726
        }
727

728
        return $array;
1✔
729
    }
730

731
    /**
732
     * Split a string into an array using a regular expression.
733
     *
734
     * @throws RuntimeException
735
     */
736
    public function pregSplit(?string $value, string $pattern, int $limit = 0): ?array
737
    {
738
        $value = $value ?? '';
×
739

740
        try {
741
            $array = preg_split($pattern, $value, $limit);
×
742
            if ($array === false) {
×
743
                throw new RuntimeException('PREG split error.');
×
744
            }
NEW
745
        } catch (\Exception) {
×
746
            throw new RuntimeException('"preg_split" filter can not split supplied string.');
×
747
        }
748

749
        return $array;
×
750
    }
751

752
    /**
753
     * Perform a regular expression match and return the group for all matches.
754
     *
755
     * @throws RuntimeException
756
     */
757
    public function pregMatchAll(?string $value, string $pattern, int $group = 0): ?array
758
    {
759
        $value = $value ?? '';
×
760

761
        try {
762
            $array = preg_match_all($pattern, $value, $matches, PREG_PATTERN_ORDER);
×
763
            if ($array === false) {
×
764
                throw new RuntimeException('PREG match all error.');
×
765
            }
NEW
766
        } catch (\Exception) {
×
767
            throw new RuntimeException('"preg_match_all" filter can not match in supplied string.');
×
768
        }
769

770
        return $matches[$group];
×
771
    }
772

773
    /**
774
     * Calculates estimated time to read a text.
775
     */
776
    public function readtime(?string $text): string
777
    {
778
        $text = $text ?? '';
1✔
779

780
        $words = str_word_count(strip_tags($text));
1✔
781
        $min = floor($words / 200);
1✔
782
        if ($min === 0) {
1✔
783
            return '1';
×
784
        }
785

786
        return (string) $min;
1✔
787
    }
788

789
    /**
790
     * Gets the value of an environment variable.
791
     */
792
    public function getEnv(?string $var): ?string
793
    {
794
        $var = $var ?? '';
1✔
795

796
        return getenv($var) ?: null;
1✔
797
    }
798

799
    /**
800
     * Dump variable (or Twig context).
801
     */
802
    public function varDump(\Twig\Environment $env, array $context, $var = null, ?array $options = null): void
803
    {
804
        if (!$env->isDebug()) {
1✔
805
            return;
×
806
        }
807

808
        if ($var === null) {
1✔
809
            $var = array();
×
810
            foreach ($context as $key => $value) {
×
811
                if (!$value instanceof \Twig\Template && !$value instanceof \Twig\TemplateWrapper) {
×
812
                    $var[$key] = $value;
×
813
                }
814
            }
815
        }
816

817
        $cloner = new VarCloner();
1✔
818
        $cloner->setMinDepth(4);
1✔
819
        $dumper = new HtmlDumper();
1✔
820
        $dumper->setTheme($options['theme'] ?? 'light');
1✔
821

822
        $data = $cloner->cloneVar($var)->withMaxDepth(4);
1✔
823
        $dumper->dump($data, null, ['maxDepth' => 4]);
1✔
824
    }
825

826
    /**
827
     * Tests if a variable is an Asset.
828
     */
829
    public function isAsset($variable): bool
830
    {
831
        return $variable instanceof Asset;
×
832
    }
833

834
    /**
835
     * Returns the dominant hex color of an image asset.
836
     *
837
     * @param string|Asset $asset
838
     *
839
     * @return string
840
     */
841
    public function dominantColor($asset): string
842
    {
843
        if (!$asset instanceof Asset) {
1✔
844
            $asset = new Asset($this->builder, $asset);
×
845
        }
846

847
        return Image::getDominantColor($asset);
1✔
848
    }
849

850
    /**
851
     * Returns a Low Quality Image Placeholder (LQIP) as data URL.
852
     *
853
     * @param string|Asset $asset
854
     *
855
     * @return string
856
     */
857
    public function lqip($asset): string
858
    {
859
        if (!$asset instanceof Asset) {
1✔
860
            $asset = new Asset($this->builder, $asset);
×
861
        }
862

863
        return Image::getLqip($asset);
1✔
864
    }
865

866
    /**
867
     * Converts an hexadecimal color to RGB.
868
     *
869
     * @throws RuntimeException
870
     */
871
    public function hexToRgb(?string $variable): array
872
    {
873
        $variable = $variable ?? '';
1✔
874

875
        if (!self::isHex($variable)) {
1✔
876
            throw new RuntimeException(sprintf('"%s" is not a valid hexadecimal value.', $variable));
×
877
        }
878
        $hex = ltrim($variable, '#');
1✔
879
        if (\strlen($hex) == 3) {
1✔
880
            $hex = $hex[0] . $hex[0] . $hex[1] . $hex[1] . $hex[2] . $hex[2];
×
881
        }
882
        $c = hexdec($hex);
1✔
883

884
        return [
1✔
885
            'red'   => $c >> 16 & 0xFF,
1✔
886
            'green' => $c >> 8 & 0xFF,
1✔
887
            'blue'  => $c & 0xFF,
1✔
888
        ];
1✔
889
    }
890

891
    /**
892
     * Split a string in multiple lines.
893
     */
894
    public function splitLine(?string $variable, int $max = 18): array
895
    {
896
        $variable = $variable ?? '';
1✔
897

898
        return preg_split("/.{0,{$max}}\K(\s+|$)/", $variable, 0, PREG_SPLIT_NO_EMPTY);
1✔
899
    }
900

901
    /**
902
     * Is a hexadecimal color is valid?
903
     */
904
    private static function isHex(string $hex): bool
905
    {
906
        $valid = \is_string($hex);
1✔
907
        $hex = ltrim($hex, '#');
1✔
908
        $length = \strlen($hex);
1✔
909
        $valid = $valid && ($length === 3 || $length === 6);
1✔
910
        $valid = $valid && ctype_xdigit($hex);
1✔
911

912
        return $valid;
1✔
913
    }
914
}
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