Passed
Push — master ( dd54b4...24f848 )
by Arnaud
05:44
created

Core::varDump()   A

Complexity

Conditions 6
Paths 3

Size

Total Lines 21
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 7.0487

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 6
eloc 12
c 1
b 0
f 0
nc 3
nop 4
dl 0
loc 21
ccs 9
cts 13
cp 0.6923
crap 7.0487
rs 9.2222
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\VarDumper\Cloner\VarCloner;
33
use Symfony\Component\VarDumper\Dumper\HtmlDumper;
34
use Symfony\Component\Yaml\Exception\ParseException;
35
use Symfony\Component\Yaml\Yaml;
36
37
/**
38
 * Class Renderer\Extension\Core.
39
 */
40
class Core extends SlugifyExtension
41
{
42
    /** @var Builder */
43
    protected $builder;
44
45
    /** @var Config */
46
    protected $config;
47
48
    /** @var Slugify */
49
    private static $slugifier;
50
51 1
    public function __construct(Builder $builder)
52
    {
53 1
        if (!self::$slugifier instanceof Slugify) {
54 1
            self::$slugifier = Slugify::create(['regexp' => Page::SLUGIFY_PATTERN]);
55
        }
56
57 1
        parent::__construct(self::$slugifier);
58
59 1
        $this->builder = $builder;
60 1
        $this->config = $builder->getConfig();
61
    }
62
63
    /**
64
     * {@inheritdoc}
65
     */
66
    public function getName()
67
    {
68
        return 'CoreExtension';
69
    }
70
71
    /**
72
     * {@inheritdoc}
73
     */
74 1
    public function getFunctions()
75
    {
76 1
        return [
77 1
            new \Twig\TwigFunction('url', [$this, 'url']),
78
            // assets
79 1
            new \Twig\TwigFunction('asset', [$this, 'asset']),
80 1
            new \Twig\TwigFunction('integrity', [$this, 'integrity']),
81 1
            new \Twig\TwigFunction('image_srcset', [$this, 'imageSrcset']),
82 1
            new \Twig\TwigFunction('image_sizes', [$this, 'imageSizes']),
83
            // content
84 1
            new \Twig\TwigFunction('readtime', [$this, 'readtime']),
85
            // others
86 1
            new \Twig\TwigFunction('getenv', [$this, 'getEnv']),
87 1
            new \Twig\TwigFunction('d', [$this, 'varDump'], ['needs_context' => true, 'needs_environment' => true]),
88
            // deprecated
89 1
            new \Twig\TwigFunction(
90 1
                'hash',
91 1
                [$this, 'integrity'],
92 1
                ['deprecated' => true, 'alternative' => 'integrity']
93 1
            ),
94 1
            new \Twig\TwigFunction(
95 1
                'minify',
96 1
                [$this, 'minify'],
97 1
                ['deprecated' => true, 'alternative' => 'minify filter']
98 1
            ),
99 1
            new \Twig\TwigFunction(
100 1
                'toCSS',
101 1
                [$this, 'toCss'],
102 1
                ['deprecated' => true, 'alternative' => 'to_css filter']
103 1
            ),
104 1
        ];
105
    }
106
107
    /**
108
     * {@inheritdoc}
109
     */
110 1
    public function getFilters()
111
    {
112 1
        return [
113 1
            new \Twig\TwigFilter('url', [$this, 'url']),
114
            // collections
115 1
            new \Twig\TwigFilter('sort_by_title', [$this, 'sortByTitle']),
116 1
            new \Twig\TwigFilter('sort_by_weight', [$this, 'sortByWeight']),
117 1
            new \Twig\TwigFilter('sort_by_date', [$this, 'sortByDate']),
118 1
            new \Twig\TwigFilter('filter_by', [$this, 'filterBy']),
119
            // assets
120 1
            new \Twig\TwigFilter('html', [$this, 'html']),
121 1
            new \Twig\TwigFilter('inline', [$this, 'inline']),
122 1
            new \Twig\TwigFilter('fingerprint', [$this, 'fingerprint']),
123 1
            new \Twig\TwigFilter('to_css', [$this, 'toCss']),
124 1
            new \Twig\TwigFilter('minify', [$this, 'minify']),
125 1
            new \Twig\TwigFilter('minify_css', [$this, 'minifyCss']),
126 1
            new \Twig\TwigFilter('minify_js', [$this, 'minifyJs']),
127 1
            new \Twig\TwigFilter('scss_to_css', [$this, 'scssToCss']),
128 1
            new \Twig\TwigFilter('sass_to_css', [$this, 'scssToCss']),
129 1
            new \Twig\TwigFilter('resize', [$this, 'resize']),
130 1
            new \Twig\TwigFilter('dataurl', [$this, 'dataurl']),
131 1
            new \Twig\TwigFilter('dominant_color', [$this, 'dominantColor']),
132 1
            new \Twig\TwigFilter('lqip', [$this, 'lqip']),
133 1
            new \Twig\TwigFilter('webp', [$this, 'webp']),
134
            // content
135 1
            new \Twig\TwigFilter('slugify', [$this, 'slugifyFilter']),
136 1
            new \Twig\TwigFilter('excerpt', [$this, 'excerpt']),
137 1
            new \Twig\TwigFilter('excerpt_html', [$this, 'excerptHtml']),
138 1
            new \Twig\TwigFilter('markdown_to_html', [$this, 'markdownToHtml']),
139 1
            new \Twig\TwigFilter('toc', [$this, 'markdownToToc']),
140 1
            new \Twig\TwigFilter('json_decode', [$this, 'jsonDecode']),
141 1
            new \Twig\TwigFilter('yaml_parse', [$this, 'yamlParse']),
142 1
            new \Twig\TwigFilter('preg_split', [$this, 'pregSplit']),
143 1
            new \Twig\TwigFilter('preg_match_all', [$this, 'pregMatchAll']),
144 1
            new \Twig\TwigFilter('hex_to_rgb', [$this, 'hexToRgb']),
145 1
            new \Twig\TwigFilter('splitline', [$this, 'splitLine']),
146
            // deprecated
147 1
            new \Twig\TwigFilter(
148 1
                'filterBySection',
149 1
                [$this, 'filterBySection'],
150 1
                ['deprecated' => true, 'alternative' => 'filter_by']
151 1
            ),
152 1
            new \Twig\TwigFilter(
153 1
                'filterBy',
154 1
                [$this, 'filterBy'],
155 1
                ['deprecated' => true, 'alternative' => 'filter_by']
156 1
            ),
157 1
            new \Twig\TwigFilter(
158 1
                'sortByTitle',
159 1
                [$this, 'sortByTitle'],
160 1
                ['deprecated' => true, 'alternative' => 'sort_by_title']
161 1
            ),
162 1
            new \Twig\TwigFilter(
163 1
                'sortByWeight',
164 1
                [$this, 'sortByWeight'],
165 1
                ['deprecated' => true, 'alternative' => 'sort_by_weight']
166 1
            ),
167 1
            new \Twig\TwigFilter(
168 1
                'sortByDate',
169 1
                [$this, 'sortByDate'],
170 1
                ['deprecated' => true, 'alternative' => 'sort_by_date']
171 1
            ),
172 1
            new \Twig\TwigFilter(
173 1
                'minifyCSS',
174 1
                [$this, 'minifyCss'],
175 1
                ['deprecated' => true, 'alternative' => 'minifyCss']
176 1
            ),
177 1
            new \Twig\TwigFilter(
178 1
                'minifyJS',
179 1
                [$this, 'minifyJs'],
180 1
                ['deprecated' => true, 'alternative' => 'minifyJs']
181 1
            ),
182 1
            new \Twig\TwigFilter(
183 1
                'SCSStoCSS',
184 1
                [$this, 'scssToCss'],
185 1
                ['deprecated' => true, 'alternative' => 'scss_to_css']
186 1
            ),
187 1
            new \Twig\TwigFilter(
188 1
                'excerptHtml',
189 1
                [$this, 'excerptHtml'],
190 1
                ['deprecated' => true, 'alternative' => 'excerpt_html']
191 1
            ),
192 1
            new \Twig\TwigFilter(
193 1
                'urlize',
194 1
                [$this, 'slugifyFilter'],
195 1
                ['deprecated' => true, 'alternative' => 'slugify']
196 1
            ),
197 1
        ];
198
    }
199
200
    /**
201
     * {@inheritdoc}
202
     */
203 1
    public function getTests()
204
    {
205 1
        return [
206 1
            new \Twig\TwigTest('asset', [$this, 'isAsset']),
207 1
        ];
208
    }
209
210
    /**
211
     * Filters by Section.
212
     */
213
    public function filterBySection(PagesCollection $pages, string $section): CollectionInterface
214
    {
215
        return $this->filterBy($pages, 'section', $section);
216
    }
217
218
    /**
219
     * Filters a pages collection by variable's name/value.
220
     */
221 1
    public function filterBy(PagesCollection $pages, string $variable, string $value): CollectionInterface
222
    {
223 1
        $filteredPages = $pages->filter(function (Page $page) use ($variable, $value) {
224
            // is a dedicated getter exists?
225 1
            $method = 'get' . ucfirst($variable);
226 1
            if (method_exists($page, $method) && $page->$method() == $value) {
227
                return $page->getType() == Type::PAGE() && !$page->isVirtual() && true;
228
            }
229
            // or a classic variable
230 1
            if ($page->getVariable($variable) == $value) {
231 1
                return $page->getType() == Type::PAGE() && !$page->isVirtual() && true;
232
            }
233 1
        });
234
235 1
        return $filteredPages;
236
    }
237
238
    /**
239
     * Sorts a collection by title.
240
     */
241 1
    public function sortByTitle(\Traversable $collection): array
242
    {
243 1
        $sort = \SORT_ASC;
244
245 1
        $collection = iterator_to_array($collection);
246 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

246
        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

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