Passed
Push — extensions ( 654ea7...f21e0c )
by Arnaud
08:49 queued 05:35
created

CoreExtension::sortByDate()   B

Complexity

Conditions 8
Paths 1

Size

Total Lines 20
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 8.064

Importance

Changes 0
Metric Value
cc 8
eloc 9
nc 1
nop 4
dl 0
loc 20
ccs 9
cts 10
cp 0.9
crap 8.064
rs 8.4444
c 0
b 0
f 0
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 Extension\CoreExtension.
37
 */
38
class CoreExtension 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 1
    public function __construct(Builder $builder)
50
    {
51 1
        if (!self::$slugifier instanceof Slugify) {
52 1
            self::$slugifier = Slugify::create(['regexp' => Page::SLUGIFY_PATTERN]);
53
        }
54
55 1
        parent::__construct(self::$slugifier);
56
57 1
        $this->builder = $builder;
58 1
        $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 1
    public function getFunctions()
73
    {
74
        return [
75 1
            new \Twig\TwigFunction('url', [$this, 'url']),
76
            // assets
77 1
            new \Twig\TwigFunction('asset', [$this, 'asset']),
78 1
            new \Twig\TwigFunction('integrity', [$this, 'integrity']),
79
            // content
80 1
            new \Twig\TwigFunction('readtime', [$this, 'readtime']),
81
            // others
82 1
            new \Twig\TwigFunction('getenv', [$this, 'getEnv']),
83
            // deprecated
84 1
            new \Twig\TwigFunction(
85
                'hash',
86 1
                [$this, 'integrity'],
87 1
                ['deprecated' => true, 'alternative' => 'integrity']
88
            ),
89 1
            new \Twig\TwigFunction(
90
                'minify',
91 1
                [$this, 'minify'],
92 1
                ['deprecated' => true, 'alternative' => 'minify filter']
93
            ),
94 1
            new \Twig\TwigFunction(
95
                'toCSS',
96 1
                [$this, 'toCss'],
97 1
                ['deprecated' => true, 'alternative' => 'to_css filter']
98
            ),
99
        ];
100
    }
101
102
    /**
103
     * {@inheritdoc}
104
     */
105 1
    public function getFilters()
106
    {
107
        return [
108 1
            new \Twig\TwigFilter('url', [$this, 'url']),
109
            // collections
110 1
            new \Twig\TwigFilter('sort_by_title', [$this, 'sortByTitle']),
111 1
            new \Twig\TwigFilter('sort_by_weight', [$this, 'sortByWeight']),
112 1
            new \Twig\TwigFilter('sort_by_date', [$this, 'sortByDate']),
113 1
            new \Twig\TwigFilter('filter_by', [$this, 'filterBy']),
114
            // assets
115 1
            new \Twig\TwigFilter('html', [$this, 'html']),
116 1
            new \Twig\TwigFilter('inline', [$this, 'inline']),
117 1
            new \Twig\TwigFilter('fingerprint', [$this, 'fingerprint']),
118 1
            new \Twig\TwigFilter('to_css', [$this, 'toCss']),
119 1
            new \Twig\TwigFilter('minify', [$this, 'minify']),
120 1
            new \Twig\TwigFilter('minify_css', [$this, 'minifyCss']),
121 1
            new \Twig\TwigFilter('minify_js', [$this, 'minifyJs']),
122 1
            new \Twig\TwigFilter('scss_to_css', [$this, 'scssToCss']),
123 1
            new \Twig\TwigFilter('sass_to_css', [$this, 'scssToCss']),
124 1
            new \Twig\TwigFilter('resize', [$this, 'resize']),
125 1
            new \Twig\TwigFilter('dataurl', [$this, 'dataurl']),
126 1
            new \Twig\TwigFilter('dominant_color', [$this, 'dominantColor']),
127
            // content
128 1
            new \Twig\TwigFilter('slugify', [$this, 'slugifyFilter']),
129 1
            new \Twig\TwigFilter('excerpt', [$this, 'excerpt']),
130 1
            new \Twig\TwigFilter('excerpt_html', [$this, 'excerptHtml']),
131 1
            new \Twig\TwigFilter('markdown_to_html', [$this, 'markdownToHtml']),
132 1
            new \Twig\TwigFilter('toc', [$this, 'markdownToToc']),
133 1
            new \Twig\TwigFilter('json_decode', [$this, 'jsonDecode']),
134 1
            new \Twig\TwigFilter('yaml_parse', [$this, 'yamlParse']),
135 1
            new \Twig\TwigFilter('preg_split', [$this, 'pregSplit']),
136 1
            new \Twig\TwigFilter('preg_match_all', [$this, 'pregMatchAll']),
137 1
            new \Twig\TwigFilter('hex_to_rgb', [$this, 'hexToRgb']),
138
            // deprecated
139 1
            new \Twig\TwigFilter(
140
                'filterBySection',
141 1
                [$this, 'filterBySection'],
142 1
                ['deprecated' => true, 'alternative' => 'filter_by']
143
            ),
144 1
            new \Twig\TwigFilter(
145
                'filterBy',
146 1
                [$this, 'filterBy'],
147 1
                ['deprecated' => true, 'alternative' => 'filter_by']
148
            ),
149 1
            new \Twig\TwigFilter(
150
                'sortByTitle',
151 1
                [$this, 'sortByTitle'],
152 1
                ['deprecated' => true, 'alternative' => 'sort_by_title']
153
            ),
154 1
            new \Twig\TwigFilter(
155
                'sortByWeight',
156 1
                [$this, 'sortByWeight'],
157 1
                ['deprecated' => true, 'alternative' => 'sort_by_weight']
158
            ),
159 1
            new \Twig\TwigFilter(
160
                'sortByDate',
161 1
                [$this, 'sortByDate'],
162 1
                ['deprecated' => true, 'alternative' => 'sort_by_date']
163
            ),
164 1
            new \Twig\TwigFilter(
165
                'minifyCSS',
166 1
                [$this, 'minifyCss'],
167 1
                ['deprecated' => true, 'alternative' => 'minifyCss']
168
            ),
169 1
            new \Twig\TwigFilter(
170
                'minifyJS',
171 1
                [$this, 'minifyJs'],
172 1
                ['deprecated' => true, 'alternative' => 'minifyJs']
173
            ),
174 1
            new \Twig\TwigFilter(
175
                'SCSStoCSS',
176 1
                [$this, 'scssToCss'],
177 1
                ['deprecated' => true, 'alternative' => 'scss_to_css']
178
            ),
179 1
            new \Twig\TwigFilter(
180
                'excerptHtml',
181 1
                [$this, 'excerptHtml'],
182 1
                ['deprecated' => true, 'alternative' => 'excerpt_html']
183
            ),
184 1
            new \Twig\TwigFilter(
185
                'urlize',
186 1
                [$this, 'slugifyFilter'],
187 1
                ['deprecated' => true, 'alternative' => 'slugify']
188
            ),
189
        ];
190
    }
191
192
    /**
193
     * {@inheritdoc}
194
     */
195 1
    public function getTests()
196
    {
197
        return [
198 1
            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 1
    public function filterBy(PagesCollection $pages, string $variable, string $value): CollectionInterface
214
    {
215 1
        $filteredPages = $pages->filter(function (Page $page) use ($variable, $value) {
216
            // is a dedicated getter exists?
217 1
            $method = 'get'.ucfirst($variable);
218 1
            if (method_exists($page, $method) && $page->$method() == $value) {
219
                return $page->getType() == Type::PAGE() && !$page->isVirtual() && true;
220
            }
221
            // or a classic variable
222 1
            if ($page->getVariable($variable) == $value) {
223 1
                return $page->getType() == Type::PAGE() && !$page->isVirtual() && true;
224
            }
225
        });
226
227 1
        return $filteredPages;
228
    }
229
230
    /**
231
     * Sorts a collection by title.
232
     */
233 1
    public function sortByTitle(\Traversable $collection, bool $reverse = false): array
234
    {
235 1
        $sort = $reverse ? \SORT_DESC : \SORT_ASC;
236
237 1
        $collection = iterator_to_array($collection);
238
        /** @var \array $collection */
239 1
        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 1
        return $collection;
242
    }
243
244
    /**
245
     * Sorts a collection by weight.
246
     */
247 1
    public function sortByWeight(\Traversable $collection, bool $reverse = false): array
248
    {
249 1
        $callback = function ($a, $b) use ($reverse) {
250 1
            if (!isset($a['weight'])) {
251 1
                $a['weight'] = 0;
252
            }
253 1
            if (!isset($b['weight'])) {
254
                $a['weight'] = 0;
255
            }
256 1
            if ($a['weight'] == $b['weight']) {
257 1
                return 0;
258
            }
259
260 1
            return ($reverse ? -1 : 1) * ($a['weight'] < $b['weight'] ? -1 : 1);
261
        };
262
263 1
        $collection = iterator_to_array($collection);
264
        /** @var \array $collection */
265 1
        usort(/** @scrutinizer ignore-type */ $collection, $callback);
266
267 1
        return $collection;
268
    }
269
270
    /**
271
     * Sorts by creation date (or 'updated' date): the most recent first.
272
     */
273 1
    public function sortByDate(\Traversable $collection, string $variable = 'date', bool $reverse = false, bool $descTitle = false): array
274
    {
275 1
        $callback = function ($a, $b) use ($variable, $reverse, $descTitle) {
276 1
            if ($a[$variable] == $b[$variable]) {
277
                // if dates are equal and "descTitle" is true
278 1
                if ($descTitle && (isset($a['title']) && isset($b['title']))) {
279
                    return $a['title'] > $b['title'] ? -1 : 1;
280
                }
281
282 1
                return 0;
283
            }
284
285 1
            return ($reverse ? -1 : 1) * ($a[$variable] > $b[$variable] ? -1 : 1);
286
        };
287
288 1
        $collection = iterator_to_array($collection);
289
        /** @var \array $collection */
290 1
        usort(/** @scrutinizer ignore-type */ $collection, $callback);
291
292 1
        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 1
    public function url($value = null, array $options = null): string
308
    {
309 1
        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 1
    public function asset($path, array $options = null): Asset
321
    {
322 1
        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 1
    public function toCss($asset): Asset
333
    {
334 1
        if (!$asset instanceof Asset) {
335
            $asset = new Asset($this->builder, $asset);
336
        }
337
338 1
        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 1
    public function minify($asset): Asset
349
    {
350 1
        if (!$asset instanceof Asset) {
351
            $asset = new Asset($this->builder, $asset);
352
        }
353
354 1
        return $asset->minify();
355
    }
356
357
    /**
358
     * Fingerprinting an asset.
359
     *
360
     * @param string|Asset $asset
361
     *
362
     * @return Asset
363
     */
364 1
    public function fingerprint($asset): Asset
365
    {
366 1
        if (!$asset instanceof Asset) {
367
            $asset = new Asset($this->builder, $asset);
368
        }
369
370 1
        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 1
    public function dataurl($asset): string
397
    {
398 1
        if (!$asset instanceof Asset) {
399
            $asset = new Asset($this->builder, $asset);
400
        }
401
402 1
        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 1
    public function integrity($asset, string $algo = 'sha384'): string
414
    {
415 1
        if (!$asset instanceof Asset) {
416 1
            $asset = new Asset($this->builder, $asset);
417
        }
418
419 1
        return $asset->getIntegrity($algo);
420
    }
421
422
    /**
423
     * Minifying a CSS string.
424
     */
425 1
    public function minifyCss(?string $value): string
426
    {
427 1
        $value = $value ?? '';
428
429 1
        if ($this->builder->isDebug()) {
430 1
            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 1
    public function minifyJs(?string $value): string
448
    {
449 1
        $value = $value ?? '';
450
451 1
        if ($this->builder->isDebug()) {
452 1
            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 1
    public function html(Asset $asset, array $attributes = [], array $options = []): string
509
    {
510 1
        $htmlAttributes = '';
511 1
        $preload = false;
512 1
        $responsive = $this->config->get('assets.images.responsive.enabled') ?? false;
513 1
        $webp = $this->config->get('assets.images.webp.enabled') ?? false;
514 1
        extract($options, EXTR_IF_EXISTS);
515
516
        // builds HTML attributes
517 1
        foreach ($attributes as $name => $value) {
518 1
            $attribute = \sprintf(' %s="%s"', $name, $value);
519 1
            if (empty($value)) {
520 1
                $attribute = \sprintf(' %s', $name);
521
            }
522 1
            $htmlAttributes .= $attribute;
523
        }
524
525
        // be sure Asset file is saved
526 1
        $asset->save();
527
528
        // CSS or JavaScript
529 1
        switch ($asset['ext']) {
530 1
            case 'css':
531 1
                if ($preload) {
532 1
                    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 1
                        $this->url($asset, $options),
535
                        $htmlAttributes
536
                    );
537
                }
538
539 1
                return \sprintf('<link rel="stylesheet" href="%s"%s>', $this->url($asset, $options), $htmlAttributes);
540 1
            case 'js':
541
                return \sprintf('<script src="%s"%s></script>', $this->url($asset, $options), $htmlAttributes);
542
        }
543
        // image
544 1
        if ($asset['type'] == 'image') {
545
            // responsive
546 1
            if ($responsive && $srcset = Image::buildSrcset(
547
                $asset,
548 1
                $this->config->get('assets.images.responsive.widths') ?? [480, 640, 768, 1024, 1366, 1600, 1920]
549
            )) {
550
                $htmlAttributes .= \sprintf(' srcset="%s"', $srcset);
551
                $htmlAttributes .= \sprintf(' sizes="%s"', $this->config->get('assets.images.responsive.sizes.default') ?? '100vw');
552
            }
553
554
            // <img> element
555 1
            $img = \sprintf(
556 1
                '<img src="%s" width="'.($asset->getWidth() ?: '').'" height="'.($asset->getHeight() ?: '').'"%s>',
557 1
                $this->url($asset, $options),
558
                $htmlAttributes
559
            );
560
561
            // WebP conversion?
562 1
            if ($webp && $asset['subtype'] != 'image/webp' && !Image::isAnimatedGif($asset)) {
563
                try {
564 1
                    $assetWebp = Image::convertTopWebp($asset, $this->config->get('assets.images.quality') ?? 75);
565
                    // <source> element
566
                    $source = \sprintf('<source type="image/webp" srcset="%s">', $assetWebp);
567
                    // responsive
568
                    if ($responsive) {
569
                        $srcset = Image::buildSrcset(
570
                            $assetWebp,
571
                            $this->config->get('assets.images.responsive.widths') ?? [480, 640, 768, 1024, 1366, 1600, 1920]
572
                        ) ?: (string) $assetWebp;
573
                        // <source> element
574
                        $source = \sprintf(
575
                            '<source type="image/webp" srcset="%s" sizes="%s">',
576
                            $srcset,
577
                            $this->config->get('assets.images.responsive.sizes.default') ?? '100vw'
578
                        );
579
                    }
580
581
                    return \sprintf("<picture>\n  %s\n  %s\n</picture>", $source, $img);
582 1
                } catch (\Exception $e) {
583 1
                    $this->builder->getLogger()->debug($e->getMessage());
584
                }
585
            }
586
587 1
            return $img;
588
        }
589
590
        throw new RuntimeException(\sprintf('%s is available for CSS, JavaScript and images files only.', '"html" filter'));
591
    }
592
593
    /**
594
     * Returns the content of an asset.
595
     */
596 1
    public function inline(Asset $asset): string
597
    {
598 1
        return $asset['content'];
599
    }
600
601
    /**
602
     * Reads $length first characters of a string and adds a suffix.
603
     */
604
    public function excerpt(?string $string, int $length = 450, string $suffix = ' …'): string
605
    {
606
        $string = $string ?? '';
607
608
        $string = str_replace('</p>', '<br /><br />', $string);
609
        $string = trim(strip_tags($string, '<br>'), '<br />');
610
        if (mb_strlen($string) > $length) {
611
            $string = mb_substr($string, 0, $length);
612
            $string .= $suffix;
613
        }
614
615
        return $string;
616
    }
617
618
    /**
619
     * Reads characters before '<!-- excerpt|break -->'.
620
     * Options:
621
     *  - separator: string to use as separator
622
     *  - capture: string to capture, 'before' (default) or 'after'.
623
     */
624 1
    public function excerptHtml(?string $string, array $options = []): string
625
    {
626 1
        $string = $string ?? '';
627
628 1
        $separator = 'excerpt|break';
629 1
        $capture = 'before';
630 1
        extract($options, EXTR_IF_EXISTS);
631
632
        // https://regex101.com/r/n9TWHF/1
633 1
        $pattern = '(.*)<!--[[:blank:]]?('.$separator.')[[:blank:]]?-->(.*)';
634 1
        preg_match('/'.$pattern.'/is', $string, $matches);
635
636 1
        if (empty($matches)) {
637 1
            return $string;
638
        }
639 1
        if ($capture == 'after') {
640
            return trim($matches[3]);
641
        }
642
        // remove footnotes
643 1
        return preg_replace('/<sup[^>]*>[^u]*<\/sup>/', '', trim($matches[1]));
644
    }
645
646
    /**
647
     * Converts a Markdown string to HTML.
648
     *
649
     * @throws RuntimeException
650
     */
651 1
    public function markdownToHtml(?string $markdown): ?string
652
    {
653 1
        $markdown = $markdown ?? '';
654
655
        try {
656 1
            $parsedown = new Parsedown($this->builder);
657 1
            $html = $parsedown->text($markdown);
658
        } catch (\Exception $e) {
659
            throw new RuntimeException('"markdown_to_html" filter can not convert supplied Markdown.');
660
        }
661
662 1
        return $html;
663
    }
664
665
    /**
666
     * Extract table of content of a Markdown string,
667
     * in the given format ("html" or "json", "html" by default).
668
     *
669
     * @throws RuntimeException
670
     */
671
    public function markdownToToc(?string $markdown, $format = 'html'): ?string
672
    {
673
        $markdown = $markdown ?? '';
674
675
        try {
676
            $parsedown = new Parsedown($this->builder, ['selectors' => ['h2']]);
677
            $parsedown->body($markdown);
678
            $return = $parsedown->contentsList($format);
679
        } catch (\Exception $e) {
680
            throw new RuntimeException('"toc" filter can not convert supplied Markdown.');
681
        }
682
683
        return $return;
684
    }
685
686
    /**
687
     * Converts a JSON string to an array.
688
     *
689
     * @throws RuntimeException
690
     */
691 1
    public function jsonDecode(?string $json): ?array
692
    {
693 1
        $json = $json ?? '';
694
695
        try {
696 1
            $array = json_decode($json, true);
697 1
            if ($array === null && json_last_error() !== JSON_ERROR_NONE) {
698 1
                throw new \Exception('JSON error.');
699
            }
700
        } catch (\Exception $e) {
701
            throw new RuntimeException('"json_decode" filter can not parse supplied JSON.');
702
        }
703
704 1
        return $array;
705
    }
706
707
    /**
708
     * Converts a YAML string to an array.
709
     *
710
     * @throws RuntimeException
711
     */
712 1
    public function yamlParse(?string $yaml): ?array
713
    {
714 1
        $yaml = $yaml ?? '';
715
716
        try {
717 1
            $array = Yaml::parse($yaml);
718 1
            if (!is_array($array)) {
719 1
                throw new ParseException('YAML error.');
720
            }
721
        } catch (ParseException $e) {
722
            throw new RuntimeException(\sprintf('"yaml_parse" filter can not parse supplied YAML: %s', $e->getMessage()));
723
        }
724
725 1
        return $array;
726
    }
727
728
    /**
729
     * Split a string into an array using a regular expression.
730
     *
731
     * @throws RuntimeException
732
     */
733
    public function pregSplit(?string $value, string $pattern, int $limit = 0): ?array
734
    {
735
        $value = $value ?? '';
736
737
        try {
738
            $array = preg_split($pattern, $value, $limit);
739
            if ($array === false) {
740
                throw new RuntimeException('PREG split error.');
741
            }
742
        } catch (\Exception $e) {
743
            throw new RuntimeException('"preg_split" filter can not split supplied string.');
744
        }
745
746
        return $array;
747
    }
748
749
    /**
750
     * Perform a regular expression match and return the group for all matches.
751
     *
752
     * @throws RuntimeException
753
     */
754
    public function pregMatchAll(?string $value, string $pattern, int $group = 0): ?array
755
    {
756
        $value = $value ?? '';
757
758
        try {
759
            $array = preg_match_all($pattern, $value, $matches, PREG_PATTERN_ORDER);
760
            if ($array === false) {
761
                throw new RuntimeException('PREG match all error.');
762
            }
763
        } catch (\Exception $e) {
764
            throw new RuntimeException('"preg_match_all" filter can not match in supplied string.');
765
        }
766
767
        return $matches[$group];
768
    }
769
770
    /**
771
     * Calculates estimated time to read a text.
772
     */
773
    public function readtime(?string $text): string
774
    {
775
        $text = $text ?? '';
776
777
        $words = str_word_count(strip_tags($text));
778
        $min = floor($words / 200);
779
        if ($min === 0) {
780
            return '1';
781
        }
782
783
        return (string) $min;
784
    }
785
786
    /**
787
     * Gets the value of an environment variable.
788
     */
789 1
    public function getEnv(?string $var): ?string
790
    {
791 1
        $var = $var ?? '';
792
793 1
        return getenv($var) ?: null;
794
    }
795
796
    /**
797
     * Tests if a variable is an Asset.
798
     */
799
    public function isAsset($variable): bool
800
    {
801
        return $variable instanceof Asset;
802
    }
803
804
    /**
805
     * Returns the dominant hex color of an image asset.
806
     *
807
     * @param string|Asset $path
808
     *
809
     * @return string
810
     */
811 1
    public function dominantColor($asset): string
812
    {
813 1
        if (!$asset instanceof Asset) {
814
            $asset = new Asset($this->builder, $asset);
815
        }
816
817 1
        return Image::getDominantColor($asset);
818
    }
819
820
    /**
821
     * Converts an hexadecimal color to RGB.
822
     *
823
     * @throws RuntimeException
824
     */
825
    public function hexToRgb(?string $variable): array
826
    {
827
        $variable = $variable ?? '';
828
829
        if (!self::isHex($variable)) {
830
            throw new RuntimeException(\sprintf('"%s" is not a valid hexadecimal value.', $variable));
831
        }
832
        $hex = ltrim($variable, '#');
833
        if (strlen($hex) == 3) {
834
            $hex = $hex[0].$hex[0].$hex[1].$hex[1].$hex[2].$hex[2];
835
        }
836
        $c = hexdec($hex);
837
838
        return [
839
            'red'   => $c >> 16 & 0xFF,
840
            'green' => $c >> 8 & 0xFF,
841
            'blue'  => $c & 0xFF,
842
        ];
843
    }
844
845
    /**
846
     * Is a hexadecimal color is valid?
847
     */
848
    private static function isHex(string $hex): bool
849
    {
850
        $valid = is_string($hex);
851
        $hex = ltrim($hex, '#');
852
        $length = strlen($hex);
853
        $valid = $valid && ($length === 3 || $length === 6);
854
        $valid = $valid && ctype_xdigit($hex);
855
856
        return $valid;
857
    }
858
}
859