Completed
Pull Request — master (#95)
by Gino
01:48
created

Minify::openFileForWriting()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 7
rs 9.4285
cc 2
eloc 4
nc 2
nop 1
1
<?php
2
3
namespace MatthiasMullie\Minify;
4
5
use Psr\Cache\CacheItemInterface;
6
7
/**
8
 * Abstract minifier class.
9
 *
10
 * Please report bugs on https://github.com/matthiasmullie/minify/issues
11
 *
12
 * @author Matthias Mullie <[email protected]>
13
 * @copyright Copyright (c) 2012, Matthias Mullie. All rights reserved.
14
 * @license MIT License
15
 */
16
abstract class Minify
17
{
18
    /**
19
     * The data to be minified.
20
     *
21
     * @var string[]
22
     */
23
    protected $data = array();
24
25
    /**
26
     * Array of patterns to match.
27
     *
28
     * @var string[]
29
     */
30
    protected $patterns = array();
31
32
    /**
33
     * This array will hold content of strings and regular expressions that have
34
     * been extracted from the JS source code, so we can reliably match "code",
35
     * without having to worry about potential "code-like" characters inside.
36
     *
37
     * @var string[]
38
     */
39
    public $extracted = array();
40
41
    /**
42
     * Init the minify class - optionally, code may be passed along already.
43
     */
44
    public function __construct(/* $data = null, ... */)
45
    {
46
        // it's possible to add the source through the constructor as well ;)
47
        if (func_num_args()) {
48
            call_user_func_array(array($this, 'add'), func_get_args());
49
        }
50
    }
51
52
    /**
53
     * Add a file or straight-up code to be minified.
54
     *
55
     * @param string $data
56
     */
57
    public function add($data /* $data = null, ... */)
58
    {
59
        // bogus "usage" of parameter $data: scrutinizer warns this variable is
60
        // not used (we're using func_get_args instead to support overloading),
61
        // but it still needs to be defined because it makes no sense to have
62
        // this function without argument :)
63
        $args = array($data) + func_get_args();
64
65
        // this method can be overloaded
66
        foreach ($args as $data) {
67
            // redefine var
68
            $data = (string) $data;
69
70
            // load data
71
            $value = $this->load($data);
72
            $key = ($data != $value) ? $data : count($this->data);
73
74
            // store data
75
            $this->data[$key] = $value;
76
        }
77
    }
78
79
    /**
80
     * Minify the data & (optionally) saves it to a file.
81
     *
82
     * @param string[optional] $path Path to write the data to.
83
     *
84
     * @return string The minified data.
85
     */
86
    public function minify($path = null)
87
    {
88
        $content = $this->execute($path);
89
90
        // save to path
91
        if ($path !== null) {
92
            $this->save($content, $path);
93
        }
94
95
        return $content;
96
    }
97
98
    /**
99
     * Minify & gzip the data & (optionally) saves it to a file.
100
     *
101
     * @param string[optional] $path  Path to write the data to.
102
     * @param int[optional]    $level Compression level, from 0 to 9.
103
     *
104
     * @return string The minified & gzipped data.
105
     */
106
    public function gzip($path = null, $level = 9)
107
    {
108
        $content = $this->execute($path);
109
        $content = gzencode($content, $level, FORCE_GZIP);
110
111
        // save to path
112
        if ($path !== null) {
113
            $this->save($content, $path);
114
        }
115
116
        return $content;
117
    }
118
119
    /**
120
     * Minify the data & write it to a CacheItemInterface object.
121
     *
122
     * @param CacheItemInterface $item Cache item to write the data to.
123
     *
124
     * @return CacheItemInterface Cache item with the minifier data.
125
     */
126
    public function cache(CacheItemInterface $item)
127
    {
128
        $content = $this->execute();
129
        $item->set($content);
130
131
        return $item;
132
    }
133
134
    /**
135
     * Minify the data.
136
     *
137
     * @param string[optional] $path Path to write the data to.
138
     *
139
     * @return string The minified data.
140
     */
141
    abstract public function execute($path = null);
142
143
    /**
144
     * Load data.
145
     *
146
     * @param string $data Either a path to a file or the content itself.
147
     *
148
     * @return string
149
     */
150
    protected function load($data)
151
    {
152
        // check if the data is a file
153
        if ($this->canImportFile($data)) {
154
            $data = file_get_contents($data);
155
156
            // strip BOM, if any
157
            if (substr($data, 0, 3) == "\xef\xbb\xbf") {
158
                $data = substr($data, 3);
159
            }
160
        }
161
162
        return $data;
163
    }
164
165
    /**
166
     * Save to file.
167
     *
168
     * @param string $content The minified data.
169
     * @param string $path    The path to save the minified data to.
170
     *
171
     * @throws Exception
172
     */
173
    protected function save($content, $path)
174
    {
175
        $handler = $this->openFileForWriting($path);
176
177
        $this->writeToFile($handler, $content);
178
179
        @fclose($handler);
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...
180
    }
181
182
    /**
183
     * Register a pattern to execute against the source content.
184
     *
185
     * @param string          $pattern     PCRE pattern.
186
     * @param string|callable $replacement Replacement value for matched pattern.
187
     *
188
     * @throws Exception
189
     */
190
    protected function registerPattern($pattern, $replacement = '')
191
    {
192
        // study the pattern, we'll execute it more than once
193
        $pattern .= 'S';
194
195
        $this->patterns[] = array($pattern, $replacement);
196
    }
197
198
    /**
199
     * We can't "just" run some regular expressions against JavaScript: it's a
200
     * complex language. E.g. having an occurrence of // xyz would be a comment,
201
     * unless it's used within a string. Of you could have something that looks
202
     * like a 'string', but inside a comment.
203
     * The only way to accurately replace these pieces is to traverse the JS one
204
     * character at a time and try to find whatever starts first.
205
     *
206
     * @param string $content The content to replace patterns in.
207
     *
208
     * @return string The (manipulated) content.
209
     */
210
    protected function replace($content)
211
    {
212
        $processed = '';
213
        $positions = array_fill(0, count($this->patterns), -1);
214
        $matches = array();
215
216
        while ($content) {
217
            // find first match for all patterns
218
            foreach ($this->patterns as $i => $pattern) {
219
                list($pattern, $replacement) = $pattern;
220
221
                // no need to re-run matches that are still in the part of the
222
                // content that hasn't been processed
223
                if ($positions[$i] >= 0) {
224
                    continue;
225
                }
226
227
                $match = null;
228
                if (preg_match($pattern, $content, $match)) {
229
                    $matches[$i] = $match;
230
231
                    // we'll store the match position as well; that way, we
232
                    // don't have to redo all preg_matches after changing only
233
                    // the first (we'll still know where those others are)
234
                    $positions[$i] = strpos($content, $match[0]);
235
                } else {
236
                    // if the pattern couldn't be matched, there's no point in
237
                    // executing it again in later runs on this same content;
238
                    // ignore this one until we reach end of content
239
                    unset($matches[$i]);
240
                    $positions[$i] = strlen($content);
241
                }
242
            }
243
244
            // no more matches to find: everything's been processed, break out
245
            if (!$matches) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $matches of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
246
                $processed .= $content;
247
                break;
248
            }
249
250
            // see which of the patterns actually found the first thing (we'll
251
            // only want to execute that one, since we're unsure if what the
252
            // other found was not inside what the first found)
253
            $discardLength = min($positions);
254
            $firstPattern = array_search($discardLength, $positions);
255
            $match = $matches[$firstPattern][0];
256
257
            // execute the pattern that matches earliest in the content string
258
            list($pattern, $replacement) = $this->patterns[$firstPattern];
259
            $replacement = $this->replacePattern($pattern, $replacement, $content);
260
261
            // figure out which part of the string was unmatched; that's the
262
            // part we'll execute the patterns on again next
263
            $content = substr($content, $discardLength);
264
            $unmatched = (string) substr($content, strpos($content, $match) + strlen($match));
265
266
            // move the replaced part to $processed and prepare $content to
267
            // again match batch of patterns against
268
            $processed .= substr($replacement, 0, strlen($replacement) - strlen($unmatched));
269
            $content = $unmatched;
270
271
            // first match has been replaced & that content is to be left alone,
272
            // the next matches will start after this replacement, so we should
273
            // fix their offsets
274
            foreach ($positions as $i => $position) {
275
                $positions[$i] -= $discardLength + strlen($match);
276
            }
277
        }
278
279
        return $processed;
280
    }
281
282
    /**
283
     * This is where a pattern is matched against $content and the matches
284
     * are replaced by their respective value.
285
     * This function will be called plenty of times, where $content will always
286
     * move up 1 character.
287
     *
288
     * @param string          $pattern     Pattern to match.
289
     * @param string|callable $replacement Replacement value.
290
     * @param string          $content     Content to match pattern against.
291
     *
292
     * @return string
293
     */
294
    protected function replacePattern($pattern, $replacement, $content)
295
    {
296
        if (is_callable($replacement)) {
297
            return preg_replace_callback($pattern, $replacement, $content, 1, $count);
298
        } else {
299
            return preg_replace($pattern, $replacement, $content, 1, $count);
300
        }
301
    }
302
303
    /**
304
     * Strings are a pattern we need to match, in order to ignore potential
305
     * code-like content inside them, but we just want all of the string
306
     * content to remain untouched.
307
     *
308
     * This method will replace all string content with simple STRING#
309
     * placeholder text, so we've rid all strings from characters that may be
310
     * misinterpreted. Original string content will be saved in $this->extracted
311
     * and after doing all other minifying, we can restore the original content
312
     * via restoreStrings().
313
     *
314
     * @param string[optional] $chars
315
     */
316
    protected function extractStrings($chars = '\'"')
317
    {
318
        // PHP only supports $this inside anonymous functions since 5.4
319
        $minifier = $this;
320
        $callback = function ($match) use ($minifier) {
321
            if (!$match[1]) {
322
                /*
323
                 * Empty strings need no placeholder; they can't be confused for
324
                 * anything else anyway.
325
                 * But we still needed to match them, for the extraction routine
326
                 * to skip over this particular string.
327
                 */
328
                return $match[0];
329
            }
330
331
            $count = count($minifier->extracted);
332
            $placeholder = $match[1].$count.$match[1];
333
            $minifier->extracted[$placeholder] = $match[1].$match[2].$match[1];
334
335
            return $placeholder;
336
        };
337
338
        /*
339
         * The \\ messiness explained:
340
         * * Don't count ' or " as end-of-string if it's escaped (has backslash
341
         * in front of it)
342
         * * Unless... that backslash itself is escaped (another leading slash),
343
         * in which case it's no longer escaping the ' or "
344
         * * So there can be either no backslash, or an even number
345
         * * multiply all of that times 4, to account for the escaping that has
346
         * to be done to pass the backslash into the PHP string without it being
347
         * considered as escape-char (times 2) and to get it in the regex,
348
         * escaped (times 2)
349
         */
350
        $this->registerPattern('/(['.$chars.'])(.*?(?<!\\\\)(\\\\\\\\)*+)\\1/s', $callback);
351
    }
352
353
    /**
354
     * This method will restore all extracted data (strings, regexes) that were
355
     * replaced with placeholder text in extract*(). The original content was
356
     * saved in $this->extracted.
357
     *
358
     * @param string $content
359
     *
360
     * @return string
361
     */
362
    protected function restoreExtractedData($content)
363
    {
364
        if (!$this->extracted) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->extracted of type string[] is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
365
            // nothing was extracted, nothing to restore
366
            return $content;
367
        }
368
369
        $content = strtr($content, $this->extracted);
370
371
        $this->extracted = array();
372
373
        return $content;
374
    }
