forked from matthiasmullie/minify
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMinify.php
More file actions
312 lines (276 loc) · 11.5 KB
/
Copy pathMinify.php
File metadata and controls
312 lines (276 loc) · 11.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
<?php
namespace MatthiasMullie\Minify;
/**
* Minify abstract class
*
* This source file can be used to write minifiers for multiple file types.
*
* The class is documented in the file itself. If you find any bugs help me out and report them. Reporting can be done by sending an email to minify@mullie.eu.
* If you report a bug, make sure you give me enough information (include your code).
*
* License
* Copyright (c) 2012, Matthias Mullie. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products derived from this software without specific prior written permission.
*
* This software is provided by the author "as is" and any express or implied warranties, including, but not limited to, the implied warranties of merchantability and fitness for a particular purpose are disclaimed. In no event shall the author be liable for any direct, indirect, incidental, special, exemplary, or consequential damages (including, but not limited to, procurement of substitute goods or services; loss of use, data, or profits; or business interruption) however caused and on any theory of liability, whether in contract, strict liability, or tort (including negligence or otherwise) arising in any way out of the use of this software, even if advised of the possibility of such damage.
*
* @author Matthias Mullie <minify@mullie.eu>
* @version 1.3.0
*
* @copyright Copyright (c) 2012, Matthias Mullie. All rights reserved.
* @license MIT License
*/
abstract class Minify
{
/**
* The data to be minified
*
* @var array
*/
protected $data = array();
/**
* Array of patterns to match.
*
* @var array
*/
protected $patterns = array();
/**
* Quite a useless variable, for dev-purpose only.
* Can be helpful when running the test suite, to single out a specific
* test to debug.
*
* @var bool
*/
protected $debug = false;
/**
* Init the minify class - optionally, code may be passed along already.
*
* @param string[optional] $css
*/
public function __construct()
{
// it's possible to add the css through the constructor as well ;)
$arguments = func_get_args();
if(func_num_args()) call_user_func_array(array($this, 'add'), $arguments);
}
/**
* Add a file or straight-up code to be minified.
*
* @param string $data
*/
public function add($data)
{
// this method can be overloaded
foreach (func_get_args() as $data) {
// redefine var
$data = (string) $data;
// load data
$value = $this->load($data);
$key = ($data != $value) ? $data : 0;
// initialize key
if(!array_key_exists($key, $this->data)) $this->data[$key] = '';
// store data
$this->data[$key] .= $value;
}
}
/**
* Load data.
*
* @param string $data Either a path to a file or the content itself.
* @return string
*/
protected function load($data)
{
// check if the data is a file
if (@file_exists($data) && is_file($data)) {
// grab content
return @file_get_contents($data);
}
// no file, just return the data itself
else return $data;
}
/**
* Save to file
*
* @param string $content The minified data.
* @param string $path The path to save the minified data to.
* @throws Exception
*/
protected function save($content, $path)
{
// create file & open for writing
if(($handler = @fopen($path, 'w')) === false) throw new Exception('The file "' . $path . '" could not be opened. Check if PHP has enough permissions.');
// write to file
if(@fwrite($handler, $content) === false) throw new Exception('The file "' . $path . '" could not be written to. Check if PHP has enough permissions.');
// close the file
@fclose($handler);
}
/**
* Sets the debug state.
* Can be helpful when running the test suite, to single out a specific test
* to debug.
*
* @param bool $debug
*/
public function debug($debug) {
$this->debug = (bool) $debug;
}
/**
* Prints a var_dump of all vars tossed in, then exits.
* Only when $this->debug is set to true.
*
* @param mixed $vars Can be overloaded with multiple vars
*/
protected function dump($vars /* [, $var2 [, ...]] */) {
if(!$this->debug) return;
var_dump(func_get_args());
exit;
}
/**
* Minify the data.
*
* @param string[optional] $path Path to write the data to.
* @return string The minified data.
*/
abstract public function minify($path = null);
/**
* Register a pattern to execute against the source content.
* Patterns should always include caret (= start from the beginning of the
* string) - processing will be performed by traversing the content
* character by character, so we need the pattern to start matching
* exactly at the first character of the content at that point.
*
* @param string $pattern PCRE pattern.
* @param string|callable $replacement Replacement value for matched pattern.
* @param bool $skip Identifies if this match should be skipped by the rest of the patterns, once matched.
* @throws Exception
*/
protected function registerPattern($pattern, $replacement = '', $skip = false) {
// doublecheck if pattern actually starts at beginning of content
if(substr($pattern, 1, 1) !== '^') {
throw new Exception('Pattern "' . $pattern . '" should start processing at the beginning of the string.');
}
$this->patterns[] = array($pattern, $replacement, $skip);
}
/**
* We can't "just" run some regular expressions against JavaScript: it's a
* complex language. E.g. having an occurrence of // xyz would be a comment,
* unless it's used within a string. Of you could have something that looks
* like a 'string', but inside a comment.
* The only way to accurately replace these pieces is to traverse the JS one
* character at a time and try to find whatever starts first.
*
* @param string $content The content to replace patterns in.
* @return string The (manipulated) content.
*/
protected function replace($content)
{
// every character that has been processed will be moved to this string
$processed = '';
// update will keep shrinking, character by character, until all of it
// has been processed
while($content) {
$ignore = -1;
for($i = 0; $i < count($this->patterns); $i++) {
// pattern to ignore (if it was previously matched)
if($i === $ignore) continue;
list($pattern, $replacement, $skip) = $this->patterns[$i];
// replace pattern occurrences starting at this character
list($content, $replacement, $match) = $this->replacePattern($pattern, $content, $replacement);
// pattern matched & content replaced; save replacement value
if($match != '' || $replacement != '') {
// some patterns will want to make sure that the replaced
// content is not touched by any other patterns (like
// strings are comments)
if($skip) {
$processed .= $replacement;
$content = (string) substr($content, strlen($replacement));
continue 2;
}
// since there's been a change in the content, let's re-run
// all patterns at the start of the new content, but make
// sure the same pattern is ignored time
$ignore = $i;
$i = -1;
}
}
// add this character to $processed & strip it from $content, moving
// on to the next character
$processed .= $content[0];
$content = substr($content, 1);
}
// clear registered patterns
$this->patterns = array();
return $processed;
}
/**
* This is where a pattern is matched against $content and the matches
* are replaced by their respective value.
* This function will be called plenty of times, where $content will always
* move up 1 character.
*
* @param string $pattern Pattern to match.
* @param string $content Content to match pattern against.
* @param string|callable $replacement Replacement value.
* @return array [content, replacement, match]
*/
protected function replacePattern($pattern, $content, $replacement) {
if(is_callable($replacement)) {
return $this->replaceWithCallback($pattern, $content, $replacement);
} else {
return $this->replaceWithString($pattern, $content, $replacement);
}
}
/**
* Replaces pattern by a value from a callback, via preg_replace_callback.
*
* @param string $pattern Pattern to match.
* @param string $content Content to match pattern against.
* @param string|callable $replacement Replacement value.
* @return array [content, replacement, match]
*/
protected function replaceWithCallback($pattern, $content, $replacement) {
$matched = '';
$replaced = '';
/*
* Instead of just passing the $replacement callback, we'll wrap another
* callback around it to also allow us to catch the match & replacement
* value.
*/
$callback = function($match) use ($replacement, &$replaced, &$matched) {
$matched = $match;
$replaced = call_user_func($replacement, $match);
return $replaced;
};
$content = preg_replace_callback($pattern, $callback, $content, 1, $count);
return array($content, $replaced, $matched);
}
/**
* Replaces pattern by a value from a callback, via preg_replace.
*
* @param string $pattern Pattern to match.
* @param string $content Content to match pattern against.
* @param string|callable $replacement Replacement value.
* @return array [content, replacement, match]
*/
protected function replaceWithString($pattern, $content, $replacement) {
/*
* This preg_match is really only meant to capture $match, which we can
* then also use to deduce the replacement value. We can't just assume
* $replacement as replacement value, because it may be a back-reference
* (e.g. \\1)
*/
if(!preg_match($pattern, $content, $match)) {
return array($content, '', '');
}
$untouched = strlen($content) - strlen($match[0]);
$content = preg_replace($pattern, $replacement, $content, 1, $count);
$replaced = (string) substr($content, 0, strlen($content) - $untouched);
return array($content, $replaced, $match[0]);
}
}