Passed
Push — toc-url ( 47c560...bce3ef )
by Arnaud
10:27 queued 05:58
created

Core::sortByDate()   A

Complexity

Conditions 6
Paths 1

Size

Total Lines 20
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 6.027

Importance

Changes 1
Bugs 1 Features 0
Metric Value
cc 6
eloc 9
nc 1
nop 3
dl 0
loc 20
ccs 10
cts 11
cp 0.9091
crap 6.027
rs 9.2222
c 1
b 1
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 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 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 1
        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 1
                'hash',
86 1
                [$this, 'integrity'],
87 1
                ['deprecated' => true, 'alternative' => 'integrity']
88 1
            ),
89 1
            new \Twig\TwigFunction(
90 1
                'minify',
91 1
                [$this, 'minify'],
92 1
                ['deprecated' => true, 'alternative' => 'minify filter']
93 1
            ),
94 1
            new \Twig\TwigFunction(
95 1
                'toCSS',
96 1
                [$this, 'toCss'],
97 1
                ['deprecated' => true, 'alternative' => 'to_css filter']
98 1
            ),
99 1
        ];
100
    }
101
102
    /**
103
     * {@inheritdoc}
104
     */
105 1
    public function getFilters()
106
    {
107 1
        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 1
                'filterBySection',
141 1
                [$this, 'filterBySection'],
142 1
                ['deprecated' => true, 'alternative' => 'filter_by']
143 1
            ),
144 1
            new \Twig\TwigFilter(
145 1
                'filterBy',
146 1
                [$this, 'filterBy'],
147 1
                ['deprecated' => true, 'alternative' => 'filter_by']
148 1
            ),
149 1
            new \Twig\TwigFilter(
150 1
                'sortByTitle',
151 1
                [$this, 'sortByTitle'],
152 1
                ['deprecated' => true, 'alternative' => 'sort_by_title']
153 1
            ),
154 1
            new \Twig\TwigFilter(
155 1
                'sortByWeight',
156 1
                [$this, 'sortByWeight'],
157 1
                ['deprecated' => true, 'alternative' => 'sort_by_weight']
158 1
            ),
159 1
            new \Twig\TwigFilter(
160 1
                'sortByDate',
161 1
                [$this, 'sortByDate'],
162 1
                ['deprecated' => true, 'alternative' => 'sort_by_date']
163 1
            ),
164 1
            new \Twig\TwigFilter(
165 1
                'minifyCSS',
166 1
                [$this, 'minifyCss'],
167 1
                ['deprecated' => true, 'alternative' => 'minifyCss']
168 1
            ),
169 1
            new \Twig\TwigFilter(
170 1
                'minifyJS',
171 1
                [$this, 'minifyJs'],
172 1
                ['deprecated' => true, 'alternative' => 'minifyJs']
173 1
            ),
174 1
            new \Twig\TwigFilter(
175 1
                'SCSStoCSS',
176 1
                [$this, 'scssToCss'],
177 1
                ['deprecated' => true, 'alternative' => 'scss_to_css']
178 1
            ),
179 1
            new \Twig\TwigFilter(
180 1
                'excerptHtml',
181 1
                [$this, 'excerptHtml'],
182 1
                ['deprecated' => true, 'alternative' => 'excerpt_html']
183 1
            ),
184 1
            new \Twig\TwigFilter(
185 1
                'urlize',
186 1
                [$this, 'slugifyFilter'],
187 1
                ['deprecated' => true, 'alternative' => 'slugify']
188 1
            ),
189 1
        ];
190
    }
191
192
    /**
193
     * {@inheritdoc}
194
     */
195 1
    public function getTests()
196
    {
197 1
        return [
198 1
            new \Twig\TwigTest('asset', [$this, 'isAsset']),
199 1
        ];
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 1
        });
226
227 1
        return $filteredPages;
228
    }
229
230
    /**
231
     * Sorts a collection by title.
232
     */
233 1
    public function sortByTitle(\Traversable $collection): array
234
    {
235 1
        $sort = \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): array
248
    {
249 1
        $callback = function ($a, $b) {
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 $a['weight'] < $b['weight'] ? -1 : 1;
261 1
        };
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 $descTitle = false): array
274
    {
275 1
        $callback = function ($a, $b) use ($variable, $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 strnatcmp($b['title'], $a['title']);
280
                }
281
282 1
                return 0;
283
            }
284
285 1
            return $a[$variable] > $b[$variable] ? -1 : 1;
286 1
        };
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 1
                        '<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 1
                        $htmlAttributes
536 1
                    );
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
            $sizes = '';
547 1
            if ($responsive && $srcset = Image::buildSrcset(
548 1
                $asset,
549 1
                $this->config->get('assets.images.responsive.widths') ?? [480, 640, 768, 1024, 1366, 1600, 1920]
550 1
            )) {
551
                $htmlAttributes .= \sprintf(' srcset="%s"', $srcset);
552
                $sizes = $this->config->get('assets.images.responsive.sizes.default') ?? '100vw';
553
                if (isset($attributes['class'])) {
554
                    $sizes = Image::getSizes($attributes['class'], (array) $this->builder->getConfig()->get('assets.images.responsive.sizes'));
555
                }
556
                $htmlAttributes .= \sprintf(' sizes="%s"', $sizes);
557
            }
