Passed
Push — toc ( a7d83e )
by Arnaud
03:57
created

Extension::markdownToToc()   A

Complexity

Conditions 2
Paths 4

Size

Total Lines 13
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 8
c 1
b 0
f 0
nc 4
nop 2
dl 0
loc 13
rs 10
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\Twig;
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 Twig\Extension.
37
 */
38
class Extension 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 'cecil';
67
    }
68
69
    /**
70
     * {@inheritdoc}
71
     */
72
    public function getFilters()
73
    {
74
        return [
75
            new \Twig\TwigFilter('filter_by', [$this, 'filterBy']),
76
            // sort
77
            new \Twig\TwigFilter('sort_by_title', [$this, 'sortByTitle']),
78
            new \Twig\TwigFilter('sort_by_weight', [$this, 'sortByWeight']),
79
            new \Twig\TwigFilter('sort_by_date', [$this, 'sortByDate']),
80
            // assets
81
            new \Twig\TwigFilter('url', [$this, 'url']),
82
            new \Twig\TwigFilter('html', [$this, 'html']),
83
            new \Twig\TwigFilter('inline', [$this, 'inline']),
84
            new \Twig\TwigFilter('fingerprint', [$this, 'fingerprint']),
85
            new \Twig\TwigFilter('to_css', [$this, 'toCss']),
86
            new \Twig\TwigFilter('minify', [$this, 'minify']),
87
            new \Twig\TwigFilter('minify_css', [$this, 'minifyCss']),
88
            new \Twig\TwigFilter('minify_js', [$this, 'minifyJs']),
89
            new \Twig\TwigFilter('scss_to_css', [$this, 'scssToCss']),
90
            new \Twig\TwigFilter('sass_to_css', [$this, 'scssToCss']),
91
            new \Twig\TwigFilter('resize', [$this, 'resize']),
92
            new \Twig\TwigFilter('dataurl', [$this, 'dataurl']),
93
            // content
94
            new \Twig\TwigFilter('slugify', [$this, 'slugifyFilter']),
95
            new \Twig\TwigFilter('excerpt', [$this, 'excerpt']),
96
            new \Twig\TwigFilter('excerpt_html', [$this, 'excerptHtml']),
97
            new \Twig\TwigFilter('markdown_to_html', [$this, 'markdownToHtml']),
98
            new \Twig\TwigFilter('toc', [$this, 'markdownToToc']),
99
            new \Twig\TwigFilter('json_decode', [$this, 'jsonDecode']),
100
            new \Twig\TwigFilter('yaml_parse', [$this, 'yamlParse']),
101
            new \Twig\TwigFilter('preg_split', [$this, 'pregSplit']),
102
            new \Twig\TwigFilter('preg_match_all', [$this, 'pregMatchAll']),
103
            new \Twig\TwigFilter('hex_to_rgb', [$this, 'hexToRgb']),
104
            // deprecated
105
            new \Twig\TwigFilter(
106
                'filterBySection',
107
                [$this, 'filterBySection'],
108
                ['deprecated' => true, 'alternative' => 'filter_by']
109
            ),
110
            new \Twig\TwigFilter(
111
                'filterBy',
112
                [$this, 'filterBy'],
113
                ['deprecated' => true, 'alternative' => 'filter_by']
114
            ),
115
            new \Twig\TwigFilter(
116
                'sortByTitle',
117
                [$this, 'sortByTitle'],
118
                ['deprecated' => true, 'alternative' => 'sort_by_title']
119
            ),
120
            new \Twig\TwigFilter(
121
                'sortByWeight',
122
                [$this, 'sortByWeight'],
123
                ['deprecated' => true, 'alternative' => 'sort_by_weight']
124
            ),
125
            new \Twig\TwigFilter(
126
                'sortByDate',
127
                [$this, 'sortByDate'],
128
                ['deprecated' => true, 'alternative' => 'sort_by_date']
129
            ),
130
            new \Twig\TwigFilter(
131
                'minifyCSS',
132
                [$this, 'minifyCss'],
133
                ['deprecated' => true, 'alternative' => 'minifyCss']
134
            ),
135
            new \Twig\TwigFilter(
136
                'minifyJS',
137
                [$this, 'minifyJs'],
138
                ['deprecated' => true, 'alternative' => 'minifyJs']
139
            ),
140
            new \Twig\TwigFilter(
141
                'SCSStoCSS',
142
                [$this, 'scssToCss'],
143
                ['deprecated' => true, 'alternative' => 'scss_to_css']
144
            ),
145
            new \Twig\TwigFilter(
146
                'excerptHtml',
147
                [$this, 'excerptHtml'],
148
                ['deprecated' => true, 'alternative' => 'excerpt_html']
149
            ),
150
            new \Twig\TwigFilter(
151
                'urlize',
152
                [$this, 'slugifyFilter'],
153
                ['deprecated' => true, 'alternative' => 'slugify']
154
            ),
155
        ];
156
    }
