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

Cecilapp / Cecil / 4629558506

pending completion
4629558506

Pull #1664

github

GitHub
Merge b3bc073f6 into 6c3583161
Pull Request #1664: feat: image LQIP filter

9 of 9 new or added lines in 2 files covered. (100.0%)

2787 of 4117 relevant lines covered (67.69%)

0.68 hits per line

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

67.42
/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 = $this->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
            // content
80
            new \Twig\TwigFunction('readtime', [$this, 'readtime']),
1✔
81
            // others
82
            new \Twig\TwigFunction('getenv', [$this, 'getEnv']),
1✔
83
            // deprecated
84
            new \Twig\TwigFunction(
1✔
85
                'hash',
1✔
86
                [$this, 'integrity'],
1✔
87
                ['deprecated' => true, 'alternative' => 'integrity']
1✔
88
            ),
1✔
89
            new \Twig\TwigFunction(
1✔
90
                'minify',
1✔
91
                [$this, 'minify'],
1✔
92
                ['deprecated' => true, 'alternative' => 'minify filter']
1✔
93
            ),
1✔
94
            new \Twig\TwigFunction(
1✔
95
                'toCSS',
1✔
96
                [$this, 'toCss'],
1✔
97
                ['deprecated' => true, 'alternative' => 'to_css filter']
1✔
98
            ),
1✔
99
        ];
1✔
100
    }
101

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

194
    /**
195
     * {@inheritdoc}
196
     */
197
    public function getTests()
198
    {
199
        return [
1✔
200
            new \Twig\TwigTest('asset', [$this, 'isAsset']),
1✔
201
        ];
1✔
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
     */
215
    public function filterBy(PagesCollection $pages, string $variable, string $value): CollectionInterface
216
    {
217
        $filteredPages = $pages->filter(function (Page $page) use ($variable, $value) {
1✔
218
            // is a dedicated getter exists?
219
            $method = 'get' . ucfirst($variable);
1✔
220
            if (method_exists($page, $method) && $page->$method() == $value) {
1✔
221
                return $page->getType() == Type::PAGE() && !$page->isVirtual() && true;
×
222
            }
223
            // or a classic variable
224
            if ($page->getVariable($variable) == $value) {
1✔
225
                return $page->getType() == Type::PAGE() && !$page->isVirtual() && true;
1✔
226
            }
227
        });
1✔
228

229
        return $filteredPages;
1✔
230
    }
231

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

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

242
        return $collection;
1✔
243
    }
244

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

261
            return $a['weight'] < $b['weight'] ? -1 : 1;
1✔
262
        };
1✔
263

264
        $collection = iterator_to_array($collection);
1✔
265
        usort(/** @scrutinizer ignore-type */ $collection, $callback);
1✔
266

267
        return $collection;
1✔
268
    }
269

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

282
                return 0;
1✔
283
            }
284

285
            return $a[$variable] > $b[$variable] ? -1 : 1;
1✔
286
        };
1✔
287

288
        $collection = iterator_to_array($collection);
1✔
289
        usort(/** @scrutinizer ignore-type */ $collection, $callback);
1✔
290

291
        return $collection;
1✔
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
     */
306
    public function url($value = null, array $options = null): string
307
    {
308
        return (new Url($this->builder, $value, $options))->getUrl();
1✔
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
     */
319
    public function asset($path, array $options = null): Asset
320
    {
321
        return new Asset($this->builder, $path, $options);
1✔
322
    }
323

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

337
        return $asset->compile();
1✔
338
    }
339

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

353
        return $asset->minify();
1✔
354
    }
355

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

369
        return $asset->fingerprint();
1✔
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
     */
395
    public function dataurl($asset): string