558
559
            // <img> element
560 1
            $img = \sprintf(
561 1
                '<img src="%s" width="'.($asset->getWidth() ?: '').'" height="'.($asset->getHeight() ?: '').'"%s>',
562 1
                $this->url($asset, $options),
563 1
                $htmlAttributes
564 1
            );
565
566
            // WebP conversion?
567 1
            if ($webp && $asset['subtype'] != 'image/webp' && !Image::isAnimatedGif($asset)) {
568
                try {
569 1
                    $assetWebp = Image::convertTopWebp($asset, $this->config->get('assets.images.quality') ?? 75);
570
                    // <source> element
571
                    $source = \sprintf('<source type="image/webp" srcset="%s">', $assetWebp);
572
                    // responsive
573
                    if ($responsive) {
574
                        $srcset = Image::buildSrcset(
575
                            $assetWebp,
576
                            $this->config->get('assets.images.responsive.widths') ?? [480, 640, 768, 1024, 1366, 1600, 1920]
577
                        ) ?: (string) $assetWebp;
578
                        // <source> element
579
                        $source = \sprintf(
580
                            '<source type="image/webp" srcset="%s" sizes="%s">',
581
                            $srcset,
582
                            $sizes
583
                        );
584
                    }
585
586
                    return \sprintf("<picture>\n  %s\n  %s\n</picture>", $source, $img);
587 1
                } catch (\Exception $e) {
588 1
                    $this->builder->getLogger()->debug($e->getMessage());
589
                }
590
            }
591
592 1
            return $img;
593
        }
594
595
        throw new RuntimeException(\sprintf('%s is available for CSS, JavaScript and images files only.', '"html" filter'));
596
    }
597
598
    /**
599
     * Returns the content of an asset.
600
     */
601 1
    public function inline(Asset $asset): string
602
    {
603 1
        return $asset['content'];
604
    }
605
606
    /**
607
     * Reads $length first characters of a string and adds a suffix.
608
     */
609
    public function excerpt(?string $string, int $length = 450, string $suffix = ' …'): string
610
    {
611
        $string = $string ?? '';
612
613
        $string = str_replace('</p>', '<br /><br />', $string);
614
        $string = trim(strip_tags($string, '<br>'), '<br />');
615
        if (mb_strlen($string) > $length) {
616
            $string = mb_substr($string, 0, $length);
617
            $string .= $suffix;
618
        }
619
620
        return $string;
621
    }
622
623
    /**
624
     * Reads characters before or after '<!-- separator -->'.
625
     * Options:
626
     *  - separator: string to use as separator (`excerpt|break` by default)
627
     *  - capture: part to capture, `before` or `after` the separator (`before` by default).
628
     */
629 1
    public function excerptHtml(?string $string, array $options = []): string
630
    {
631 1
        $string = $string ?? '';
632
633 1
        $separator = $this->builder->getConfig()->get('body.excerpt.separator');
634 1
        $capture = $this->builder->getConfig()->get('body.excerpt.capture');
635 1
        extract($options, EXTR_IF_EXISTS);
636
637
        // https://regex101.com/r/n9TWHF/1
638 1
        $pattern = '(.*)<!--[[:blank:]]?('.$separator.')[[:blank:]]?-->(.*)';
639 1
        preg_match('/'.$pattern.'/is', $string, $matches);
640
641 1
        if (empty($matches)) {
642 1
            return $string;
643
        }
644 1
        $result = trim($matches[1]);
645 1
        if ($capture == 'after') {
646 1
            $result = trim($matches[3]);
647
        }
648
        // removes footnotes and returns result
649 1
        return preg_replace('/<sup[^>]*>[^u]*<\/sup>/', '', $result);
650
    }
651
652
    /**
653
     * Converts a Markdown string to HTML.
654
     *
655
     * @throws RuntimeException
656
     */
657 1
    public function markdownToHtml(?string $markdown): ?string
658
    {
659 1
        $markdown = $markdown ?? '';
660
661
        try {
662 1
            $parsedown = new Parsedown($this->builder);
663 1
            $html = $parsedown->text($markdown);
664
        } catch (\Exception $e) {
665
            throw new RuntimeException('"markdown_to_html" filter can not convert supplied Markdown.');
666
        }
667
668 1
        return $html;
669
    }
670
671
    /**
672
     * Extract table of content of a Markdown string,
673
     * in the given format ("html" or "json", "html" by default).
674
     *
675
     * @throws RuntimeException
676
     */
677
    public function markdownToToc(?string $markdown, $format = 'html', $url = ''): ?string
678
    {
679
        $markdown = $markdown ?? '';
680
681
        try {
682
            $parsedown = new Parsedown($this->builder, ['selectors' => ['h2'], 'url' => $url]);
683
            $parsedown->body($markdown);
684
            $return = $parsedown->contentsList($format);
685
        } catch (\Exception $e) {
686
            throw new RuntimeException('"toc" filter can not convert supplied Markdown.');
687
        }
688
689
        return $return;
690
    }
