• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

Cecilapp / Cecil / 5063085769

pending completion
5063085769

push

github

Arnaud Ligny
Update assets.html.twig

2794 of 3393 relevant lines covered (82.35%)

0.82 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

68.31
/src/Renderer/Extension/Core.php
1
<?php
2

3
declare(strict_types=1);
4

5
/*
6
 * This file is part of Cecil.
7
 *
8
 * Copyright (c) Arnaud Ligny <arnaud@ligny.fr>
9
 *
10
 * For the full copyright and license information, please view the LICENSE
11
 * file that was distributed with this source code.
12
 */
13

14
namespace Cecil\Renderer\Extension;
15

16
use Cecil\Assets\Asset;
17
use Cecil\Assets\Cache;
18
use Cecil\Assets\Image;
19
use Cecil\Assets\Url;
20
use Cecil\Builder;
21
use Cecil\Collection\CollectionInterface;
22
use Cecil\Collection\Page\Collection as PagesCollection;
23
use Cecil\Collection\Page\Page;
24
use Cecil\Collection\Page\Type;
25
use Cecil\Config;
26
use Cecil\Converter\Parsedown;
27
use Cecil\Exception\RuntimeException;
28
use Cocur\Slugify\Bridge\Twig\SlugifyExtension;
29
use Cocur\Slugify\Slugify;
30
use MatthiasMullie\Minify;
31
use ScssPhp\ScssPhp\Compiler;
32
use Symfony\Component\Yaml\Exception\ParseException;
33
use Symfony\Component\Yaml\Yaml;
34

35
/**
36
 * Class Renderer\Extension\Core.
37
 */