157
158
    /**
159
     * {@inheritdoc}
160
     */
161
    public function getFunctions()
162
    {
163
        return [
164
            // assets
165
            new \Twig\TwigFunction('url', [$this, 'url']),
166
            new \Twig\TwigFunction('asset', [$this, 'asset']),
167
            new \Twig\TwigFunction('integrity', [$this, 'integrity']),
168
            // content
169
            new \Twig\TwigFunction('readtime', [$this, 'readtime']),
170
            // others
171
            new \Twig\TwigFunction('getenv', [$this, 'getEnv']),
172
            // deprecated
173
            new \Twig\TwigFunction(
174
                'minify',
175
                [$this, 'minify'],
176
                ['deprecated' => true, 'alternative' => 'minify filter']
177
            ),
178
            new \Twig\TwigFunction(
179
                'toCSS',
180
                [$this, 'toCss'],
181
                ['deprecated' => true, 'alternative' => 'to_css filter']
182
            ),
183
            new \Twig\TwigFunction(
184
                'hash',
185
                [$this, 'integrity'],
186
                ['deprecated' => true, 'alternative' => 'integrity']
187
            ),
188
        ];
189
    }
190
191
    /**
192
     * {@inheritdoc}
193
     */
194
    public function getTests()
195
    {
196
        return [
197
            new \Twig\TwigTest('asset', [$this, 'isAsset']),
198
        ];
199
    }
200
201
    /**
202
     * Filters by Section.
203
     * Alias of `filterBy('section', $value)`.
204
     */
205
    public function filterBySection(PagesCollection $pages, string $section): CollectionInterface
206
    {
207
        return $this->filterBy($pages, 'section', $section);
208
    }
209
210
    /**
211
     * Filters by variable's name/value.
212
     */
213
    public function filterBy(PagesCollection $pages, string $variable, string $value): CollectionInterface
214
    {
215
        $filteredPages = $pages->filter(function (Page $page) use ($variable, $value) {
216
            // is a dedicated getter exists?
217
            $method = 'get'.ucfirst($variable);
218
            if (method_exists($page, $method) && $page->$method() == $value) {
219
                return $page->getType() == Type::PAGE() && !$page->isVirtual() && true;
220
            }
221
            // or a classic variable
222
            if ($page->getVariable($variable) == $value) {
223
                return $page->getType() == Type::PAGE() && !$page->isVirtual() && true;
224
            }
225
        });
226
227
        return $filteredPages;
228
    }
229
230
    /**
231
     * Sorts by title.
232
     */
233
    public function sortByTitle(\Traversable $collection): array
234
    {
235
        $collection = iterator_to_array($collection);
236
        /** @var \array $collection */
237
        array_multisort(array_keys(/** @scrutinizer ignore-type */ $collection), \SORT_ASC, \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

237
        array_multisort(/** @scrutinizer ignore-type */ array_keys(/** @scrutinizer ignore-type */ $collection), \SORT_ASC, \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

237
        array_multisort(array_keys(/** @scrutinizer ignore-type */ $collection), \SORT_ASC, /** @scrutinizer ignore-type */ \SORT_NATURAL | \SORT_FLAG_CASE, $collection);
Loading history...
Bug introduced by
SORT_ASC 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

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