396
    {
397
        if (!$asset instanceof Asset) {
1✔
398
            $asset = new Asset($this->builder, $asset);
×
399
        }
400

401
        return $asset->dataurl();
1✔
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
     */
412
    public function integrity($asset, string $algo = 'sha384'): string
413
    {
414
        if (!$asset instanceof Asset) {
1✔
415
            $asset = new Asset($this->builder, $asset);
1✔
416
        }
417

418
        return $asset->getIntegrity($algo);
1✔
419
    }
420

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

428
        if ($this->builder->isDebug()) {
1✔
429
            return $value;
1✔
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
     */
446
    public function minifyJs(?string $value): string
447
    {
448
        $value = $value ?? '';
1✔
449

450
        if ($this->builder->isDebug()) {
1✔
451
            return $value;
1✔
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
     */
507
    public function html(Asset $asset, array $attributes = [], array $options = []): string
508
    {
509
        $htmlAttributes = '';
1✔
510
        $preload = false;
1✔
511
        $responsive = (bool) $this->config->get('assets.images.responsive.enabled') ?? false;
1✔
512
        $webp = (bool) $this->config->get('assets.images.webp.enabled') ?? false;
1✔
513
        extract($options, EXTR_IF_EXISTS);
1✔
514

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

524
        // be sure Asset file is saved
525
        $asset->save();
1✔
526

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

538
                return \sprintf('<link rel="stylesheet" href="%s"%s>', $this->url($asset, $options), $htmlAttributes);
1✔
539
            case 'js':
1✔
540
                return \sprintf('<script src="%s"%s></script>', $this->url($asset, $options), $htmlAttributes);
×
541
        }
542
        // image
543
        if ($asset['type'] == 'image') {
1✔
544
            // responsive
545
            $sizes = '';
1✔
546
            if (
547
                $responsive && $srcset = Image::buildSrcset(
1✔
548
                    $asset,
1✔
549
                    $this->config->getAssetsImagesWidths()
1✔
550
                )
1✔
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
            // <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
     * Returns the content of an asset.
601
     */
602
    public function inline(Asset $asset): string
603
    {
604
        return $asset['content'];
1✔
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
     */
630
    public function excerptHtml(?string $string, array $options = []): string
631
    {
632
        $string = $string ?? '';
1✔
633

634
        $separator = (string) $this->builder->getConfig()->get('body.excerpt.separator');
1✔
635
        $capture = (string) $this->builder->getConfig()->get('body.excerpt.capture');
1✔
636
        extract($options, EXTR_IF_EXISTS);
1✔
637

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

642
        if (empty($matches)) {
1✔
643
            return $string;
1✔
644
        }
645
        $result = trim($matches[1]);
1✔
646
        if ($capture == 'after') {
1✔
647
            $result = trim($matches[3]);
1✔
648
        }
649
        // removes footnotes and returns result
650
        return preg_replace('/<sup[^>]*>[^u]*<\/sup>/', '', $result);
1✔
651
    }
652

653
    /**
654
     * Converts a Markdown string to HTML.
655
     *
656
     * @throws RuntimeException
657
     */
658
    public function markdownToHtml(?string $markdown): ?string
659
    {
660
        $markdown = $markdown ?? '';
1✔
661

662
        try {
663
            $parsedown = new Parsedown($this->builder);
1✔
664
            $html = $parsedown->text($markdown);
1✔
665
        } catch (\Exception $e) {
×
666
            throw new RuntimeException('"markdown_to_html" filter can not convert supplied Markdown.');
×
667
        }
668

669
        return $html;
1✔
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
     */
698
    public function jsonDecode(?string $json): ?array
699
    {
700
        $json = $json ?? '';
1✔
701

702
        try {
703
            $array = json_decode($json, true);
1✔
704
            if ($array === null && json_last_error() !== JSON_ERROR_NONE) {
1✔
705
                throw new \Exception('JSON error.');
1✔
706
            }
707
        } catch (\Exception $e) {
×
708
            throw new RuntimeException('"json_decode" filter can not parse supplied JSON.');
×
709
        }
710

711
        return $array;
1✔
712
    }
713

714
    /**
715
     * Converts a YAML string to an array.
716
     *
717
     * @throws RuntimeException
718
     */
719
    public function yamlParse(?string $yaml): ?array
720
    {
721
        $yaml = $yaml ?? '';
1✔
722

723
        try {
724
            $array = Yaml::parse($yaml);
1✔
725
            if (!is_array($array)) {
1✔
726
                throw new ParseException('YAML error.');
1✔
727
            }
728
        } catch (ParseException $e) {
×
729
            throw new RuntimeException(\sprintf('"yaml_parse" filter can not parse supplied YAML: %s', $e->getMessage()));
×
730
        }
731

732
        return $array;
1✔
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
     */
796
    public function getEnv(?string $var): ?string
797
    {
798
        $var = $var ?? '';
1✔
799

800
        return getenv($var) ?: null;
1✔
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
     */
818
    public function dominantColor($asset): string
819
    {
820
        if (!$asset instanceof Asset) {
1✔
821
            $asset = new Asset($this->builder, $asset);
×
822
        }
823

824
        return Image::getDominantColor($asset);
1✔
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) {
1✔
837
            $asset = new Asset($this->builder, $asset);
×
838
        }
839

840
        return Image::getLqip($asset);
1✔
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
}
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