Test Failed
Pull Request — master (#1664)
by Arnaud
08:39 queued 04:04
created

Core   F

Complexity

Total Complexity 109

Size/Duplication

Total Lines 852
Duplicated Lines 0 %

Test Coverage

Coverage 64.87%

Importance

Changes 4
Bugs 1 Features 1
Metric Value
eloc 344
dl 0
loc 852
ccs 253
cts 390
cp 0.6487
rs 2
c 4
b 1
f 1
wmc 109

39 Methods

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

How to fix   Complexity   

Complex Class

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

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

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

1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of Cecil.
7
 *
8
 * Copyright (c) Arnaud Ligny <[email protected]>
9
 *
10
 * For the full copyright and license information, please view the LICENSE
11
 * file that was distributed with this source code.
12
 */
13
14
namespace Cecil\Renderer\Extension;
15
16
use Cecil\Assets\Asset;
17
use Cecil\Assets\Cache;
18
use Cecil\Assets\Image;
19
use Cecil\Assets\Url;
20
use Cecil\Builder;
21
use Cecil\Collection\CollectionInterface;
22
use Cecil\Collection\Page\Collection as PagesCollection;
23
use Cecil\Collection\Page\Page;
24
use Cecil\Collection\Page\Type;
25
use Cecil\Config;
26
use Cecil\Converter\Parsedown;
27
use Cecil\Exception\RuntimeException;
28
use Cocur\Slugify\Bridge\Twig\SlugifyExtension;
29
use Cocur\Slugify\Slugify;
30
use MatthiasMullie\Minify;
31
use ScssPhp\ScssPhp\Compiler;
32
use Symfony\Component\Yaml\Exception\ParseException;
33
use Symfony\Component\Yaml\Yaml;
34
35
/**
36
 * Class Renderer\Extension\Core.
37
 */
38
class Core extends SlugifyExtension
39
{
40
    /** @var Builder */
41
    protected $builder;
42
43
    /** @var Config */
44
    protected $config;
45
46
    /** @var Slugify */
47
    private static $slugifier;
48
49 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
            new \Twig\TwigFilter('lqip', [$this, 'lqip']),
128 1
            // content
129 1
            new \Twig\TwigFilter('slugify', [$this, 'slugifyFilter']),
130 1
            new \Twig\TwigFilter('excerpt', [$this, 'excerpt']),
131 1
            new \Twig\TwigFilter('excerpt_html', [$this, 'excerptHtml']),
132 1
            new \Twig\TwigFilter('markdown_to_html', [$this, 'markdownToHtml']),
133 1
            new \Twig\TwigFilter('toc', [$this, 'markdownToToc']),
134 1
            new \Twig\TwigFilter('json_decode', [$this, 'jsonDecode']),
135 1
            new \Twig\TwigFilter('yaml_parse', [$this, 'yamlParse']),
136 1
            new \Twig\TwigFilter('preg_split', [$this, 'pregSplit']),
137 1
            new \Twig\TwigFilter('preg_match_all', [$this, 'pregMatchAll']),
138 1
            new \Twig\TwigFilter('hex_to_rgb', [$this, 'hexToRgb']),
139
            new \Twig\TwigFilter('splitline', [$this, 'splitLine']),
140 1
            // deprecated
141 1
            new \Twig\TwigFilter(
142 1
                'filterBySection',
143 1
                [$this, 'filterBySection'],
144 1
                ['deprecated' => true, 'alternative' => 'filter_by']
145 1
            ),
146 1
            new \Twig\TwigFilter(
147 1
                'filterBy',
148 1
                [$this, 'filterBy'],
149 1
                ['deprecated' => true, 'alternative' => 'filter_by']
150 1
            ),
151 1
            new \Twig\TwigFilter(
152 1
                'sortByTitle',
153 1
                [$this, 'sortByTitle'],
154 1
                ['deprecated' => true, 'alternative' => 'sort_by_title']
155 1
            ),
156 1
            new \Twig\TwigFilter(
157 1
                'sortByWeight',
158 1
                [$this, 'sortByWeight'],
159 1
                ['deprecated' => true, 'alternative' => 'sort_by_weight']
160 1
            ),
161 1
            new \Twig\TwigFilter(
162 1
                'sortByDate',
163 1
                [$this, 'sortByDate'],
164 1
                ['deprecated' => true, 'alternative' => 'sort_by_date']
165 1
            ),
166 1
            new \Twig\TwigFilter(
167 1
                'minifyCSS',
168 1
                [$this, 'minifyCss'],
169 1
                ['deprecated' => true, 'alternative' => 'minifyCss']
170 1
            ),
171 1
            new \Twig\TwigFilter(
172 1
                'minifyJS',
173 1
                [$this, 'minifyJs'],
174 1
                ['deprecated' => true, 'alternative' => 'minifyJs']
175 1
            ),
176 1
            new \Twig\TwigFilter(
177 1
                'SCSStoCSS',
178 1
                [$this, 'scssToCss'],
179 1
                ['deprecated' => true, 'alternative' => 'scss_to_css']
180 1
            ),
181 1
            new \Twig\TwigFilter(
182 1
                'excerptHtml',
183 1
                [$this, 'excerptHtml'],
184 1
                ['deprecated' => true, 'alternative' => 'excerpt_html']
185 1
            ),
186 1
            new \Twig\TwigFilter(
187 1
                'urlize',
188 1
                [$this, 'slugifyFilter'],
189 1
                ['deprecated' => true, 'alternative' => 'slugify']
190 1
            ),
191
        ];
192
    }
193
194
    /**
195
     * {@inheritdoc}
196 1
     */
197
    public function getTests()
198 1
    {
199 1
        return [
200 1
            new \Twig\TwigTest('asset', [$this, 'isAsset']),
201
        ];
202
    }
203
204
    /**
205
     * Filters by Section.
206
     */
207
    public function filterBySection(PagesCollection $pages, string $section): CollectionInterface
208
    {
209
        return $this->filterBy($pages, 'section', $section);
210
    }
211
212
    /**
213
     * Filters a pages collection by variable's name/value.
214 1
     */
215
    public function filterBy(PagesCollection $pages, string $variable, string $value): CollectionInterface
216 1
    {
217
        $filteredPages = $pages->filter(function (Page $page) use ($variable, $value) {
218 1
            // is a dedicated getter exists?
219 1
            $method = 'get' . ucfirst($variable);
220
            if (method_exists($page, $method) && $page->$method() == $value) {
221
                return $page->getType() == Type::PAGE() && !$page->isVirtual() && true;
222
            }
223 1
            // or a classic variable
224 1
            if ($page->getVariable($variable) == $value) {
225
                return $page->getType() == Type::PAGE() && !$page->isVirtual() && true;
226 1
            }
227
        });
228 1
229
        return $filteredPages;
230
    }
231
232
    /**
233
     * Sorts a collection by title.
234 1
     */
235
    public function sortByTitle(\Traversable $collection): array
236 1
    {
237
        $sort = \SORT_ASC;
238 1
239 1
        $collection = iterator_to_array($collection);
240
        array_multisort(array_keys(/** @scrutinizer ignore-type */ $collection), $sort, \SORT_NATURAL | \SORT_FLAG_CASE, $collection);
0 ignored issues
show
Bug introduced by
array_keys($collection) cannot be passed to array_multisort() as the parameter $array expects a reference. ( Ignorable by Annotation )

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

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

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

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