375
376
    /**
377
     *
378
     * Check if the path is a regular file and can be read.
379
     *
380
     * @param string $path
381
     * @return bool
382
     */
383
    protected function canImportFile($path) {
384
        return (strlen($path) < PHP_MAXPATHLEN && is_file($path) && is_readable($path));
385
    }
386
387
    /**
388
     *
389
     * Attempts to open file specified by $path for writing.
390
     *
391
     * @param   string      $path   The path to the file.
392
     * @return  resource    Specifier for the target file.
393
     *
394
     * @throws  Exception
395
     */
396
    protected function openFileForWriting($path) {
397
        if (($handler = @fopen($path, 'w')) === false) {
398
            throw new Exception('The file "'.$path.'" could not be opened for writing. Check if PHP has enough permissions.');
399
        }
400
401
        return $handler;
402
    }
403
404
    /**
405
     *
406
     * Attempts to write $content to the file specified by $handler. $path is used for printing exceptions.
407
     *
408
     * @param   resource    $handler    The resource to write to.
409
     * @param   string      $content    The content to write.
410
     * @param   string      $path       The path to the file (for exception printing only).
411
     *
412
     * @throws  Exception
413
     */
414
    protected function writeToFile($handler, $content, $path = '') {
415
        if (@fwrite($handler, $content) === false) {
416
            throw new Exception('The file "'.$path.'" could not be written to. Check your disk space and file permissions.');
417
        }
418
    }
419
}
420