38
class Core extends SlugifyExtension
39
{
40
    /** @var Builder */
41
    protected $builder;
42

43
    /** @var Config */
44
    protected $config;
45

46
    /** @var Slugify */
47
    private static $slugifier;
48

49
    public function __construct(Builder $builder)
50
    {
51
        if (!self::$slugifier instanceof Slugify) {
1✔
52
            self::$slugifier = Slugify::create(['regexp' => Page::SLUGIFY_PATTERN]);
1✔
53
        }
54

55
        parent::__construct(self::$slugifier);
1✔
56

57
        $this->builder = $builder;
1✔
58
        $this->config = $builder->getConfig();
1✔
59
    }
60

61
    /**
62
     * {@inheritdoc}
63
     */
64
    public function getName()
65
    {
66
        return 'CoreExtension';
×
67
    }
68

69
    /**
70
     * {@inheritdoc}
71
     */
72
    public function getFunctions()
73
    {
74
        return [
1✔
75
            new \Twig\TwigFunction('url', [$this, 'url']),
1✔
76
            // assets
77
            new \Twig\TwigFunction('asset', [$this, 'asset']),
1✔
78
            new \Twig\TwigFunction('integrity', [$this, 'integrity']),
1✔
79
            new \Twig\TwigFunction('image_srcset', [$this, 'imageSrcset']),
1✔
80
            new \Twig\TwigFunction('image_sizes', [$this, 'imageSizes']),
1✔
81
            // content
82
            new \Twig\TwigFunction('readtime', [$this, 'readtime']),
1✔
83
            // others
84
            new \Twig\TwigFunction('getenv', [$this, 'getEnv']),
1✔
85
            // deprecated
86
            new \Twig\TwigFunction(
1✔
87
                'hash',
1✔
88
                [$this, 'integrity'],
1✔
89
                ['deprecated' => true, 'alternative' => 'integrity']
1✔
90
            ),
1✔
91
            new \Twig\TwigFunction(
1✔
92
                'minify',
1✔
93
                [$this, 'minify'],
1✔
94
                ['deprecated' => true, 'alternative' => 'minify filter']
1✔
95
            ),
1✔
96
            new \Twig\TwigFunction(
1✔
97
                'toCSS',
1✔
98
                [$this, 'toCss'],
1✔
99
                ['deprecated' => true, 'alternative' => 'to_css filter']
1✔
100
            ),
1✔
101
        ];
1✔
102
    }
103

104
    /**
105
     * {@inheritdoc}
106
     */
107
    public function getFilters()
108
    {
109
        return [
1✔
110
            new \Twig\TwigFilter('url', [$this, 'url']),
1✔
111
            // collections
112
            new \Twig\TwigFilter('sort_by_title', [$this, 'sortByTitle']),
1✔
113
            new \Twig\TwigFilter('sort_by_weight', [$this, 'sortByWeight']),
1✔
114
            new \Twig\TwigFilter('sort_by_date', [$this, 'sortByDate']),
1✔
115
            new \Twig\TwigFilter('filter_by', [$this, 'filterBy']),
1✔
116
            // assets
117
            new \Twig\TwigFilter('html', [$this, 'html']),
1✔
118
            new \Twig\TwigFilter('inline', [$this, 'inline']),
1✔
119
            new \Twig\TwigFilter('fingerprint', [$this, 'fingerprint']),
1✔
120
            new \Twig\TwigFilter('to_css', [$this, 'toCss']),
1✔
121
            new \Twig\TwigFilter('minify', [$this, 'minify']),
1✔
122
            new \Twig\TwigFilter('minify_css', [$this, 'minifyCss']),
1✔
123
            new \Twig\TwigFilter('minify_js', [$this, 'minifyJs']),
1✔
124
            new \Twig\TwigFilter('scss_to_css', [$this, 'scssToCss']),
1✔
125
            new \Twig\TwigFilter('sass_to_css', [$this, 'scssToCss']),
1✔
126
            new \Twig\TwigFilter('resize', [$this, 'resize']),
1✔
127
            new \Twig\TwigFilter('dataurl', [$this, 'dataurl']),
1✔
128
            new \Twig\TwigFilter('dominant_color', [$this, 'dominantColor']),
1✔
129
            new \Twig\TwigFilter('lqip', [$this, 'lqip']),
1✔
130
            new \Twig\TwigFilter('webp', [$this, 'webp']),
1✔
131
            // content
132
            new \Twig\TwigFilter('slugify', [$this, 'slugifyFilter']),
1✔
133
            new \Twig\TwigFilter('excerpt', [$this, 'excerpt']),
1✔
134
            new \Twig\TwigFilter('excerpt_html', [$this, 'excerptHtml']),
1✔
135
            new \Twig\TwigFilter('markdown_to_html', [$this, 'markdownToHtml']),
1✔
136
            new \Twig\TwigFilter('toc', [$this, 'markdownToToc']),
1✔
137
            new \Twig\TwigFilter('json_decode', [$this, 'jsonDecode']),
1✔
138
            new \Twig\TwigFilter('yaml_parse', [$this, 'yamlParse']),
1✔
139
            new \Twig\TwigFilter('preg_split', [$this, 'pregSplit']),
1✔
140
            new \Twig\TwigFilter('preg_match_all', [$this, 'pregMatchAll']),
1✔
141
            new \Twig\TwigFilter('hex_to_rgb', [$this, 'hexToRgb']),
1✔
142
            new \Twig\TwigFilter('splitline', [$this, 'splitLine']),
1✔
143
            // deprecated
144
            new \Twig\TwigFilter(
1✔
145
                'filterBySection',
1✔
146
                [$this, 'filterBySection'],
1✔
147
                ['deprecated' => true, 'alternative' => 'filter_by']
1✔
148
            ),
1✔
149
            new \Twig\TwigFilter(
1✔
150
                'filterBy',
1✔
151
                [$this, 'filterBy'],
1✔
152
                ['deprecated' => true, 'alternative' => 'filter_by']
1✔
153
            ),
1✔
154
            new \Twig\TwigFilter(
1✔
155
                'sortByTitle',
1✔
156
                [$this, 'sortByTitle'],
1✔
157
                ['deprecated' => true, 'alternative' => 'sort_by_title']
1✔
158
            ),
1✔
159
            new \Twig\TwigFilter(
1✔
160
                'sortByWeight',
1✔
161
                [$this, 'sortByWeight'],
1✔
162
                ['deprecated' => true, 'alternative' => 'sort_by_weight']
1✔
163
            ),
1✔
164
            new \Twig\TwigFilter(
1✔
165
                'sortByDate',
1✔
166
                [$this, 'sortByDate'],
1✔
167
                ['deprecated' => true, 'alternative' => 'sort_by_date']
1✔
168
            ),
1✔
169
            new \Twig\TwigFilter(
1✔
170
                'minifyCSS',
1✔
171
                [$this, 'minifyCss'],
1✔
172
                ['deprecated' => true, 'alternative' => 'minifyCss']
1✔
173
            ),
1✔
174
            new \Twig\TwigFilter(
1✔
175
                'minifyJS',
1✔
176
                [$this, 'minifyJs'],
1✔
177
                ['deprecated' => true, 'alternative' => 'minifyJs']
1✔
178
            ),
1✔
179
            new \Twig\TwigFilter(
1✔
180
                'SCSStoCSS',
1✔
181
                [$this, 'scssToCss'],
1✔
182
                ['deprecated' => true, 'alternative' => 'scss_to_css']
1✔
183
            ),
1✔
184
            new \Twig\TwigFilter(
1✔
185
                'excerptHtml',
1✔
186
                [$this, 'excerptHtml'],
1✔
187
                ['deprecated' => true, 'alternative' => 'excerpt_html']
1✔
188
            ),
1✔
189
            new \Twig\TwigFilter(
1✔
190
                'urlize',
1✔
191
                [$this, 'slugifyFilter'],
1✔
192
                ['deprecated' => true, 'alternative' => 'slugify']
1✔
193
            ),
1✔
194
        ];
1✔
195
    }
196

197
    /**
198
     * {@inheritdoc}
199
     */
200
    public function getTests()
201
    {
202
        return [
1✔
203
            new \Twig\TwigTest('asset', [$this, 'isAsset']),
1✔
204
        ];
1✔
205
    }
206

207
    /**
208
     * Filters by Section.
209
     */
210
    public function filterBySection(PagesCollection $pages, string $section): CollectionInterface
211
    {
212
        return $this->filterBy($pages, 'section', $section);
×
213
    }
214

215
    /**
216
     * Filters a pages collection by variable's name/value.
217
     */
218
    public function filterBy(PagesCollection $pages, string $variable, string $value): CollectionInterface
219
    {
220
        $filteredPages = $pages->filter(function (Page $page) use ($variable, $value) {
1✔
221
            // is a dedicated getter exists?
222
            $method = 'get' . ucfirst($variable);
1✔
223
            if (method_exists($page, $method) && $page->$method() == $value) {
1✔
224
                return $page->getType() == Type::PAGE() && !$page->isVirtual() && true;
×
225
            }
226
            // or a classic variable
227
            if ($page->getVariable($variable) == $value) {
1✔
228
                return $page->getType() == Type::PAGE() && !$page->isVirtual() && true;
1✔
229
            }
230
        });
1✔
231

232
        return $filteredPages;
1✔
233
    }
234

235
    /**
236
     * Sorts a collection by title.
237
     */
238
    public function sortByTitle(\Traversable $collection): array
239
    {
240
        $sort = \SORT_ASC;
1✔
241

242
        $collection = iterator_to_array($collection);
1✔
243
        array_multisort(array_keys(/** @scrutinizer ignore-type */ $collection), $sort, \SORT_NATURAL | \SORT_FLAG_CASE, $collection);
1✔
244

245
        return $collection;
1✔
246
    }
247

248
    /**
249
     * Sorts a collection by weight.
250
     */
251
    public function sortByWeight(\Traversable $collection): array
252
    {
253
        $callback = function ($a, $b) {
1✔
254
            if (!isset($a['weight'])) {
1✔
255
                $a['weight'] = 0;
1✔
256
            }
257
            if (!isset($b['weight'])) {
1✔
258
                $a['weight'] = 0;
×
259
            }
260
            if ($a['weight'] == $b['weight']) {
1✔
261
                return 0;
1✔
262
            }
263

264
            return $a['weight'] < $b['weight'] ? -1 : 1;
1✔
265
        };
1✔
266

267
        $collection = iterator_to_array($collection);
1✔
268
        usort(/** @scrutinizer ignore-type */ $collection, $callback);
1✔
269

270
        return $collection;
1✔
271
    }
272

273
    /**
274
     * Sorts by creation date (or 'updated' date): the most recent first.
275
     */
276
    public function sortByDate(\Traversable $collection, string $variable = 'date', bool $descTitle = false): array
277
    {
278
        $callback = function ($a, $b) use ($variable, $descTitle) {
1✔
279
            if ($a[$variable] == $b[$variable]) {
1✔
280
                // if dates are equal and "descTitle" is true
281
                if ($descTitle && (isset($a['title']) && isset($b['title']))) {
1✔
282
                    return strnatcmp($b['title'], $a['title']);
×
283
                }
284

285
                return 0;
1✔
286
            }
287

288
            return $a[$variable] > $b[$variable] ? -1 : 1;
1✔
289
        };
1✔
290

291
        $collection = iterator_to_array($collection);
1✔
292
        usort(/** @scrutinizer ignore-type */ $collection, $callback);
1✔
293

294
        return $collection;
1✔
295
    }
296

297
    /**
298
     * Creates an URL.
299
     *
300
     * $options[
301
     *     'canonical' => false,
302
     *     'format'    => 'html',
303
     *     'language'  => null,
304
     * ];
305
     *
306
     * @param Page|Asset|string|null $value
307
     * @param array|null             $options
308
     */
309
    public function url($value = null, array $options = null): string
310
    {
311
        return (new Url($this->builder, $value, $options))->getUrl();
1✔
312
    }
313

314
    /**
315
     * Creates an Asset (CSS, JS, images, etc.) from a path or an array of paths.
316
     *
317
     * @param string|array $path    File path or array of files path (relative from `assets/` or `static/` dir).
318
     * @param array|null   $options
319
     *
320
     * @return Asset
321
     */
322
    public function asset($path, array $options = null): Asset
323
    {
324
        return new Asset($this->builder, $path, $options);
1✔
325
    }
326

327
    /**
328
     * Compiles a SCSS asset.
329
     *
330
     * @param string|Asset $asset
331
     *
332
     * @return Asset
333
     */
334
    public function toCss($asset): Asset
335
    {
336
        if (!$asset instanceof Asset) {
1✔
337
            $asset = new Asset($this->builder, $asset);
×
338
        }
339

340
        return $asset->compile();
1✔
341
    }
342

343
    /**
344
     * Minifying an asset (CSS or JS).
345
     *
346
     * @param string|Asset $asset
347
     *
348
     * @return Asset
349
     */
350
    public function minify($asset): Asset
351
    {
352
        if (!$asset instanceof Asset) {
1✔
353
            $asset = new Asset($this->builder, $asset);
×
354
        }
355

356
        return $asset->minify();
1✔
357
    }
358

359
    /**
360
     * Fingerprinting an asset.
361
     *
362
     * @param string|Asset $asset
363
     *
364
     * @return Asset
365
     */
366
    public function fingerprint($asset): Asset
367
    {
368
        if (!$asset instanceof Asset) {
1✔
369
            $asset = new Asset($this->builder, $asset);
×
370
        }
371

372
        return $asset->fingerprint();
1✔
373
    }
374

375
    /**
376
     * Resizes an image.
377
     *
378
     * @param string|Asset $asset
379
     *
380
     * @return Asset
381
     */
382
    public function resize($asset, int $size): Asset
383
    {
384
        if (!$asset instanceof Asset) {
1✔
385
            $asset = new Asset($this->builder, $asset);
×
386
        }
387

388
        return $asset->resize($size);
1✔
389
    }
390

391
    /**
392
     * Returns the data URL of an image.
393
     *
394
     * @param string|Asset $asset
395
     *
396
     * @return string
397
     */
398
    public function dataurl($asset): string
399
    {
400
        if (!$asset instanceof Asset) {
1✔
401
            $asset = new Asset($this->builder, $asset);
×
402
        }
403

404
        return $asset->dataurl();
1✔
405
    }
406

407
    /**
408
     * Hashing an asset with algo (sha384 by default).
409
     *
410
     * @param string|Asset $asset
411
     * @param string       $algo
412
     *
413
     * @return string
414
     */
415
    public function integrity($asset, string $algo = 'sha384'): string
416
    {
417
        if (!$asset instanceof Asset) {
1✔
418
            $asset = new Asset($this->builder, $asset);
1✔
419
        }
420

421
        return $asset->getIntegrity($algo);
1✔
422
    }
423

424
    /**
425
     * Minifying a CSS string.
426
     */
427
    public function minifyCss(?string $value): string
428
    {
429
        $value = $value ?? '';
1✔
430

431
        if ($this->builder->isDebug()) {
1✔
432
            return $value;
1✔
433
        }
434

435
        $cache = new Cache($this->builder);
×
436
        $cacheKey = $cache->createKeyFromString($value);
×
437
        if (!$cache->has($cacheKey)) {
×
438
            $minifier = new Minify\CSS($value);
×
439
            $value = $minifier->minify();
×
440
            $cache->set($cacheKey, $value);
×
441
        }
442

443
        return $cache->get($cacheKey, $value);
×
444
    }
445

446
    /**
447
     * Minifying a JavaScript string.
448
     */
449
    public function minifyJs(?string $value): string
450
    {
451
        $value = $value ?? '';
1✔
452

453
        if ($this->builder->isDebug()) {
1✔
454
            return $value;
1✔
455
        }
456

457
        $cache = new Cache($this->builder);
×
458
        $cacheKey = $cache->createKeyFromString($value);
×
459
        if (!$cache->has($cacheKey)) {
×
460
            $minifier = new Minify\JS($value);
×
461
            $value = $minifier->minify();
×
462
            $cache->set($cacheKey, $value);
×
463
        }
464

465
        return $cache->get($cacheKey, $value);
×
466
    }
467

468
    /**
469
     * Compiles a SCSS string.
470
     *
471
     * @throws RuntimeException
472
     */
473
    public function scssToCss(?string $value): string
474
    {
475
        $value = $value ?? '';
×
476

477
        $cache = new Cache($this->builder);
×
478
        $cacheKey = $cache->createKeyFromString($value);
×
479
        if (!$cache->has($cacheKey)) {
×
480
            $scssPhp = new Compiler();
×
481
            $outputStyles = ['expanded', 'compressed'];
×
482
            $outputStyle = strtolower((string) $this->config->get('assets.compile.style'));
×
483
            if (!\in_array($outputStyle, $outputStyles)) {
×
484
                throw new RuntimeException(sprintf('Scss output style "%s" doesn\'t exists.', $outputStyle));
×
485
            }
486
            $scssPhp->setOutputStyle($outputStyle);
×
487
            $variables = $this->config->get('assets.compile.variables') ?? [];
×
488
            if (!empty($variables)) {
×
489
                $variables = array_map('ScssPhp\ScssPhp\ValueConverter::parseValue', $variables);
×
490
                $scssPhp->replaceVariables($variables);
×
491
            }
492
            $value = $scssPhp->compileString($value)->getCss();
×
493
            $cache->set($cacheKey, $value);
×
494
        }
495

496
        return $cache->get($cacheKey, $value);
×
497
    }
498

499
    /**
500
     * Creates the HTML element of an asset.
501
     *
502
     * $options[
503
     *     'preload'    => false,
504
     *     'responsive' => false,
505
     *     'webp'       => false,
506
     * ];
507
     *
508
     * @throws RuntimeException
509
     */
510
    public function html(Asset $asset, array $attributes = [], array $options = []): string
511
    {
512
        $htmlAttributes = '';
1✔
513
        $preload = false;
1✔
514
        $responsive = (bool) $this->config->get('assets.images.responsive.enabled') ?? false;
1✔
515
        $webp = (bool) $this->config->get('assets.images.webp.enabled') ?? false;
1✔
516
        extract($options, EXTR_IF_EXISTS);
1✔
517

518
        // builds HTML attributes
519
        foreach ($attributes as $name => $value) {
1✔
520
            $attribute = sprintf(' %s="%s"', $name, $value);
1✔
521
            if (empty($value)) {
1✔
522
                $attribute = sprintf(' %s', $name);
×
523
            }
524
            $htmlAttributes .= $attribute;
1✔
525
        }
526

527
        // be sure Asset file is saved
528
        $asset->save();
1✔
529

530
        // CSS or JavaScript
531
        switch ($asset['ext']) {
1✔
532
            case 'css':
1✔
533
                if ($preload) {
1✔
534
                    return sprintf(
1✔
535
                        '<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>',
1✔
536
                        $this->url($asset, $options),
1✔
537
                        $htmlAttributes
1✔
538
                    );
1✔
539
                }
540

541
                return sprintf('<link rel="stylesheet" href="%s"%s>', $this->url($asset, $options), $htmlAttributes);
1✔
542
            case 'js':
1✔
543
                return sprintf('<script src="%s"%s></script>', $this->url($asset, $options), $htmlAttributes);
1✔
544
        }
545
        // image
546
        if ($asset['type'] == 'image') {
1✔
547
            // responsive
548
            $sizes = '';
1✔
549
            if (
550
                $responsive && $srcset = Image::buildSrcset(
1✔
551
                    $asset,
1✔
552
                    $this->config->getAssetsImagesWidths()
1✔
553
                )
1✔
554
            ) {
555
                $htmlAttributes .= sprintf(' srcset="%s"', $srcset);
1✔
556
                $sizes = Image::getSizes($attributes['class'] ?? '', $this->config->getAssetsImagesSizes());
1✔
557
                $htmlAttributes .= sprintf(' sizes="%s"', $sizes);
1✔
558
            }
559

560
            // <img> element
561
            $img = sprintf(
1✔
562
                '<img src="%s" width="' . ($asset['width'] ?: '') . '" height="' . ($asset['height'] ?: '') . '"%s>',
1✔
563
                $this->url($asset, $options),
1✔
564
                $htmlAttributes
1✔
565
            );
1✔
566

567
            // WebP conversion?
568
            if ($webp && $asset['subtype'] != 'image/webp' && !Image::isAnimatedGif($asset)) {
1✔
569
                try {
570
                    $assetWebp = $asset->webp();
1✔
571
                    // <source> element
572
                    $source = sprintf('<source type="image/webp" srcset="%s">', $assetWebp);
1✔
573
                    // responsive
574
                    if ($responsive) {
1✔
575
                        $srcset = Image::buildSrcset(
1✔
576
                            $assetWebp,
1✔
577
                            $this->config->getAssetsImagesWidths()
1✔
578
                        ) ?: (string) $assetWebp;
1✔
579
                        // <source> element
580
                        $source = sprintf(
1✔
581
                            '<source type="image/webp" srcset="%s" sizes="%s">',
1✔
582
                            $srcset,
1✔
583
                            $sizes
1✔
584
                        );
1✔
585
                    }
586

587
                    return sprintf("<picture>\n  %s\n  %s\n</picture>", $source, $img);
1✔
588
                } catch (\Exception $e) {
×
589
                    $this->builder->getLogger()->debug($e->getMessage());
×
590
                }
591
            }
592

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
     * Builds the HTML img `srcset` (responsive) attribute of an image Asset.
601
     *
602
     * @throws RuntimeException
603
     */
604
    public function imageSrcset(Asset $asset): string
605
    {
606
        return Image::buildSrcset($asset, $this->config->getAssetsImagesWidths());
1✔
607
    }
608

609
    /**
610
     * Returns the HTML img `sizes` attribute based on a CSS class name.
611
     */
612
    public function imageSizes(string $class): string
613
    {
614
        return Image::getSizes($class, $this->config->getAssetsImagesWidths());
1✔
615
    }
616

617
    /**
618
     * Converts an image Asset to WebP format.
619
     *
620
     * @throws RuntimeException
621
     */
622
    public function webp(Asset $asset, ?int $quality = null): Asset
623
    {
624
        if ($asset['subtype'] == 'image/webp') {
×
625
            return $asset;
×
626
        }
627
        if (Image::isAnimatedGif($asset)) {
×
628
            throw new RuntimeException(sprintf('Can\'t convert the animated GIF "%s" to WebP.', $asset['path']));
×
629
        }
630
        try {
631
            return $asset->webp($quality);
×
632
        } catch (\Exception $e) {
×
633
            throw new RuntimeException(sprintf('Can\'t convert "%s" to WebP (%s).', $asset['path'], $e->getMessage()));
×
634
        }
635
    }
636

637
    /**
638
     * Returns the content of an asset.
639
     */
640
    public function inline(Asset $asset): string
641
    {
642
        return $asset['content'];
1✔
643
    }
644

645
    /**
646
     * Reads $length first characters of a string and adds a suffix.
647
     */
648
    public function excerpt(?string $string, int $length = 450, string $suffix = ' …'): string
649
    {
650
        $string = $string ?? '';
×
651

652
        $string = str_replace('</p>', '<br /><br />', $string);
×
653
        $string = trim(strip_tags($string, '<br>'), '<br />');
×
654
        if (mb_strlen($string) > $length) {
×
655
            $string = mb_substr($string, 0, $length);
×
656
            $string .= $suffix;
×
657
        }
658

659
        return $string;
×
660
    }
661

662
    /**
663
     * Reads characters before or after '<!-- separator -->'.
664
     * Options:
665
     *  - separator: string to use as separator (`excerpt|break` by default)
666
     *  - capture: part to capture, `before` or `after` the separator (`before` by default).
667
     */
668
    public function excerptHtml(?string $string, array $options = []): string
669
    {
670
        $string = $string ?? '';
1✔
671

672
        $separator = (string) $this->config->get('body.excerpt.separator');
1✔
673
        $capture = (string) $this->config->get('body.excerpt.capture');
1✔
674
        extract($options, EXTR_IF_EXISTS);
1✔
675

676
        // https://regex101.com/r/n9TWHF/1
677
        $pattern = '(.*)<!--[[:blank:]]?(' . $separator . ')[[:blank:]]?-->(.*)';
1✔
678
        preg_match('/' . $pattern . '/is', $string, $matches);
1✔
679

680
        if (empty($matches)) {
1✔
681
            return $string;
1✔
682
        }
683
        $result = trim($matches[1]);
1✔
684
        if ($capture == 'after') {
1✔
685
            $result = trim($matches[3]);
1✔
686
        }
687
        // removes footnotes and returns result
688
        return preg_replace('/<sup[^>]*>[^u]*<\/sup>/', '', $result);
1✔
689
    }
690

691
    /**
692
     * Converts a Markdown string to HTML.
693
     *
694
     * @throws RuntimeException
695
     */
696
    public function markdownToHtml(?string $markdown): ?string
697
    {
698
        $markdown = $markdown ?? '';
1✔
699

700
        try {
701
            $parsedown = new Parsedown($this->builder);
1✔
702
            $html = $parsedown->text($markdown);
1✔
703
        } catch (\Exception $e) {
×
704
            throw new RuntimeException('"markdown_to_html" filter can not convert supplied Markdown.');
×
705
        }
706

707
        return $html;
1✔
708
    }
709

710
    /**
711
     * Extract table of content of a Markdown string,
712
     * in the given format ("html" or "json", "html" by default).
713
     *
714
     * @throws RuntimeException
715
     */
716
    public function markdownToToc(?string $markdown, $format = 'html', $url = ''): ?string
717
    {
718
        $markdown = $markdown ?? '';
×
719

720
        try {
721
            $parsedown = new Parsedown($this->builder, ['selectors' => ['h2'], 'url' => $url]);
×
722
            $parsedown->body($markdown);
×
723
            $return = $parsedown->contentsList($format);
×
724
        } catch (\Exception $e) {
×
725
            throw new RuntimeException('"toc" filter can not convert supplied Markdown.');
×
726
        }
727

728
        return $return;
×
729
    }
730

731
    /**
732
     * Converts a JSON string to an array.
733
     *
734
     * @throws RuntimeException
735
     */
736
    public function jsonDecode(?string $json): ?array
737
    {
738
        $json = $json ?? '';
1✔
739

740
        try {
741
            $array = json_decode($json, true);
1✔
742
            if ($array === null && json_last_error() !== JSON_ERROR_NONE) {
1✔
743
                throw new \Exception('JSON error.');
1✔
744
            }
745
        } catch (\Exception $e) {
×
746
            throw new RuntimeException('"json_decode" filter can not parse supplied JSON.');
×
747
        }
748

749
        return $array;
1✔
750
    }
751

752
    /**
753
     * Converts a YAML string to an array.
754
     *
755
     * @throws RuntimeException
756
     */
757
    public function yamlParse(?string $yaml): ?array
758
    {
759
        $yaml = $yaml ?? '';
1✔
760

761
        try {
762
            $array = Yaml::parse($yaml);
1✔
763
            if (!\is_array($array)) {
1✔
764
                throw new ParseException('YAML error.');
1✔
765
            }
766
        } catch (ParseException $e) {
×
767
            throw new RuntimeException(sprintf('"yaml_parse" filter can not parse supplied YAML: %s', $e->getMessage()));
×
768
        }
769

770
        return $array;
1✔
771
    }
772

773
    /**
774
     * Split a string into an array using a regular expression.
775
     *
776
     * @throws RuntimeException
777
     */
778
    public function pregSplit(?string $value, string $pattern, int $limit = 0): ?array
779
    {
780
        $value = $value ?? '';
×
781

782
        try {
783
            $array = preg_split($pattern, $value, $limit);
×
784
            if ($array === false) {
×
785
                throw new RuntimeException('PREG split error.');
×
786
            }
787
        } catch (\Exception $e) {
×
788
            throw new RuntimeException('"preg_split" filter can not split supplied string.');
×
789
        }
790

791
        return $array;
×
792
    }
793

794
    /**
795
     * Perform a regular expression match and return the group for all matches.
796
     *
797
     * @throws RuntimeException
798
     */
799
    public function pregMatchAll(?string $value, string $pattern, int $group = 0): ?array
800
    {
801
        $value = $value ?? '';
×
802

803
        try {
804
            $array = preg_match_all($pattern, $value, $matches, PREG_PATTERN_ORDER);
×
805
            if ($array === false) {
×
806
                throw new RuntimeException('PREG match all error.');
×
807
            }
808
        } catch (\Exception $e) {
×
809
            throw new RuntimeException('"preg_match_all" filter can not match in supplied string.');
×
810
        }
811

812
        return $matches[$group];
×
813
    }
814

815
    /**
816
     * Calculates estimated time to read a text.
817
     */
818
    public function readtime(?string $text): string
819
    {
820
        $text = $text ?? '';
×
821

822
        $words = str_word_count(strip_tags($text));
×
823
        $min = floor($words / 200);
×
824
        if ($min === 0) {
×
825
            return '1';
×
826
        }
827

828
        return (string) $min;
×
829
    }
830

831
    /**
832
     * Gets the value of an environment variable.
833
     */
834
    public function getEnv(?string $var): ?string
835
    {
836
        $var = $var ?? '';
1✔
837

838
        return getenv($var) ?: null;
1✔
839
    }
840

841
    /**
842
     * Tests if a variable is an Asset.
843
     */
844
    public function isAsset($variable): bool
845
    {
846
        return $variable instanceof Asset;
×
847
    }
848

849
    /**
850
     * Returns the dominant hex color of an image asset.
851
     *
852
     * @param string|Asset $asset
853
     *
854
     * @return string
855
     */
856
    public function dominantColor($asset): string
857
    {
858
        if (!$asset instanceof Asset) {
1✔
859
            $asset = new Asset($this->builder, $asset);
×
860
        }
861

862
        return Image::getDominantColor($asset);
1✔
863
    }
864

865
    /**
866
     * Returns a Low Quality Image Placeholder (LQIP) as data URL.
867
     *
868
     * @param string|Asset $asset
869
     *
870
     * @return string
871
     */
872
    public function lqip($asset): string
873
    {
874
        if (!$asset instanceof Asset) {
1✔
875
            $asset = new Asset($this->builder, $asset);
×
876
        }
877

878
        return Image::getLqip($asset);
1✔
879
    }
880

881
    /**
882
     * Converts an hexadecimal color to RGB.
883
     *
884
     * @throws RuntimeException
885
     */
886
    public function hexToRgb(?string $variable): array
887
    {
888
        $variable = $variable ?? '';
×
889

890
        if (!self::isHex($variable)) {
×
891
            throw new RuntimeException(sprintf('"%s" is not a valid hexadecimal value.', $variable));
×
892
        }
893
        $hex = ltrim($variable, '#');
×
894
        if (\strlen($hex) == 3) {
×
895
            $hex = $hex[0] . $hex[0] . $hex[1] . $hex[1] . $hex[2] . $hex[2];
×
896
        }
897
        $c = hexdec($hex);
×
898

899
        return [
×
900
            'red'   => $c >> 16 & 0xFF,
×
901
            'green' => $c >> 8 & 0xFF,
×
902
            'blue'  => $c & 0xFF,
×
903
        ];
×
904
    }
905

906
    /**
907
     * Split a string in multiple lines.
908
     */
909
    public function splitLine(?string $variable, int $max = 18): array
910
    {
911
        $variable = $variable ?? '';
×
912

913
        return preg_split("/.{0,{$max}}\K(\s+|$)/", $variable, 0, PREG_SPLIT_NO_EMPTY);
×
914
    }
915

916
    /**
917
     * Is a hexadecimal color is valid?
918
     */
919
    private static function isHex(string $hex): bool
920
    {
921
        $valid = \is_string($hex);
×
922
        $hex = ltrim($hex, '#');
×
923
        $length = \strlen($hex);
×
924
        $valid = $valid && ($length === 3 || $length === 6);
×
925
        $valid = $valid && ctype_xdigit($hex);
×
926

927
        return $valid;
×
928
    }
929
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc