Passed
Push — converter ( 2ce234...3934d6 )
by Arnaud
03:13
created

Core::html()   D

Complexity

Conditions 18
Paths 93

Size

Total Lines 87
Code Lines 52

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 18
eloc 52
c 1
b 0
f 0
nc 93
nop 3
dl 0
loc 87
rs 4.8666

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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
            // content
128
            new \Twig\TwigFilter('slugify', [$this, 'slugifyFilter']),
129
            new \Twig\TwigFilter('excerpt', [$this, 'excerpt']),
130
            new \Twig\TwigFilter('excerpt_html', [$this, 'excerptHtml']),
131
            new \Twig\TwigFilter('markdown_to_html', [$this, 'markdownToHtml']),
132
            new \Twig\TwigFilter('toc', [$this, 'markdownToToc']),
133
            new \Twig\TwigFilter('json_decode', [$this, 'jsonDecode']),
134
            new \Twig\TwigFilter('yaml_parse', [$this, 'yamlParse']),
135
            new \Twig\TwigFilter('preg_split', [$this, 'pregSplit']),
136
            new \Twig\TwigFilter('preg_match_all', [$this, 'pregMatchAll']),
137
            new \Twig\TwigFilter('hex_to_rgb', [$this, 'hexToRgb']),
138
            // deprecated
139
            new \Twig\TwigFilter(
140
                'filterBySection',
141
                [$this, 'filterBySection'],
142
                ['deprecated' => true, 'alternative' => 'filter_by']
143
            ),
144
            new \Twig\TwigFilter(
145
                'filterBy',
146
                [$this, 'filterBy'],
147
                ['deprecated' => true, 'alternative' => 'filter_by']
148
            ),
149
            new \Twig\TwigFilter(
150
                'sortByTitle',
151
                [$this, 'sortByTitle'],
152
                ['deprecated' => true, 'alternative' => 'sort_by_title']
153
            ),
154
            new \Twig\TwigFilter(
155
                'sortByWeight',
156
                [$this, 'sortByWeight'],
157
                ['deprecated' => true, 'alternative' => 'sort_by_weight']
158
            ),
159
            new \Twig\TwigFilter(
160
                'sortByDate',
161
                [$this, 'sortByDate'],
162
                ['deprecated' => true, 'alternative' => 'sort_by_date']
163
            ),
164
            new \Twig\TwigFilter(
165
                'minifyCSS',
166
                [$this, 'minifyCss'],
167
                ['deprecated' => true, 'alternative' => 'minifyCss']
168
            ),
169
            new \Twig\TwigFilter(
170
                'minifyJS',
171
                [$this, 'minifyJs'],
172
                ['deprecated' => true, 'alternative' => 'minifyJs']
173
            ),
174
            new \Twig\TwigFilter(
175
                'SCSStoCSS',
176
                [$this, 'scssToCss'],
177
                ['deprecated' => true, 'alternative' => 'scss_to_css']
178
            ),
179
            new \Twig\TwigFilter(
180
                'excerptHtml',
181
                [$this, 'excerptHtml'],
182
                ['deprecated' => true, 'alternative' => 'excerpt_html']
183
            ),
184
            new \Twig\TwigFilter(
185
                'urlize',
186
                [$this, 'slugifyFilter'],
187
                ['deprecated' => true, 'alternative' => 'slugify']
188
            ),
189
        ];
190
    }
191
192
    /**
193
     * {@inheritdoc}
194
     */
195
    public function getTests()
196
    {
197
        return [
198
            new \Twig\TwigTest('asset', [$this, 'isAsset']),
199
        ];
200
    }
201
202
    /**
203
     * Filters by Section.
204
     */
205
    public function filterBySection(PagesCollection $pages, string $section): CollectionInterface
206
    {
207
        return $this->filterBy($pages, 'section', $section);
208
    }
209
210
    /**
211
     * Filters a pages collection 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 a collection by title.
232
     */
233
    public function sortByTitle(\Traversable $collection, bool $reverse = false): array
234
    {
235
        $sort = $reverse ? \SORT_DESC : \SORT_ASC;
236
237
        $collection = iterator_to_array($collection);
238
        /** @var \array $collection */
239
        array_multisort(array_keys(/** @scrutinizer ignore-type */ $collection), $sort, \SORT_NATURAL | \SORT_FLAG_CASE, $collection);
0 ignored issues
show
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

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

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