Minify::keepImportantComments()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 5
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
1
<?php
2
3
namespace Robo\Task\Assets;
4
5
use Robo\Result;
6
use Robo\Task\BaseTask;
7
8
/**
9
 * Minifies an asset file (CSS or JS).
10
 *
11
 * ``` php
12
 * <?php
13
 * $this->taskMinify('web/assets/theme.css')
14
 *      ->run()
15
 * ?>
16
 * ```
17
 * Please install additional packages to use this task:
18
 *
19
 * ```
20
 * composer require patchwork/jsqueeze:^2.0
21
 * composer require natxet/cssmin:^3.0
22
 * ```
23
 */
24
class Minify extends BaseTask
25
{
26
    /**
27
     * @var string[]
28
     */
29
    protected $types = ['css', 'js'];
30
31
    /**
32
     * @var string
33
     */
34
    protected $text;
35
36
    /**
37
     * @var string
38
     */
39
    protected $dst;
40
41
    /**
42
     * @var string
43
     */
44
    protected $type;
45
46
    /**
47
     * @var bool[]
48
     */
49
    protected $squeezeOptions = [
50
        'singleLine' => true,
51
        'keepImportantComments' => true,
52
        'specialVarRx' => false,
53
    ];
54
55
    /**
56
     * Constructor. Accepts asset file path or string source.
57
     *
58
     * @param string $input
59
     */
60
    public function __construct($input)
61
    {
62
        if (file_exists($input)) {
63
            $this->fromFile($input);
64
            return;
65
        }
66
67
        $this->fromText($input);
68
    }
69
70
    /**
71
     * Sets destination. Tries to guess type from it.
72
     *
73
     * @param string $dst
74
     *
75
     * @return $this
76
     */
77
    public function to($dst)
78
    {
79
        $this->dst = $dst;
80
81
        if (!empty($this->dst) && empty($this->type)) {
82
            $this->type($this->getExtension($this->dst));
83
        }
84
85
        return $this;
86
    }
87
88
    /**
89
     * Sets type with validation.
90
     *
91
     * @param string $type
92
     *   Allowed values: "css", "js".
93
     *
94
     * @return $this
95
     */
96
    public function type($type)
97
    {
98
        $type = strtolower($type);
99
100
        if (in_array($type, $this->types)) {
101
            $this->type = $type;
102
        }
103
104
        return $this;
105
    }
106
107
    /**
108
     * Sets text from string source.
109
     *
110
     * @param string $text
111
     *
112
     * @return $this
113
     */
114
    protected function fromText($text)
115
    {
116
        $this->text = (string)$text;
117
        unset($this->type);
118
119
        return $this;
120
    }
121
122
    /**
123
     * Sets text from asset file path. Tries to guess type and set default destination.
124
     *
125
     * @param string $path
126
     *
127
     * @return $this
128
     */
129
    protected function fromFile($path)
130
    {
131
        $this->text = file_get_contents($path);
132
133
        unset($this->type);
134
        $this->type($this->getExtension($path));
135
136
        if (empty($this->dst) && !empty($this->type)) {
137
            $ext_length = strlen($this->type) + 1;
138
            $this->dst = substr($path, 0, -$ext_length) . '.min.' . $this->type;
139
        }
140
141
        return $this;
142
    }
143
144
    /**
145
     * Gets file extension from path.
146
     *
147
     * @param string $path
148
     *
149
     * @return string
150
     */
151
    protected function getExtension($path)
152
    {
153
        return pathinfo($path, PATHINFO_EXTENSION);
154
    }
155
156
    /**
157
     * Minifies and returns text.
158
     *
159
     * @return string|bool
160
     */
161
    protected function getMinifiedText()
162
    {
163
        switch ($this->type) {
164
            case 'css':
165
                if (!class_exists('\CssMin')) {
166
                    return Result::errorMissingPackage($this, 'CssMin', 'natxet/cssmin');
0 ignored issues
show
Bug Best Practice introduced by
The return type of return \Robo\Result::err...Min', 'natxet/cssmin'); (Robo\Result) is incompatible with the return type documented by Robo\Task\Assets\Minify::getMinifiedText of type string|boolean.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
167
                }
168
169
                return \CssMin::minify($this->text);
170
                break;
0 ignored issues
show
Unused Code introduced by
break is not strictly necessary here and could be removed.

The break statement is not necessary if it is preceded for example by a return statement:

switch ($x) {
    case 1:
        return 'foo';
        break; // This break is not necessary and can be left off.
}

If you would like to keep this construct to be consistent with other case statements, you can safely mark this issue as a false-positive.

Loading history...
171
172
            case 'js':
173
                if (!class_exists('\JSqueeze') && !class_exists('\Patchwork\JSqueeze')) {
174
                    return Result::errorMissingPackage($this, 'Patchwork\JSqueeze', 'patchwork/jsqueeze');
0 ignored issues
show
Bug Best Practice introduced by
The return type of return \Robo\Result::err... 'patchwork/jsqueeze'); (Robo\Result) is incompatible with the return type documented by Robo\Task\Assets\Minify::getMinifiedText of type string|boolean.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
175
                }
176
177
                if (class_exists('\JSqueeze')) {
178
                    $jsqueeze = new \JSqueeze();
179
                } else {
180
                    $jsqueeze = new \Patchwork\JSqueeze();
181
                }
182
183
                return $jsqueeze->squeeze(
184
                    $this->text,
185
                    $this->squeezeOptions['singleLine'],
186
                    $this->squeezeOptions['keepImportantComments'],
187
                    $this->squeezeOptions['specialVarRx']
188
                );
189
                break;
0 ignored issues
show
Unused Code introduced by
break is not strictly necessary here and could be removed.

The break statement is not necessary if it is preceded for example by a return statement:

switch ($x) {
    case 1:
        return 'foo';
        break; // This break is not necessary and can be left off.
}

If you would like to keep this construct to be consistent with other case statements, you can safely mark this issue as a false-positive.

Loading history...
190
        }
191
192
        return false;
193
    }
