Passed
Push — json-decode ( fe98e1...44270f )
by Arnaud
22:20 queued 19:17
created

Extension   F

Complexity

Total Complexity 60

Size/Duplication

Total Lines 582
Duplicated Lines 0 %

Importance

Changes 12
Bugs 0 Features 0
Metric Value
eloc 211
c 12
b 0
f 0
dl 0
loc 582
rs 3.6
wmc 60

26 Methods

Rating   Name   Duplication   Size   Complexity  
A inline() 0 7 2
A excerpt() 0 10 2
A getName() 0 3 1
A __construct() 0 10 2
A minify() 0 7 2
A toCss() 0 7 2
A sortByDate() 0 14 3
A resize() 0 5 1
B filterBy() 0 18 7
A minifyJs() 0 11 2
A markdownToHtml() 0 10 2
A getFunctions() 0 26 1
A asset() 0 3 1
A scssToCss() 0 18 3
A integrity() 0 7 2
A sortByWeight() 0 20 5
A minifyCss() 0 11 2
A url() 0 3 1
A filterBySection() 0 3 1
A html() 0 27 6
B getFilters() 0 75 1
A sortByTitle() 0 6 1
A getEnv() 0 3 2
A readtime() 0 9 2
A jsonDecode() 0 12 4
A excerptHtml() 0 10 2

How to fix   Complexity   

Complex Class

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

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

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

1
<?php
2
/**
3
 * This file is part of the Cecil/Cecil package.
4
 *
5
 * Copyright (c) Arnaud Ligny <[email protected]>
6
 *
7
 * For the full copyright and license information, please view the LICENSE
8
 * file that was distributed with this source code.
9
 */
10
11
namespace Cecil\Renderer\Twig;
12
13
use Cecil\Assets\Asset;
14
use Cecil\Assets\Cache;
15
use Cecil\Assets\Image;
16
use Cecil\Assets\Url;
17
use Cecil\Builder;
18
use Cecil\Collection\CollectionInterface;
19
use Cecil\Collection\Page\Collection as PagesCollection;
20
use Cecil\Collection\Page\Page;
21
use Cecil\Config;
22
use Cecil\Converter\Parsedown;
23
use Cecil\Exception\Exception;
24
use Cocur\Slugify\Bridge\Twig\SlugifyExtension;
25
use Cocur\Slugify\Slugify;
26
use MatthiasMullie\Minify;
27
use ScssPhp\ScssPhp\Compiler;
28
29
/**
30
 * Class Twig\Extension.
31
 */
