Passed
Push — feat/lqip ( b3bc07...82f790 )
by Arnaud
05:16 queued 01:11
created

Core   F

Complexity

Total Complexity 109

Size/Duplication

Total Lines 852
Duplicated Lines 0 %

Importance

Changes 4
Bugs 1 Features 1
Metric Value
eloc 344
c 4
b 1
f 1
dl 0
loc 852
rs 2
wmc 109

39 Methods

Rating   Name   Duplication   Size   Complexity  
A getFunctions() 0 26 1
A __construct() 0 10 2
A getName() 0 3 1
A filterBySection() 0 3 1
A inline() 0 3 1
A sortByDate() 0 19 6
A excerpt() 0 12 2
A dataurl() 0 7 2
A isAsset() 0 3 1
A fingerprint() 0 7 2
B filterBy() 0 15 8
A getEnv() 0 5 2
A minify() 0 7 2
A hexToRgb() 0 17 3
A minifyCss() 0 17 3
A asset() 0 3 1
A readtime() 0 11 2
A sortByWeight() 0 20 5
A lqip() 0 7 2
A pregSplit() 0 14 3
A url() 0 3 1
B getFilters() 0 85 1
A sortByTitle() 0 8 1
A jsonDecode() 0 14 4
A markdownToToc() 0 13 2
A dominantColor() 0 7 2
A toCss() 0 7 2
A scssToCss() 0 24 4
A integrity() 0 7 2
A resize() 0 7 2
A isHex() 0 9 4
A yamlParse() 0 14 3
A splitLine() 0 5 1
A markdownToHtml() 0 12 2
A minifyJs() 0 17 3
A getTests() 0 4 1
D html() 0 90 18
A pregMatchAll() 0 14 3
A excerptHtml() 0 21 3

How to fix   Complexity   

Complex Class

Complex classes like Core often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use Core, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of Cecil.
7
 *
8
 * Copyright (c) Arnaud Ligny <[email protected]>
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\Yaml\Exception\ParseException;
33
use Symfony\Component\Yaml\Yaml;
34
35
/**
36
 * Class Renderer\Extension\Core.
37
 */