194
195
    /**
196
     * Single line option for the JS minimisation.
197
     *
198
     * @param bool $singleLine
199
     *
200
     * @return $this
201
     */
202
    public function singleLine($singleLine)
203
    {
204
        $this->squeezeOptions['singleLine'] = (bool)$singleLine;
205
        return $this;
206
    }
207
208
    /**
209
     * keepImportantComments option for the JS minimisation.
210
     *
211
     * @param bool $keepImportantComments
212
     *
213
     * @return $this
214
     */
215
    public function keepImportantComments($keepImportantComments)
216
    {
217
        $this->squeezeOptions['keepImportantComments'] = (bool)$keepImportantComments;
218
        return $this;
219
    }
220
221
    /**
222
     * Set specialVarRx option for the JS minimisation.
223
     *
224
     * @param bool $specialVarRx
225
     *
226
     * @return $this
227
     */
228
    public function specialVarRx($specialVarRx)
229
    {
230
        $this->squeezeOptions['specialVarRx'] = (bool)$specialVarRx;
231
        return $this;
232
    }
233
234
    /**
235
     * @return string
236
     */
237
    public function __toString()
238
    {
239
        return (string) $this->getMinifiedText();
240
    }
241
242
    /**
243
     * {@inheritdoc}
244
     */
245
    public function run()
246
    {
247
        if (empty($this->type)) {
248
            return Result::error($this, 'Unknown asset type.');
249
        }
250
251
        if (empty($this->dst)) {
252
            return Result::error($this, 'Unknown file destination.');
253
        }
254
255 View Code Duplication
        if (file_exists($this->dst) && !is_writable($this->dst)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
256
            return Result::error($this, 'Destination already exists and cannot be overwritten.');
257
        }
258
259
        $size_before = strlen($this->text);
260
        $minified = $this->getMinifiedText();
261
262
        if ($minified instanceof Result) {
263
            return $minified;
264
        } elseif (false === $minified) {
265
            return Result::error($this, 'Minification failed.');
266
        }
267
268
        $size_after = strlen($minified);
269
270
        // Minification did not reduce file size, so use original file.
271
        if ($size_after > $size_before) {
272
            $minified = $this->text;
273
            $size_after = $size_before;
274
        }
275
276
        $dst = $this->dst . '.part';
277
        $write_result = file_put_contents($dst, $minified);
278
279
        if (false === $write_result) {
280
            @unlink($dst);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
281
            return Result::error($this, 'File write failed.');
282
        }
283
        // Cannot be cross-volume; should always succeed.
284
        @rename($dst, $this->dst);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
285
        if ($size_before === 0) {
286
            $minified_percent = 0;
287
        } else {
288
            $minified_percent = number_format(100 - ($size_after / $size_before * 100), 1);
289
        }
290
        $this->printTaskSuccess('Wrote {filepath}', ['filepath' => $this->dst]);
291
        $context = [
292
            'bytes' => $this->formatBytes($size_after),
293
            'reduction' => $this->formatBytes(($size_before - $size_after)),
294
            'percentage' => $minified_percent,
295
        ];
296
        $this->printTaskSuccess('Wrote {bytes} (reduced by {reduction} / {percentage})', $context);
297
        return Result::success($this, 'Asset minified.');
298
    }
299
}
300