691
692
    /**
693
     * Converts a JSON string to an array.
694
     *
695
     * @throws RuntimeException
696
     */
697 1
    public function jsonDecode(?string $json): ?array
698
    {
699 1
        $json = $json ?? '';
700
701
        try {
702 1
            $array = json_decode($json, true);
703 1
            if ($array === null && json_last_error() !== JSON_ERROR_NONE) {
704 1
                throw new \Exception('JSON error.');
705
            }
706
        } catch (\Exception $e) {
707
            throw new RuntimeException('"json_decode" filter can not parse supplied JSON.');
708
        }
709
710 1
        return $array;
711
    }
712
713
    /**
714
     * Converts a YAML string to an array.
715
     *
716
     * @throws RuntimeException
717
     */
718 1
    public function yamlParse(?string $yaml): ?array
719
    {
720 1
        $yaml = $yaml ?? '';
721
722
        try {
723 1
            $array = Yaml::parse($yaml);
724 1
            if (!is_array($array)) {
725 1
                throw new ParseException('YAML error.');
726
            }
727
        } catch (ParseException $e) {
728
            throw new RuntimeException(\sprintf('"yaml_parse" filter can not parse supplied YAML: %s', $e->getMessage()));
729
        }
730
731 1
        return $array;
732
    }
733
734
    /**
735
     * Split a string into an array using a regular expression.
736
     *
737
     * @throws RuntimeException
738
     */
739
    public function pregSplit(?string $value, string $pattern, int $limit = 0): ?array
740
    {
741
        $value = $value ?? '';
742
743
        try {
744
            $array = preg_split($pattern, $value, $limit);
745
            if ($array === false) {
746
                throw new RuntimeException('PREG split error.');
747
            }
748
        } catch (\Exception $e) {
749
            throw new RuntimeException('"preg_split" filter can not split supplied string.');
750
        }
751
752
        return $array;
753
    }
754
755
    /**
756
     * Perform a regular expression match and return the group for all matches.
757
     *
758
     * @throws RuntimeException
759
     */
760
    public function pregMatchAll(?string $value, string $pattern, int $group = 0): ?array
761
    {
762
        $value = $value ?? '';
763
764
        try {
765
            $array = preg_match_all($pattern, $value, $matches, PREG_PATTERN_ORDER);
766
            if ($array === false) {
767
                throw new RuntimeException('PREG match all error.');
768
            }
769
        } catch (\Exception $e) {
770
            throw new RuntimeException('"preg_match_all" filter can not match in supplied string.');
771
        }
772
773
        return $matches[$group];
774
    }
775
776
    /**
777
     * Calculates estimated time to read a text.
778
     */
779
    public function readtime(?string $text): string
780
    {
781
        $text = $text ?? '';
782
783
        $words = str_word_count(strip_tags($text));
784
        $min = floor($words / 200);
785
        if ($min === 0) {
786
            return '1';
787
        }
788
789
        return (string) $min;
790
    }
791
792
    /**
793
     * Gets the value of an environment variable.
794
     */
795 1
    public function getEnv(?string $var): ?string
796
    {
797 1
        $var = $var ?? '';
798
799 1
        return getenv($var) ?: null;
800
    }
801
802
    /**
803
     * Tests if a variable is an Asset.
804
     */
805
    public function isAsset($variable): bool
806
    {
807
        return $variable instanceof Asset;
808
    }
809
810
    /**
811
     * Returns the dominant hex color of an image asset.
812
     *
813
     * @param string|Asset $path
814
     *
815
     * @return string
816
     */
817 1
    public function dominantColor($asset): string
818
    {
819 1
        if (!$asset instanceof Asset) {
820
            $asset = new Asset($this->builder, $asset);
821
        }
822
823 1
        return Image::getDominantColor($asset);
824
    }
825
826
    /**
827
     * Converts an hexadecimal color to RGB.
828
     *
829
     * @throws RuntimeException
830
     */
831
    public function hexToRgb(?string $variable): array
832
    {
833
        $variable = $variable ?? '';
834
835
        if (!self::isHex($variable)) {
836
            throw new RuntimeException(\sprintf('"%s" is not a valid hexadecimal value.', $variable));
837
        }
838
        $hex = ltrim($variable, '#');
839
        if (strlen($hex) == 3) {
840
            $hex = $hex[0].$hex[0].$hex[1].$hex[1].$hex[2].$hex[2];
841
        }
842
        $c = hexdec($hex);
843
844
        return [
845
            'red'   => $c >> 16 & 0xFF,
846
            'green' => $c >> 8 & 0xFF,
847
            'blue'  => $c & 0xFF,
848
        ];
849
    }
850
851
    /**
852
     * Is a hexadecimal color is valid?
853
     */
854
    private static function isHex(string $hex): bool
855
    {
856
        $valid = is_string($hex);
857
        $hex = ltrim($hex, '#');
858
        $length = strlen($hex);
859
        $valid = $valid && ($length === 3 || $length === 6);
860
        $valid = $valid && ctype_xdigit($hex);
861
862
        return $valid;
863
    }
864
}
865