Completed
Pull Request — master (#95)
by Gino
01:51
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 MatthiasMullie\Minify\Exception\IOException;
6
use Psr\Cache\CacheItemInterface;
7
8
/**
9
 * Abstract minifier class.
10
 *
11
 * Please report bugs on https://github.com/matthiasmullie/minify/issues
12
 *
13
 * @author Matthias Mullie <[email protected]>
14
 * @copyright Copyright (c) 2012, Matthias Mullie. All rights reserved.
15
 * @license MIT License
16
 */
17
abstract class Minify
18
{
19
    /**
20
     * The data to be minified.
21
     *
22
     * @var string[]
23
     */
24
    public $data = array();
25
26
    /**
27
     * Array of patterns to match.
28
     *
29
     * @var string[]
30
     */
31
    protected $patterns = array();
32
33
    /**
34
     * This array will hold content of strings and regular expressions that have
35
     * been extracted from the JS source code, so we can reliably match "code",
36
     * without having to worry about potential "code-like" characters inside.
37
     *
38
     * @var string[]
39
     */
40
    public $extracted = array();
41
42
    /**
43
     * Init the minify class - optionally, code may be passed along already.
44
     */
45
    public function __construct(/* $data = null, ... */)
46
    {
47
        // it's possible to add the source through the constructor as well ;)
48
        if (func_num_args()) {
49
            call_user_func_array(array($this, 'add'), func_get_args());
50
        }
51
    }
52
53
    /**
54
     * Add a file or straight-up code to be minified.
55
     *
56
     * @param string $data
57
     */
58
    public function add($data /* $data = null, ... */)
59
    {
60
        // bogus "usage" of parameter $data: scrutinizer warns this variable is
61
        // not used (we're using func_get_args instead to support overloading),
62
        // but it still needs to be defined because it makes no sense to have
63
        // this function without argument :)
64
        $args = array($data) + func_get_args();
65
66
        // this method can be overloaded
67
        foreach ($args as $data) {
68
            // redefine var
69
            $data = (string) $data;
70
71
            // load data
72
            $value = $this->load($data);
73
            $key = ($data != $value) ? $data : count($this->data);
74
75
            // store data
76
            $this->data[$key] = $value;
77
        }
78
    }
79
80
    /**
81
     * Minify the data & (optionally) saves it to a file.
82
     *
83
     * @param string[optional] $path Path to write the data to.
84
     *
85
     * @return string The minified data.
86
     */
87
    public function minify($path = null)
88
    {
89
        $content = $this->execute($path);
90
91
        // save to path
92
        if ($path !== null) {
93
            $this->save($content, $path);
94
        }
95
96
        return $content;
97
    }
98
99
    /**
100
     * Minify & gzip the data & (optionally) saves it to a file.
101
     *
102
     * @param string[optional] $path  Path to write the data to.
103
     * @param int[optional]    $level Compression level, from 0 to 9.
104
     *
105
     * @return string The minified & gzipped data.
106
     */
107
    public function gzip($path = null, $level = 9)
108
    {
109
        $content = $this->execute($path);
110
        $content = gzencode($content, $level, FORCE_GZIP);
111
112
        // save to path
113
        if ($path !== null) {
114
            $this->save($content, $path);
115
        }
116
117
        return $content;
118
    }
119
120
    /**
121
     * Minify the data & write it to a CacheItemInterface object.
122
     *
123
     * @param CacheItemInterface $item Cache item to write the data to.
124
     *
125
     * @return CacheItemInterface Cache item with the minifier data.
126
     */
127
    public function cache(CacheItemInterface $item)
128
    {
129
        $content = $this->execute();
130
        $item->set($content);
131
132
        return $item;
133
    }
134
135
    /**
136
     * Minify the data.
137
     *
138
     * @param string[optional] $path Path to write the data to.
139
     *
140
     * @return string The minified data.
141
     */
142
    abstract public function execute($path = null);
143
144
    /**
145
     * Load data.
146
     *
147
     * @param string $data Either a path to a file or the content itself.
148
     *
149
     * @return string
150
     */
151
    protected function load($data)
152
    {
153
        // check if the data is a file
154
        if ($this->canImportFile($data)) {
155
            $data = file_get_contents($data);
156
157
            // strip BOM, if any
158
            if (substr($data, 0, 3) == "\xef\xbb\xbf") {
159
                $data = substr($data, 3);
160
            }
161
        }
162
163
        return $data;
164
    }
165
166
    /**
167
     * Save to file.
168
     *
169
     * @param string $content The minified data.
170
     * @param string $path    The path to save the minified data to.
171
     *
172
     * @throws IOException
173
     */
174
    protected function save($content, $path)
175
    {
176
        $handler = $this->openFileForWriting($path);
177
178
        $this->writeToFile($handler, $content);
179
180
        @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...
181
    }
182
183
    /**
184
     * Register a pattern to execute against the source content.
185
     *
186
     * @param string          $pattern     PCRE pattern.
187
     * @param string|callable $replacement Replacement value for matched pattern.
188
     *
189
     * @throws Exception
190
     */
191
    protected function registerPattern($pattern, $replacement = '')
192
    {
193
        // study the pattern, we'll execute it more than once
194
        $pattern .= 'S';
195
196
        $this->patterns[] = array($pattern, $replacement);
197
    }
198
199
    /**
200
     * We can't "just" run some regular expressions against JavaScript: it's a
201
     * complex language. E.g. having an occurrence of // xyz would be a comment,
202
     * unless it's used within a string. Of you could have something that looks
203
     * like a 'string', but inside a comment.
204
     * The only way to accurately replace these pieces is to traverse the JS one
205
     * character at a time and try to find whatever starts first.
206
     *
207
     * @param string $content The content to replace patterns in.
208
     *
209
     * @return string The (manipulated) content.
210
     */
211
    protected function replace($content)
212
    {
213
        $processed = '';
214
        $positions = array_fill(0, count($this->patterns), -1);
215
        $matches = array();
216
217
        while ($content) {
218
            // find first match for all patterns
219
            foreach ($this->patterns as $i => $pattern) {
220
                list($pattern, $replacement) = $pattern;
221
222
                // no need to re-run matches that are still in the part of the
223
                // content that hasn't been processed
224
                if ($positions[$i] >= 0) {
225
                    continue;
226
                }
227
228
                $match = null;
229
                if (preg_match($pattern, $content, $match)) {
230
                    $matches[$i] = $match;
231
232
                    // we'll store the match position as well; that way, we
233
                    // don't have to redo all preg_matches after changing only
234
                    // the first (we'll still know where those others are)
235
                    $positions[$i] = strpos($content, $match[0]);
236
                } else {
237
                    // if the pattern couldn't be matched, there's no point in
238
                    // executing it again in later runs on this same content;
239
                    // ignore this one until we reach end of content
240
                    unset($matches[$i]);
241
                    $positions[$i] = strlen($content);
242
                }
243
            }
244
245
            // no more matches to find: everything's been processed, break out
246
            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...
247
                $processed .= $content;
248
                break;
249
            }
250
251
            // see which of the patterns actually found the first thing (we'll
252
            // only want to execute that one, since we're unsure if what the
253
            // other found was not inside what the first found)
254
            $discardLength = min($positions);
255
            $firstPattern = array_search($discardLength, $positions);
256
            $match = $matches[$firstPattern][0];
257
258
            // execute the pattern that matches earliest in the content string
259
            list($pattern, $replacement) = $this->patterns[$firstPattern];
260
            $replacement = $this->replacePattern($pattern, $replacement, $content);
261
262
            // figure out which part of the string was unmatched; that's the
263
            // part we'll execute the patterns on again next
264
            $content = substr($content, $discardLength);
265
            $unmatched = (string) substr($content, strpos($content, $match) + strlen($match));
266
267
            // move the replaced part to $processed and prepare $content to
268
            // again match batch of patterns against
269
            $processed .= substr($replacement, 0, strlen($replacement) - strlen($unmatched));
270
            $content = $unmatched;
271
272
            // first match has been replaced & that content is to be left alone,
273
            // the next matches will start after this replacement, so we should
274
            // fix their offsets
275
            foreach ($positions as $i => $position) {
276
                $positions[$i] -= $discardLength + strlen($match);
277
            }
278
        }
279
280
        return $processed;
281
    }
282
283
    /**
284
     * This is where a pattern is matched against $content and the matches
285
     * are replaced by their respective value.
286
     * This function will be called plenty of times, where $content will always
287
     * move up 1 character.
288
     *
289
     * @param string          $pattern     Pattern to match.
290
     * @param string|callable $replacement Replacement value.
291
     * @param string          $content     Content to match pattern against.
292
     *
293
     * @return string
294
     */
295
    protected function replacePattern($pattern, $replacement, $content)
296
    {
297
        if (is_callable($replacement)) {
298
            return preg_replace_callback($pattern, $replacement, $content, 1, $count);
299
        } else {
300
            return preg_replace($pattern, $replacement, $content, 1, $count);
301
        }
302
    }
303
304
    /**
305
     * Strings are a pattern we need to match, in order to ignore potential
306
     * code-like content inside them, but we just want all of the string
307
     * content to remain untouched.
308
     *
309
     * This method will replace all string content with simple STRING#
310
     * placeholder text, so we've rid all strings from characters that may be
311
     * misinterpreted. Original string content will be saved in $this->extracted
312
     * and after doing all other minifying, we can restore the original content
313
     * via restoreStrings().
314
     *
315
     * @param string[optional] $chars
316
     */
317
    protected function extractStrings($chars = '\'"')
318
    {
319
        // PHP only supports $this inside anonymous functions since 5.4
320
        $minifier = $this;
321
        $callback = function ($match) use ($minifier) {
322
            //check the second index here, because the first always contains a quote
323
            //that's why inner block could never be reached
324
            if (!$match[2]) {
325
                /*
326
                 * Empty strings need no placeholder; they can't be confused for
327
                 * anything else anyway.
328
                 * But we still needed to match them, for the extraction routine
329
                 * to skip over this particular string.
330
                 */
331
                return $match[0];
332
            }
333
334
            $count = count($minifier->extracted);
335
            $placeholder = $match[1].$count.$match[1];
336
            $minifier->extracted[$placeholder] = $match[1].$match[2].$match[1];
337
338
            return $placeholder;
339
        };
340
341
        /*
342
         * The \\ messiness explained:
343
         * * Don't count ' or " as end-of-string if it's escaped (has backslash
344
         * in front of it)
345
         * * Unless... that backslash itself is escaped (another leading slash),
346
         * in which case it's no longer escaping the ' or "
347
         * * So there can be either no backslash, or an even number
348
         * * multiply all of that times 4, to account for the escaping that has
349
         * to be done to pass the backslash into the PHP string without it being
350
         * considered as escape-char (times 2) and to get it in the regex,
351
         * escaped (times 2)
352
         */
353
        $this->registerPattern('/(['.$chars.'])(.*?(?<!\\\\)(\\\\\\\\)*+)\\1/s', $callback);
354
    }
355
356
    /**
357
     * This method will restore all extracted data (strings, regexes) that were
358
     * replaced with placeholder text in extract*(). The original content was
359
     * saved in $this->extracted.
360
     *
361
     * @param string $content
362
     *
363
     * @return string
364
     */
365
    protected function restoreExtractedData($content)
366
    {
367
        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...
368
            // nothing was extracted, nothing to restore
369
            return $content;
370
        }
371
372
        $content = strtr($content, $this->extracted);
373
374
        $this->extracted = array();
375
376
        return $content;
377
    }