32
class Extension extends SlugifyExtension
33
{
34
    /** @var Builder */
35
    protected $builder;
36
    /** @var Config */
37
    protected $config;
38
    /** @var Slugify */
39
    private static $slugifier;
40
41
    /**
42
     * @param Builder $builder
43
     */
44
    public function __construct(Builder $builder)
45
    {
46
        if (!self::$slugifier instanceof Slugify) {
47
            self::$slugifier = Slugify::create(['regexp' => Page::SLUGIFY_PATTERN]);
48
        }
49
50
        parent::__construct(self::$slugifier);
51
52
        $this->builder = $builder;
53
        $this->config = $this->builder->getConfig();
54
    }
55
56
    /**
57
     * {@inheritdoc}
58
     */
59
    public function getName()
60
    {
61
        return 'cecil';
62
    }
63
64
    /**
65
     * {@inheritdoc}
66
     */
67
    public function getFilters()
68
    {
69
        return [
70
            new \Twig\TwigFilter('filter_by', [$this, 'filterBy']),
71
            // sort
72
            new \Twig\TwigFilter('sort_by_title', [$this, 'sortByTitle']),
73
            new \Twig\TwigFilter('sort_by_weight', [$this, 'sortByWeight']),
74
            new \Twig\TwigFilter('sort_by_date', [$this, 'sortByDate']),
75
            // assets
76
            new \Twig\TwigFilter('url', [$this, 'url']),
77
            new \Twig\TwigFilter('html', [$this, 'html']),
78
            new \Twig\TwigFilter('inline', [$this, 'inline']),
79
            new \Twig\TwigFilter('markdown_to_html', [$this, 'markdownToHtml']),
80
            new \Twig\TwigFilter('json_decode', [$this, 'jsonDecode']),
81
            new \Twig\TwigFilter('to_css', [$this, 'toCss']),
82
            new \Twig\TwigFilter('minify', [$this, 'minify']),
83
            new \Twig\TwigFilter('minify_css', [$this, 'minifyCss']),
84
            new \Twig\TwigFilter('minify_js', [$this, 'minifyJs']),
85
            new \Twig\TwigFilter('scss_to_css', [$this, 'scssToCss']),
86
            new \Twig\TwigFilter('sass_to_css', [$this, 'scssToCss']),
87
            new \Twig\TwigFilter('resize', [$this, 'resize']),
88
            // content
89
            new \Twig\TwigFilter('slugify', [$this, 'slugifyFilter']),
90
            new \Twig\TwigFilter('excerpt', [$this, 'excerpt']),
91
            new \Twig\TwigFilter('excerpt_html', [$this, 'excerptHtml']),
92
            // deprecated
93
            new \Twig\TwigFilter(
94
                'filterBySection',
95
                [$this, 'filterBySection'],
96
                ['deprecated' => true, 'alternative' => 'filter_by']
97
            ),
98
            new \Twig\TwigFilter(
99
                'filterBy',
100
                [$this, 'filterBy'],
101
                ['deprecated' => true, 'alternative' => 'filter_by']
102
            ),
103
            new \Twig\TwigFilter(
104
                'sortByTitle',
105
                [$this, 'sortByTitle'],
106
                ['deprecated' => true, 'alternative' => 'sort_by_title']
107
            ),
108
            new \Twig\TwigFilter(
109
                'sortByWeight',
110
                [$this, 'sortByWeight'],
111
                ['deprecated' => true, 'alternative' => 'sort_by_weight']
112
            ),
113
            new \Twig\TwigFilter(
114
                'sortByDate',
115
                [$this, 'sortByDate'],
116
                ['deprecated' => true, 'alternative' => 'sort_by_date']
117
            ),
118
            new \Twig\TwigFilter(
119
                'minifyCSS',
120
                [$this, 'minifyCss'],
121
                ['deprecated' => true, 'alternative' => 'minifyCss']
122
            ),
123
            new \Twig\TwigFilter(
124
                'minifyJS',
125
                [$this, 'minifyJs'],
126
                ['deprecated' => true, 'alternative' => 'minifyJs']
127
            ),
128
            new \Twig\TwigFilter(
129
                'SCSStoCSS',
130
                [$this, 'scssToCss'],
131
                ['deprecated' => true, 'alternative' => 'scss_to_css']
132
            ),
133
            new \Twig\TwigFilter(
134
                'excerptHtml',
135
                [$this, 'excerptHtml'],
136
                ['deprecated' => true, 'alternative' => 'excerpt_html']
137
            ),
138
            new \Twig\TwigFilter(
139
                'urlize',
140
                [$this, 'slugifyFilter'],
141
                ['deprecated' => true, 'alternative' => 'slugify']
142
            ),
143
        ];
144
    }
145
146
    /**
147
     * {@inheritdoc}
148
     */
149
    public function getFunctions()
150
    {
151
        return [
152
            // assets
153
            new \Twig\TwigFunction('url', [$this, 'url']),
154
            new \Twig\TwigFunction('asset', [$this, 'asset']),
155
            new \Twig\TwigFunction('integrity', [$this, 'integrity']),
156
            // content
157
            new \Twig\TwigFunction('readtime', [$this, 'readtime']),
158
            // others
159
            new \Twig\TwigFunction('getenv', [$this, 'getEnv']),
160
            // deprecated
161
            new \Twig\TwigFunction(
162
                'minify',
163
                [$this, 'minify'],
164
                ['deprecated' => true, 'alternative' => 'minify filter']
165
            ),
166
            new \Twig\TwigFunction(
167
                'toCSS',
168
                [$this, 'toCss'],
169
                ['deprecated' => true, 'alternative' => 'to_css filter']
170
            ),
171
            new \Twig\TwigFunction(
172
                'hash',
173
                [$this, 'integrity'],
174
                ['deprecated' => true, 'alternative' => 'integrity']
175
            ),
176
        ];
177
    }
178
179
    /**
180
     * Filters by Section.
181
     * Alias of `filterBy('section', $value)`.
182
     *
183
     * @param PagesCollection $pages
184
     * @param string          $section
185
     *
186
     * @return CollectionInterface
187
     */
188
    public function filterBySection(PagesCollection $pages, string $section): CollectionInterface
189
    {
190
        return $this->filterBy($pages, 'section', $section);
191
    }
192
193
    /**
194
     * Filters by variable's name/value.
195
     *
196
     * @param PagesCollection $pages
197
     * @param string          $variable
198
     * @param string          $value
199
     *
200
     * @return CollectionInterface
201
     */
202
    public function filterBy(PagesCollection $pages, string $variable, string $value): CollectionInterface
203
    {
204
        $filteredPages = $pages->filter(function (Page $page) use ($variable, $value) {
205
            $notVirtual = false;
206
            if (!$page->isVirtual()) {
207
                $notVirtual = true;
208
            }
209
            // is a dedicated getter exists?
210
            $method = 'get'.ucfirst($variable);
211
            if (method_exists($page, $method) && $page->$method() == $value) {
212
                return $notVirtual && true;
213
            }
214
            if ($page->getVariable($variable) == $value) {
215
                return $notVirtual && true;
216
            }
217
        });
218
219
        return $filteredPages;
220
    }
221
222
    /**
223
     * Sorts by title.
224
     *
225
     * @param \Traversable $collection
226
     *
227
     * @return array
228
     */
229
    public function sortByTitle(\Traversable $collection): array
230
    {
231
        $collection = iterator_to_array($collection);
232
        array_multisort(array_keys($collection), SORT_NATURAL | SORT_FLAG_CASE, $collection);
1 ignored issue
show
Bug introduced by
array_keys($collection) cannot be passed to array_multisort() as the parameter $arr 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

232
        array_multisort(/** @scrutinizer ignore-type */ array_keys($collection), SORT_NATURAL | SORT_FLAG_CASE, $collection);
Loading history...
233
234
        return $collection;
235
    }
236
237
    /**
238
     * Sorts by weight.
239
     *
240
     * @param \Traversable $collection
241
     *
242
     * @return array
243
     */
244
    public function sortByWeight(\Traversable $collection): array
245
    {
246
        $callback = function ($a, $b) {
247
            if (!isset($a['weight'])) {
248
                $a['weight'] = 0;
249
            }
250
            if (!isset($b['weight'])) {
251
                $a['weight'] = 0;
252
            }
253
            if ($a['weight'] == $b['weight']) {
254
                return 0;
255
            }
256
257
            return ($a['weight'] < $b['weight']) ? -1 : 1;
258
        };
259
260
        $collection = iterator_to_array($collection);
261
        usort($collection, $callback);
262
263
        return $collection;
264
    }
265
266
    /**
267
     * Sorts by date: the most recent first.
268
     *
269
     * @param \Traversable $collection
270
     *
271
     * @return array
272
     */
273
    public function sortByDate(\Traversable $collection): array
274
    {
275
        $callback = function ($a, $b) {
276
            if ($a['date'] == $b['date']) {
277
                return 0;
278
            }
279
280
            return ($a['date'] > $b['date']) ? -1 : 1;
281
        };
282
283
        $collection = iterator_to_array($collection);
284
        usort($collection, $callback);
285
286
        return $collection;
287
    }
288
289
    /**
290
     * Creates an URL.
291
     *
292
     * $options[
293
     *     'canonical' => true,
294
     *     'addhash'   => false,
295
     *     'format'    => 'json',
296
     * ];
297
     *
298
     * @param Page|Asset|string|null $value
299
     * @param array|null             $options
300
     *
301
     * @return mixed
302
     */
303
    public function url($value = null, array $options = null)
304
    {
305
        return new Url($this->builder, $value, $options);
306
    }
307
308
    /**
309
     * Creates an asset (CSS, JS, images, etc.).
310
     *
311
     * @param string|array $path    File path (relative from static/ dir).
312
     * @param array|null   $options
313
     *
314
     * @return Asset
315
     */
316
    public function asset($path, array $options = null): Asset
317
    {
318
        return new Asset($this->builder, $path, $options);
319
    }
320
321
    /**
322
     * Minifying an asset (CSS or JS).
323
     * ie: minify('css/style.css').
324
     *
325
     * @param string|Asset $asset
326
     *
327
     * @return Asset
328
     */
329
    public function minify($asset): Asset
330
    {
331
        if (!$asset instanceof Asset) {
332
            $asset = new Asset($this->builder, $asset);
333
        }
334
335
        return $asset->minify();
336
    }
337
338
    /**
339
     * Compiles a SCSS asset.
340
     *
341
     * @param string|Asset $asset
342
     *
343
     * @return Asset
344
     */
345
    public function toCss($asset): Asset
346
    {
347
        if (!$asset instanceof Asset) {
348
            $asset = new Asset($this->builder, $asset);
349
        }
350
351
        return $asset->compile();
352
    }
353
354
    /**
355
     * Resizes an image.
356
     *
357
     * @param string $path Image path (relative from static/ dir or external).
358
     * @param int    $size Image new size (width).
359
     *
360
     * @return string
361
     */
362
    public function resize(string $path, int $size): string
363
    {
364
        return (new Image($this->builder))
365
            ->load($path)
366
            ->resize($size);
367
    }
368
369
    /**
370
     * Hashing an asset with algo (sha384 by default).
371
     *
372
     * @param string|Asset $path
373
     * @param string       $algo
374
     *
375
     * @return string
376
     */
377
    public function integrity($asset, string $algo = 'sha384'): string
378
    {
379
        if (!$asset instanceof Asset) {
380
            $asset = new Asset($this->builder, $asset);
381
        }
382
383
        return $asset->getIntegrity($algo);
384
    }
385
386
    /**
387
     * Minifying a CSS string.
388
     *
389
     * @param string $value
390
     *
391
     * @return string
392
     */
393
    public function minifyCss(string $value): string
394
    {
395
        $cache = new Cache($this->builder, 'assets');
396
        $cacheKey = $cache->createKeyFromValue($value);
397
        if (!$cache->has($cacheKey)) {
398
            $minifier = new Minify\CSS($value);
399
            $value = $minifier->minify();
400
            $cache->set($cacheKey, $value);
401
        }
402
403
        return $cache->get($cacheKey, $value);
404
    }
405
406
    /**
407
     * Minifying a JavaScript string.
408
     *
409
     * @param string $value
410
     *
411
     * @return string
412
     */
413
    public function minifyJs(string $value): string
414
    {
415
        $cache = new Cache($this->builder, 'assets');
416
        $cacheKey = $cache->createKeyFromValue($value);
417
        if (!$cache->has($cacheKey)) {
418
            $minifier = new Minify\JS($value);
419
            $value = $minifier->minify();
420
            $cache->set($cacheKey, $value);
421
        }
422
423
        return $cache->get($cacheKey, $value);
424
    }
425
426
    /**
427
     * Compiles a SCSS string.
428
     *
429
     * @param string $value
430
     *
431
     * @return string
432
     */
433
    public function scssToCss(string $value): string
434
    {
435
        $cache = new Cache($this->builder, 'assets');
436
        $cacheKey = $cache->createKeyFromValue($value);
437
        if (!$cache->has($cacheKey)) {
438
            $scssPhp = new Compiler();
439
            $outputStyles = ['expanded', 'compressed'];
440
            $outputStyle = strtolower((string) $this->config->get('assets.compile.style'));
441
            if (!in_array($outputStyle, $outputStyles)) {
442
                throw new Exception(\sprintf('Scss output style "%s" doesn\'t exists.', $outputStyle));
443
            }
444
            $scssPhp->setOutputStyle($outputStyle);
445
            $scssPhp->setVariables($this->config->get('assets.compile.variables') ?? []);
446
            $value = $scssPhp->compile($value);
447
            $cache->set($cacheKey, $value);
448
        }
449
450
        return $cache->get($cacheKey, $value);
451
    }
452
453
    /**
454
     * Creates an HTML element from an asset.
455
     *
456
     * @param Asset      $asset
457
     * @param array|null $attributes
458
     *
459
     * @return string
460
     */
461
    public function html(Asset $asset, array $attributes = null): string
462
    {
463
        $htmlAttributes = '';
464
        foreach ($attributes as $name => $value) {
465
            if (!empty($value)) {
466
                $htmlAttributes .= \sprintf(' %s="%s"', $name, $value);
467
            } else {
468
                $htmlAttributes .= \sprintf(' %s', $name);
469
            }
470
        }
471
472
        switch ($asset['ext']) {
473
            case 'css':
474
                return \sprintf('<link rel="stylesheet" href="%s"%s>', $asset['path'], $htmlAttributes);
475
            case 'js':
476
                return \sprintf('<script src="%s"%%s></script>', $asset['path'], $htmlAttributes);
477
        }
478
479
        if ($asset['type'] == 'image') {
480
            return \sprintf(
481
                '<img src="%s"%s>',
482
                $asset['path'],
483
                $htmlAttributes
484
            );
485
        }
486
487
        throw new Exception(\sprintf('%s is available with CSS, JS and images files only.', '"html" filter'));
488
    }
489
490
    /**
491
     * Returns the content of an Asset.
492
     *
493
     * @param Asset $asset
494
     *
495
     * @return string
496
     */
497
    public function inline(Asset $asset): string
498
    {
499
        if (is_null($asset['content'])) {
500
            throw new Exception(\sprintf('%s is available with CSS et JS files only.', '"inline" filter'));
501
        }
502
503
        return $asset['content'];
504
    }
505
506
    /**
507
     * Reads $length first characters of a string and adds a suffix.
508
     *
509
     * @param string|null $string
510
     * @param int         $length
511
     * @param string      $suffix
512
     *
513
     * @return string|null
514
     */
515
    public function excerpt(string $string = null, int $length = 450, string $suffix = ' …'): ?string
516
    {
517
        $string = str_replace('</p>', '<br /><br />', $string);
518
        $string = trim(strip_tags($string, '<br>'), '<br />');
519
        if (mb_strlen($string) > $length) {
520
            $string = mb_substr($string, 0, $length);
521
            $string .= $suffix;
522
        }
523
524
        return $string;
525
    }
526
527
    /**
528
     * Reads characters before '<!-- excerpt|break -->'.
529
     *
530
     * @param string|null $string
531
     *
532
     * @return string|null
533
     */
534
    public function excerptHtml(string $string = null): ?string
535
    {
536
        // https://regex101.com/r/Xl7d5I/3
537
        $pattern = '(.*)(<!--[[:blank:]]?(excerpt|break)[[:blank:]]?-->)(.*)';
538
        preg_match('/'.$pattern.'/is', $string, $matches);
539
        if (empty($matches)) {
540
            return $string;
541
        }
542
543
        return trim($matches[1]);
544
    }
545
546
    /**
547
     * Converts a Markdown string to HTML.
548
     *
549
     * @param string|null $markdown
550
     *
551
     * @return string|null
552
     */
553
    public function markdownToHtml(string $markdown): ?string
554
    {
555
        try {
556
            $parsedown = new Parsedown($this->builder);
557
            $html = $parsedown->text($markdown);
558
        } catch (\Exception $e) {
559
            throw new Exception('"markdown_to_html" filter can not convert supplied Markdown.');
560
        }
561
562
        return $html;
563
    }
564
565
    /**
566
     * Converts a JSON string to an array.
567
     *
568
     * @param string|null $json
569
     *
570
     * @return array|null
571
     */
572
    public function jsonDecode(string $json): ?array
573
    {
574
        try {
575
            $array = json_decode($json, true);
576
            if ($array === null && json_last_error() !== JSON_ERROR_NONE) {
577
                throw new \Exception('Error');
578
            }
579
        } catch (\Exception $e) {
580
            throw new Exception('"json_decode" filter can not parse supplied JSON.');
581
        }
582
583
        return $array;
584
    }
585
586
    /**
587
     * Calculates estimated time to read a text.
588
     *
589
     * @param string|null $text
590
     *
591
     * @return string
592
     */
593
    public function readtime(string $text = null): string
594
    {
595
        $words = str_word_count(strip_tags($text));
596
        $min = floor($words / 200);
597
        if ($min === 0) {
598
            return '1';
599
        }
600
601
        return (string) $min;
602
    }
603
604
    /**
605
     * Gets the value of an environment variable.
606
     *
607
     * @param string $var
608
     *
609
     * @return string|null
610
     */
611
    public function getEnv(string $var): ?string
612
    {
613
        return getenv($var) ?: null;
614
    }
615
}
616