38
class Core extends SlugifyExtension
39
{
40
    /** @var Builder */
41
    protected $builder;
42
43
    /** @var Config */
44
    protected $config;
45
46
    /** @var Slugify */
47
    private static $slugifier;
48
49
    public function __construct(Builder $builder)
50
    {
51
        if (!self::$slugifier instanceof Slugify) {
52
            self::$slugifier = Slugify::create(['regexp' => Page::SLUGIFY_PATTERN]);
53
        }
54
55
        parent::__construct(self::$slugifier);
56
57
        $this->builder = $builder;
58
        $this->config = $this->builder->getConfig();
59
    }
60
61
    /**
62
     * {@inheritdoc}
63
     */
64
    public function getName()
65
    {
66
        return 'CoreExtension';
67
    }
68
69
    /**
70
     * {@inheritdoc}
71
     */
72
    public function getFunctions()
73
    {
74
        return [
75
            new \Twig\TwigFunction('url', [$this, 'url']),
76
            // assets
77
            new \Twig\TwigFunction('asset', [$this, 'asset']),
78
            new \Twig\TwigFunction('integrity', [$this, 'integrity']),
79
            // content
80
            new \Twig\TwigFunction('readtime', [$this, 'readtime']),
81
            // others
82
            new \Twig\TwigFunction('getenv', [$this, 'getEnv']),
83
            // deprecated
84
            new \Twig\TwigFunction(
85
                'hash',
86
                [$this, 'integrity'],
87
                ['deprecated' => true, 'alternative' => 'integrity']
88
            ),
89
            new \Twig\TwigFunction(
90
                'minify',
91
                [$this, 'minify'],
92
                ['deprecated' => true, 'alternative' => 'minify filter']
93
            ),
94
            new \Twig\TwigFunction(
95
                'toCSS',
96
                [$this, 'toCss'],
97
                ['deprecated' => true, 'alternative' => 'to_css filter']
98
            ),
99
        ];
100
    }
101
102
    /**
103
     * {@inheritdoc}
104
     */
105
    public function getFilters()
106
    {
107
        return [
108
            new \Twig\TwigFilter('url', [$this, 'url']),
109
            // collections
110
            new \Twig\TwigFilter('sort_by_title', [$this, 'sortByTitle']),
111
            new \Twig\TwigFilter('sort_by_weight', [$this, 'sortByWeight']),
112
            new \Twig\TwigFilter('sort_by_date', [$this, 'sortByDate']),
113
            new \Twig\TwigFilter('filter_by', [$this, 'filterBy']),
114
            // assets
115
            new \Twig\TwigFilter('html', [$this, 'html']),
116
            new \Twig\TwigFilter('inline', [$this, 'inline']),
117
            new \Twig\TwigFilter('fingerprint', [$this, 'fingerprint']),
118
            new \Twig\TwigFilter('to_css', [$this, 'toCss']),
119
            new \Twig\TwigFilter('minify', [$this, 'minify']),
120
            new \Twig\TwigFilter('minify_css', [$this, 'minifyCss']),
121
            new \Twig\TwigFilter('minify_js', [$this, 'minifyJs']),
122
            new \Twig\TwigFilter('scss_to_css', [$this, 'scssToCss']),
123
            new \Twig\TwigFilter('sass_to_css', [$this, 'scssToCss']),
124
            new \Twig\TwigFilter('resize', [$this, 'resize']),
125
            new \Twig\TwigFilter('dataurl', [$this, 'dataurl']),
126
            new \Twig\TwigFilter('dominant_color', [$this, 'dominantColor']),
127
            new \Twig\TwigFilter('lqip', [$this, 'lqip']),
128
            // content
129
            new \Twig\TwigFilter('slugify', [$this, 'slugifyFilter']),
130
            new \Twig\TwigFilter('excerpt', [$this, 'excerpt']),
131
            new \Twig\TwigFilter('excerpt_html', [$this, 'excerptHtml']),
132
            new \Twig\TwigFilter('markdown_to_html', [$this, 'markdownToHtml']),
133
            new \Twig\TwigFilter('toc', [$this, 'markdownToToc']),
134
            new \Twig\TwigFilter('json_decode', [$this, 'jsonDecode']),
135
            new \Twig\TwigFilter('yaml_parse', [$this, 'yamlParse']),
136
            new \Twig\TwigFilter('preg_split', [$this, 'pregSplit']),
137
            new \Twig\TwigFilter('preg_match_all', [$this, 'pregMatchAll']),
138
            new \Twig\TwigFilter('hex_to_rgb', [$this, 'hexToRgb']),
139
            new \Twig\TwigFilter('splitline', [$this, 'splitLine']),
140
            // deprecated
141
            new \Twig\TwigFilter(
142
                'filterBySection',
143
                [$this, 'filterBySection'],
144
                ['deprecated' => true, 'alternative' => 'filter_by']
145
            ),
146
            new \Twig\TwigFilter(
147
                'filterBy',
148
                [$this, 'filterBy'],
149
                ['deprecated' => true, 'alternative' => 'filter_by']
150
            ),
151
            new \Twig\TwigFilter(
152
                'sortByTitle',
153
                [$this, 'sortByTitle'],
154
                ['deprecated' => true, 'alternative' => 'sort_by_title']
155
            ),
156
            new \Twig\TwigFilter(
157
                'sortByWeight',
158
                [$this, 'sortByWeight'],
159
                ['deprecated' => true, 'alternative' => 'sort_by_weight']
160
            ),
161
            new \Twig\TwigFilter(
162
                'sortByDate',
163
                [$this, 'sortByDate'],
164
                ['deprecated' => true, 'alternative' => 'sort_by_date']
165
            ),
166
            new \Twig\TwigFilter(
167
                'minifyCSS',
168
                [$this, 'minifyCss'],
169
                ['deprecated' => true, 'alternative' => 'minifyCss']
170
            ),
171
            new \Twig\TwigFilter(
172
                'minifyJS',
173
                [$this, 'minifyJs'],
174
                ['deprecated' => true, 'alternative' => 'minifyJs']
175
            ),
176
            new \Twig\TwigFilter(
177
                'SCSStoCSS',
178
                [$this, 'scssToCss'],
179
                ['deprecated' => true, 'alternative' => 'scss_to_css']
180
            ),
181
            new \Twig\TwigFilter(
182
                'excerptHtml',
183
                [$this, 'excerptHtml'],
184
                ['deprecated' => true, 'alternative' => 'excerpt_html']
185
            ),
186
            new \Twig\TwigFilter(
187
                'urlize',
188
                [$this, 'slugifyFilter'],
189
                ['deprecated' => true, 'alternative' => 'slugify']
190
            ),
191
        ];
192
    }
193
194
    /**
195
     * {@inheritdoc}
196
     */
197
    public function getTests()
198
    {
199
        return [
200
            new \Twig\TwigTest('asset', [$this, 'isAsset']),
201
        ];
202
    }
203
204
    /**
205
     * Filters by Section.
206
     */
207
    public function filterBySection(PagesCollection $pages, string $section): CollectionInterface
208
    {
209
        return $this->filterBy($pages, 'section', $section);
210
    }
211
212
    /**
213
     * Filters a pages collection by variable's name/value.
214
     */
215
    public function filterBy(PagesCollection $pages, string $variable, string $value): CollectionInterface
216
    {
217
        $filteredPages = $pages->filter(function (Page $page) use ($variable, $value) {
218
            // is a dedicated getter exists?
219
            $method = 'get' . ucfirst($variable);
220
            if (method_exists($page, $method) && $page->$method() == $value) {
221
                return $page->getType() == Type::PAGE() && !$page->isVirtual() && true;
222
            }
223
            // or a classic variable
224
            if ($page->getVariable($variable) == $value) {
225
                return $page->getType() == Type::PAGE() && !$page->isVirtual() && true;
226
            }
227
        });
228
229
        return $filteredPages;
230
    }
231
232
    /**
233
     * Sorts a collection by title.
234
     */
235
    public function sortByTitle(\Traversable $collection): array
236
    {
237
        $sort = \SORT_ASC;
238
239
        $collection = iterator_to_array($collection);
240
        array_multisort(array_keys(/** @scrutinizer ignore-type */ $collection), $sort, \SORT_NATURAL | \SORT_FLAG_CASE, $collection);
0 ignored issues
show
Bug introduced by
array_keys($collection) cannot be passed to array_multisort() as the parameter $array expects a reference. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

240
        array_multisort(/** @scrutinizer ignore-type */ array_keys(/** @scrutinizer ignore-type */ $collection), $sort, \SORT_NATURAL | \SORT_FLAG_CASE, $collection);
Loading history...
Bug introduced by
SORT_NATURAL | SORT_FLAG_CASE cannot be passed to array_multisort() as the parameter $rest expects a reference. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

240
        array_multisort(array_keys(/** @scrutinizer ignore-type */ $collection), $sort, /** @scrutinizer ignore-type */ \SORT_NATURAL | \SORT_FLAG_CASE, $collection);
Loading history...
241
242
        return $collection;
243
    }
244
245
    /**
246
     * Sorts a collection by weight.
247
     */
248
    public function sortByWeight(\Traversable $collection): array
249
    {
250
        $callback = function ($a, $b) {
251
            if (!isset($a['weight'])) {
252
                $a['weight'] = 0;
253
            }
254
            if (!isset($b['weight'])) {
255
                $a['weight'] = 0;
256
            }
257
            if ($a['weight'] == $b['weight']) {
258
                return 0;
259
            }
260
261
            return $a['weight'] < $b['weight'] ? -1 : 1;
262
        };
263
264
        $collection = iterator_to_array($collection);
265
        usort(/** @scrutinizer ignore-type */ $collection, $callback);
266
267
        return $collection;
268
    }
269
270
    /**
271
     * Sorts by creation date (or 'updated' date): the most recent first.
272
     */
273
    public function sortByDate(\Traversable $collection, string $variable = 'date', bool $descTitle = false): array
274
    {
275
        $callback = function ($a, $b) use ($variable, $descTitle) {
276
            if ($a[$variable] == $b[$variable]) {
277
                // if dates are equal and "descTitle" is true
278
                if ($descTitle && (isset($a['title']) && isset($b['title']))) {
279
                    return strnatcmp($b['title'], $a['title']);
280
                }
281
282
                return 0;
283
            }
284
285
            return $a[$variable] > $b[$variable] ? -1 : 1;
286
        };
287
288
        $collection = iterator_to_array($collection);
289
        usort(/** @scrutinizer ignore-type */ $collection, $callback);
290
291
        return $collection;
292
    }
293
294
    /**
295
     * Creates an URL.
296
     *
297
     * $options[
298
     *     'canonical' => false,
299
     *     'format'    => 'html',
300
     *     'language'  => null,
301
     * ];
302
     *
303
     * @param Page|Asset|string|null $value
304
     * @param array|null             $options
305
     */
306
    public function url($value = null, array $options = null): string
307
    {
308
        return (new Url($this->builder, $value, $options))->getUrl();
309
    }
310
311
    /**
312
     * Creates an Asset (CSS, JS, images, etc.) from a path or an array of paths.
313
     *
314
     * @param string|array $path    File path or array of files path (relative from `assets/` or `static/` dir).
315
     * @param array|null   $options
316
     *
317
     * @return Asset
318
     */
319
    public function asset($path, array $options = null): Asset
320
    {
321
        return new Asset($this->builder, $path, $options);
322
    }
323
324
    /**
325
     * Compiles a SCSS asset.
326
     *
327
     * @param string|Asset $asset
328
     *
329
     * @return Asset
330
     */
331
    public function toCss($asset): Asset
332
    {
333
        if (!$asset instanceof Asset) {
334
            $asset = new Asset($this->builder, $asset);
335
        }
336
337
        return $asset->compile();
338
    }
339
340
    /**
341
     * Minifying an asset (CSS or JS).
342
     *
343
     * @param string|Asset $asset
344
     *
345
     * @return Asset
346
     */
347
    public function minify($asset): Asset
348
    {
349
        if (!$asset instanceof Asset) {
350
            $asset = new Asset($this->builder, $asset);
351
        }
352
353
        return $asset->minify();
354
    }
355
356
    /**
357
     * Fingerprinting an asset.
358
     *
359
     * @param string|Asset $asset
360
     *
361
     * @return Asset
362
     */
363
    public function fingerprint($asset): Asset
364
    {
365
        if (!$asset instanceof Asset) {
366
            $asset = new Asset($this->builder, $asset);
367
        }
368
369
        return $asset->fingerprint();
370
    }
371
372
    /**
373
     * Resizes an image.
374
     *
375
     * @param string|Asset $asset
376
     *
377
     * @return Asset
378
     */
379
    public function resize($asset, int $size): Asset
380
    {
381
        if (!$asset instanceof Asset) {
382
            $asset = new Asset($this->builder, $asset);
383
        }
384
385
        return $asset->resize($size);
386
    }
387
388
    /**
389
     * Returns the data URL of an image.
390
     *
391
     * @param string|Asset $asset
392
     *
393
     * @return string
394
     */
395
    public function dataurl($asset): string
396
    {
397
        if (!$asset instanceof Asset) {
398
            $asset = new Asset($this->builder, $asset);
399
        }
400
401
        return $asset->dataurl();
402
    }
403
404
    /**
405
     * Hashing an asset with algo (sha384 by default).
406
     *
407
     * @param string|Asset $asset
408
     * @param string       $algo
409
     *
410
     * @return string
411
     */
412
    public function integrity($asset, string $algo = 'sha384'): string
413
    {
414
        if (!$asset instanceof Asset) {
415
            $asset = new Asset($this->builder, $asset);
416
        }
417
418
        return $asset->getIntegrity($algo);
419
    }
420
421
    /**
422
     * Minifying a CSS string.
423
     */
424
    public function minifyCss(?string $value): string
425
    {
426
        $value = $value ?? '';
427
428
        if ($this->builder->isDebug()) {
429
            return $value;
430
        }
431
432
        $cache = new Cache($this->builder);
433
        $cacheKey = $cache->createKeyFromString($value);
434
        if (!$cache->has($cacheKey)) {
435
            $minifier = new Minify\CSS($value);
436
            $value = $minifier->minify();
437
            $cache->set($cacheKey, $value);
438
        }
439
440
        return $cache->get($cacheKey, $value);
441
    }
442
443
    /**
444
     * Minifying a JavaScript string.
445
     */
446
    public function minifyJs(?string $value): string
447
    {
448
        $value = $value ?? '';
449
450
        if ($this->builder->isDebug()) {
451
            return $value;
452
        }
453
454
        $cache = new Cache($this->builder);
455
        $cacheKey = $cache->createKeyFromString($value);
456
        if (!$cache->has($cacheKey)) {
457
            $minifier = new Minify\JS($value);
458
            $value = $minifier->minify();
459
            $cache->set($cacheKey, $value);
460
        }
461
462
        return $cache->get($cacheKey, $value);
463
    }
464
465
    /**
466
     * Compiles a SCSS string.
467
     *
468
     * @throws RuntimeException
469
     */
470
    public function scssToCss(?string $value): string
471
    {
472
        $value = $value ?? '';
473
474
        $cache = new Cache($this->builder);
475
        $cacheKey = $cache->createKeyFromString($value);
476
        if (!$cache->has($cacheKey)) {
477
            $scssPhp = new Compiler();
478
            $outputStyles = ['expanded', 'compressed'];
479
            $outputStyle = strtolower((string) $this->config->get('assets.compile.style'));
480
            if (!in_array($outputStyle, $outputStyles)) {
481
                throw new RuntimeException(\sprintf('Scss output style "%s" doesn\'t exists.', $outputStyle));
482
            }
483
            $scssPhp->setOutputStyle($outputStyle);
484
            $variables = $this->config->get('assets.compile.variables') ?? [];
485
            if (!empty($variables)) {
486
                $variables = array_map('ScssPhp\ScssPhp\ValueConverter::parseValue', $variables);
487
                $scssPhp->replaceVariables($variables);
488
            }
489
            $value = $scssPhp->compileString($value)->getCss();
490
            $cache->set($cacheKey, $value);
491
        }
492
493
        return $cache->get($cacheKey, $value);
494
    }
495
496
    /**
497
     * Creates the HTML element of an asset.
498
     *
499
     * $options[
500
     *     'preload'    => false,
501
     *     'responsive' => false,
502
     *     'webp'       => false,
503
     * ];
504
     *
505
     * @throws RuntimeException
506
     */
507
    public function html(Asset $asset, array $attributes = [], array $options = []): string
508
    {
509
        $htmlAttributes = '';
510
        $preload = false;
511
        $responsive = (bool) $this->config->get('assets.images.responsive.enabled') ?? false;
512
        $webp = (bool) $this->config->get('assets.images.webp.enabled') ?? false;
513
        extract($options, EXTR_IF_EXISTS);
514
515
        // builds HTML attributes
516
        foreach ($attributes as $name => $value) {
517
            $attribute = \sprintf(' %s="%s"', $name, $value);
518
            if (empty($value)) {
519
                $attribute = \sprintf(' %s', $name);
520
            }
521
            $htmlAttributes .= $attribute;
522
        }
523
524
        // be sure Asset file is saved
525
        $asset->save();
526
527
        // CSS or JavaScript
528
        switch ($asset['ext']) {
529
            case 'css':
530
                if ($preload) {
531
                    return \sprintf(
532
                        '<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>',
533
                        $this->url($asset, $options),
534
                        $htmlAttributes
535
                    );
536
                }
537
538
                return \sprintf('<link rel="stylesheet" href="%s"%s>', $this->url($asset, $options), $htmlAttributes);
539
            case 'js':
540
                return \sprintf('<script src="%s"%s></script>', $this->url($asset, $options), $htmlAttributes);
541
        }
542
        // image
543
        if ($asset['type'] == 'image') {
544
            // responsive
545
            $sizes = '';
546
            if (
547
                $responsive && $srcset = Image::buildSrcset(
548
                    $asset,
549
                    $this->config->getAssetsImagesWidths()
550
                )
551
            ) {
552
                $htmlAttributes .= \sprintf(' srcset="%s"', $srcset);
553
                $sizes = $this->config->get('assets.images.responsive.sizes.default') ?? '100vw';
554
                if (isset($attributes['class'])) {
555
                    $sizes = Image::getSizes($attributes['class'], (array) $this->builder->getConfig()->get('assets.images.responsive.sizes'));
556
                }
557
                $htmlAttributes .= \sprintf(' sizes="%s"', $sizes);
558
            }
559
560
            // <img> element
561
            $img = \sprintf(
562
                '<img src="%s" width="' . ($asset['width'] ?: '') . '" height="' . ($asset['height'] ?: '') . '"%s>',
563
                $this->url($asset, $options),
564
                $htmlAttributes
565
            );
566
567
            // WebP conversion?
568
            if ($webp && $asset['subtype'] != 'image/webp' && !Image::isAnimatedGif($asset)) {
569
                try {
570
                    $assetWebp = $asset->webp();
571
                    // <source> element
572
                    $source = \sprintf('<source type="image/webp" srcset="%s">', $assetWebp);
573
                    // responsive
574
                    if ($responsive) {
575
                        $srcset = Image::buildSrcset(
576
                            $assetWebp,
577
                            $this->config->getAssetsImagesWidths()
578
                        ) ?: (string) $assetWebp;
579
                        // <source> element
580
                        $source = \sprintf(
581
                            '<source type="image/webp" srcset="%s" sizes="%s">',
582
                            $srcset,
583
                            $sizes
584
                        );
585
                    }
586
587
                    return \sprintf("<picture>\n  %s\n  %s\n</picture>", $source, $img);
588
                } catch (\Exception $e) {
589
                    $this->builder->getLogger()->debug($e->getMessage());
590
                }
591
            }
592
593
            return $img;
594
        }
595
596
        throw new RuntimeException(\sprintf('%s is available for CSS, JavaScript and images files only.', '"html" filter'));
597
    }
598
599
    /**
600
     * Returns the content of an asset.
601
     */
602
    public function inline(Asset $asset): string
603
    {
604
        return $asset['content'];
605
    }
606
607
    /**
608
     * Reads $length first characters of a string and adds a suffix.
609
     */
610
    public function excerpt(?string $string, int $length = 450, string $suffix = ' …'): string
611
    {
612
        $string = $string ?? '';
613
614
        $string = str_replace('</p>', '<br /><br />', $string);
615
        $string = trim(strip_tags($string, '<br>'), '<br />');
616
        if (mb_strlen($string) > $length) {
617
            $string = mb_substr($string, 0, $length);
618
            $string .= $suffix;
619
        }
620
621
        return $string;
622
    }
623
624
    /**
625
     * Reads characters before or after '<!-- separator -->'.
626
     * Options:
627
     *  - separator: string to use as separator (`excerpt|break` by default)
628
     *  - capture: part to capture, `before` or `after` the separator (`before` by default).
629
     */
630
    public function excerptHtml(?string $string, array $options = []): string
631
    {
632
        $string = $string ?? '';
633
634
        $separator = (string) $this->builder->getConfig()->get('body.excerpt.separator');
635
        $capture = (string) $this->builder->getConfig()->get('body.excerpt.capture');
636
        extract($options, EXTR_IF_EXISTS);
637
638
        // https://regex101.com/r/n9TWHF/1
639
        $pattern = '(.*)<!--[[:blank:]]?(' . $separator . ')[[:blank:]]?-->(.*)';
640
        preg_match('/' . $pattern . '/is', $string, $matches);
641
642
        if (empty($matches)) {
643
            return $string;
644
        }
645
        $result = trim($matches[1]);
646
        if ($capture == 'after') {
647
            $result = trim($matches[3]);
648
        }
649
        // removes footnotes and returns result
650
        return preg_replace('/<sup[^>]*>[^u]*<\/sup>/', '', $result);
651
    }
652
653
    /**
654
     * Converts a Markdown string to HTML.
655
     *
656
     * @throws RuntimeException
657
     */
658
    public function markdownToHtml(?string $markdown): ?string
659
    {
660
        $markdown = $markdown ?? '';
661
662
        try {
663
            $parsedown = new Parsedown($this->builder);
664
            $html = $parsedown->text($markdown);
665
        } catch (\Exception $e) {
666
            throw new RuntimeException('"markdown_to_html" filter can not convert supplied Markdown.');
667
        }
668
669
        return $html;
670
    }
671
672
    /**
673
     * Extract table of content of a Markdown string,
674
     * in the given format ("html" or "json", "html" by default).
675
     *
676
     * @throws RuntimeException
677
     */
678
    public function markdownToToc(?string $markdown, $format = 'html', $url = ''): ?string
679
    {
680
        $markdown = $markdown ?? '';
681
682
        try {
683
            $parsedown = new Parsedown($this->builder, ['selectors' => ['h2'], 'url' => $url]);
684
            $parsedown->body($markdown);
685
            $return = $parsedown->contentsList($format);
686
        } catch (\Exception $e) {
687
            throw new RuntimeException('"toc" filter can not convert supplied Markdown.');
688
        }
689
690
        return $return;
691
    }
692
693
    /**
694
     * Converts a JSON string to an array.
695
     *
696
     * @throws RuntimeException
697
     */
698
    public function jsonDecode(?string $json): ?array
699
    {
700
        $json = $json ?? '';
701
702
        try {
703
            $array = json_decode($json, true);
704
            if ($array === null && json_last_error() !== JSON_ERROR_NONE) {
705
                throw new \Exception('JSON error.');
706
            }
707
        } catch (\Exception $e) {
708
            throw new RuntimeException('"json_decode" filter can not parse supplied JSON.');
709
        }
710
711
        return $array;
712
    }
713
714
    /**
715
     * Converts a YAML string to an array.
716
     *
717
     * @throws RuntimeException
718
     */
719
    public function yamlParse(?string $yaml): ?array
720
    {
721
        $yaml = $yaml ?? '';
722
723
        try {
724
            $array = Yaml::parse($yaml);
725
            if (!is_array($array)) {
726
                throw new ParseException('YAML error.');
727
            }
728
        } catch (ParseException $e) {
729
            throw new RuntimeException(\sprintf('"yaml_parse" filter can not parse supplied YAML: %s', $e->getMessage()));
730
        }
731
732
        return $array;
733
    }
734
735
    /**
736
     * Split a string into an array using a regular expression.
737
     *
738
     * @throws RuntimeException
739
     */
740
    public function pregSplit(?string $value, string $pattern, int $limit = 0): ?array
741
    {
742
        $value = $value ?? '';
743
744
        try {
745
            $array = preg_split($pattern, $value, $limit);
746
            if ($array === false) {
747
                throw new RuntimeException('PREG split error.');
748
            }
749
        } catch (\Exception $e) {
750
            throw new RuntimeException('"preg_split" filter can not split supplied string.');
751
        }
752
753
        return $array;
754
    }
755
756
    /**
757
     * Perform a regular expression match and return the group for all matches.
758
     *
759
     * @throws RuntimeException
760
     */
761
    public function pregMatchAll(?string $value, string $pattern, int $group = 0): ?array
762
    {
763
        $value = $value ?? '';
764
765
        try {
766
            $array = preg_match_all($pattern, $value, $matches, PREG_PATTERN_ORDER);
767
            if ($array === false) {
768
                throw new RuntimeException('PREG match all error.');
769
            }
770
        } catch (\Exception $e) {
771
            throw new RuntimeException('"preg_match_all" filter can not match in supplied string.');
772
        }
773
774
        return $matches[$group];
775
    }
776
777
    /**
778
     * Calculates estimated time to read a text.
779
     */
780
    public function readtime(?string $text): string
781
    {
782
        $text = $text ?? '';
783
784
        $words = str_word_count(strip_tags($text));
785
        $min = floor($words / 200);
786
        if ($min === 0) {
787
            return '1';
788
        }
789
790
        return (string) $min;
791
    }
792
793
    /**
794
     * Gets the value of an environment variable.
795
     */
796
    public function getEnv(?string $var): ?string
797
    {
798
        $var = $var ?? '';
799
800
        return getenv($var) ?: null;
801
    }
802
803
    /**
804
     * Tests if a variable is an Asset.
805
     */
806
    public function isAsset($variable): bool
807
    {
808
        return $variable instanceof Asset;
809
    }
810
811
    /**
812
     * Returns the dominant hex color of an image asset.
813
     *
814
     * @param string|Asset $asset
815
     *
816
     * @return string
817
     */
818
    public function dominantColor($asset): string
819
    {
820
        if (!$asset instanceof Asset) {
821
            $asset = new Asset($this->builder, $asset);
822
        }
823
824
        return Image::getDominantColor($asset);
825
    }
826
827
    /**
828
     * Returns a Low Quality Image Placeholder (LQIP) as data URL.
829
     *
830
     * @param string|Asset $asset
831
     *
832
     * @return string
833
     */
834
    public function lqip($asset): string
835
    {
836
        if (!$asset instanceof Asset) {
837
            $asset = new Asset($this->builder, $asset);
838
        }
839
840
        return Image::getLqip($asset);
841
    }
842
843
    /**
844
     * Converts an hexadecimal color to RGB.
845
     *
846
     * @throws RuntimeException
847
     */
848
    public function hexToRgb(?string $variable): array
849
    {
850
        $variable = $variable ?? '';
851
852
        if (!self::isHex($variable)) {
853
            throw new RuntimeException(\sprintf('"%s" is not a valid hexadecimal value.', $variable));
854
        }
855
        $hex = ltrim($variable, '#');
856
        if (strlen($hex) == 3) {
857
            $hex = $hex[0] . $hex[0] . $hex[1] . $hex[1] . $hex[2] . $hex[2];
858
        }
859
        $c = hexdec($hex);
860
861
        return [
862
            'red'   => $c >> 16 & 0xFF,
863
            'green' => $c >> 8 & 0xFF,
864
            'blue'  => $c & 0xFF,
865
        ];
866
    }
867
868
    /**
869
     * Split a string in multiple lines.
870
     */
871
    public function splitLine(?string $variable, int $max = 18): array
872
    {
873
        $variable = $variable ?? '';
874
875
        return preg_split("/.{0,{$max}}\K(\s+|$)/", $variable, 0, PREG_SPLIT_NO_EMPTY);
876
    }
877
878
    /**
879
     * Is a hexadecimal color is valid?
880
     */
881
    private static function isHex(string $hex): bool
882
    {
883
        $valid = is_string($hex);
884
        $hex = ltrim($hex, '#');
885
        $length = strlen($hex);
886
        $valid = $valid && ($length === 3 || $length === 6);
887
        $valid = $valid && ctype_xdigit($hex);
888
889
        return $valid;
890
    }
891
}
892