378
379
    /**
380
     *
381
     * Check if the path is a regular file and can be read.
382
     *
383
     * @param string $path
384
     * @return bool
385
     */
386
    protected function canImportFile($path) {
387
        return (strlen($path) < PHP_MAXPATHLEN && is_file($path) && is_readable($path));
388
    }
389
390
    /**
391
     *
392
     * Attempts to open file specified by $path for writing.
393
     *
394
     * @param   string      $path   The path to the file.
395
     * @return  resource    Specifier for the target file.
396
     *
397
     * @throws  IOException
398
     */
399
    protected function openFileForWriting($path) {
400
        if (($handler = @fopen($path, 'w')) === false) {
401
            throw new IOException('The file "'.$path.'" could not be opened for writing. Check if PHP has enough permissions.');
402
        }
403
404
        return $handler;
405
    }
406
407
    /**
408
     *
409
     * Attempts to write $content to the file specified by $handler. $path is used for printing exceptions.
410
     *
411
     * @param   resource    $handler    The resource to write to.
412
     * @param   string      $content    The content to write.
413
     * @param   string      $path       The path to the file (for exception printing only).
414
     *
415
     * @throws  IOException
416
     */
417
    protected function writeToFile($handler, $content, $path = '') {
418
        if (($result = @fwrite($handler, $content)) === false || ($result < strlen($content))) {
419
            throw new IOException('The file "'.$path.'" could not be written to. Check your disk space and file permissions.');
420
        }
421
    }
422
}
423