Passed
Push — nested-sections ( 2d40b2...7dbf34 )
by Arnaud
12:03 queued 05:37
created

AbstractOptimize::process()   B

Complexity

Conditions 9
Paths 10

Size

Total Lines 55
Code Lines 38

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 9
eloc 38
nc 10
nop 0
dl 0
loc 55
rs 7.7564
c 0
b 0
f 0

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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\Step\Optimize;
15
16
use Cecil\Assets\Cache;
17
use Cecil\Exception\RuntimeException;
18
use Cecil\Step\AbstractStep;
19
use Cecil\Util;
20
use Symfony\Component\Finder\Finder;
21
22
/**
23
 * Post Processing.
24
 */
25
abstract class AbstractOptimize extends AbstractStep
26
{
27
    /** @var string File type (ie: 'css') */
28
    protected $type;
29
30
    /** @var mixed File processor */
31
    protected $processor;
32
33
    /**
34
     * {@inheritdoc}
35
     */
36
    public function init(array $options): void
37
    {
38
        if ($options['dry-run']) {
39
            return;
40
        }
41
        if (false === $this->config->get(sprintf('optimize.%s.enabled', $this->type))) {
42
            return;
43
        }
44
        if (true === $this->config->get('optimize.enabled')) {
45
            $this->canProcess = true;
46
        }
47
    }
48
49
    /**
50
     * {@inheritdoc}
51
     *
52
     * @throws RuntimeException
53
     */
54
    public function process(): void
55
    {
56
        $this->setProcessor();
57
58
        $extensions = (array) $this->config->get(sprintf('optimize.%s.ext', $this->type));
59
        if (empty($extensions)) {
60
            throw new RuntimeException(sprintf('The config key "optimize.%s.ext" is empty.', $this->type));
61
        }
62
63
        $files = Finder::create()
64
            ->files()
65
            ->in($this->config->getOutputPath())
66
            ->name('/\.(' . implode('|', $extensions) . ')$/')
67
            ->notName('/\.min\.(' . implode('|', $extensions) . ')$/')
68
            ->sortByName(true);
69
        $max = \count($files);
70
71
        if ($max <= 0) {
72
            $this->builder->getLogger()->info('No files');
73
74
            return;
75
        }
76
77
        $count = 0;
78
        $optimized = 0;
79
        $cache = new Cache($this->builder, 'optimized');
80
81
        /** @var \Symfony\Component\Finder\SplFileInfo $file */
82
        foreach ($files as $file) {
83
            $count++;
84
            $sizeBefore = $file->getSize();
85
            $message = sprintf('File "%s" processed', $this->builder->isDebug() ? $file->getPathname() : $file->getRelativePathname());
86
87
            $cacheKey = $cache->createKeyFromPath($file->getPathname(), $file->getRelativePathname());
88
            if (!$cache->has($cacheKey)) {
89
                $processed = $this->processFile($file);
90
                $sizeAfter = \strlen($processed);
91
                if ($sizeAfter < $sizeBefore) {
92
                    $message = sprintf(
93
                        'File "%s" optimized (%s Ko -> %s Ko)',
94
                        $this->builder->isDebug() ? $file->getPathname() : $file->getRelativePathname(),
95
                        ceil($sizeBefore / 1000),
96
                        ceil($sizeAfter / 1000)
97
                    );
98
                }
99
                $cache->set($cacheKey, $this->encode($processed));
100
                $optimized++;
101
102
                $this->builder->getLogger()->info($message, ['progress' => [$count, $max]]);
103
            }
104
            $processed = $this->decode($cache->get($cacheKey));
105
            Util\File::getFS()->dumpFile($file->getPathname(), $processed);
106
        }
107
        if ($optimized == 0) {
108
            $this->builder->getLogger()->info('Nothing to do');
109
        }
110
    }
111
112
    /**
113
     * Set file processor object.
114
     */
115
    abstract public function setProcessor(): void;
116
117
    /**
118
     * Process a file.
119
     */
120
    abstract public function processFile(\Symfony\Component\Finder\SplFileInfo $file): string;
121
122
    /**
123
     * Encode file content.
124
     */
125
    public function encode(string $content = null): ?string
126
    {
127
        return $content;
128
    }
129
130
    /**
131
     * Decode file content.
132
     */
133
    public function decode(string $content = null): ?string
134
    {
135
        return $content;
136
    }
137
}
138