/
AssetsCompressor.php
375 lines (314 loc) · 10.5 KB
/
AssetsCompressor.php
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
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
<?php
/**
* @name AssetsCompressor/AssetsCompressor
* @link https://github.com/AssetsCompressor/AssetsCompressor
* @author Artur Stępień
* @authorEmail artur.stepien@bestproject.pl
* @copyrights Copyrights (C) 2018 Artur Stępień, all rights reserved.
* @license https://github.com/AssetsCompressor/AssetsCompressor/blob/master/LICENSE MIT
*/
namespace AssetsCompressor;
use Exception;
use MatthiasMullie\Minify\JS as JSProcessor;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Yaml\Yaml;
use tubalmartin\CssMin\Minifier as CSSProcessor;
/**
* Combine and compress static files (CSS/JS) into packages and compress them.
*/
class AssetsCompressor
{
/**
* Library version
*/
const VERSION = '1.0.0';
/**
* Holds library configuration loaded from YAML file
*
* @var array
*/
protected $config = [];
/**
* Configuration file root directory. It will be treated as a root directory
* for all the paths in configuration file.
*
* @var string
*/
protected $path_root = '';
/**
* Where to store hashes json file if versioning is enabled.
*
* @var string
*/
protected $path_hashes = '';
/**
* Entry point hashes.
*
* @var array[string]
*/
protected $hashes = [];
/**
* Should minified files be named using version hash?
*
* @var bool
*/
protected $hashing = true;
/**
* Console command output.
*
* @var OutputInterface
*/
protected $console_output;
/**
* Create compressor instance.
*
* @param string $config_path Absolute configuration file path.
* @param bool $hashing Save minified output files with version tag?
*
* @codeCoverageIgnore
*/
public function __construct(string $config_path = '', bool $hashing = true)
{
// If configuration file was provided
if (!empty($config_path)) {
$this->loadConfigurationFile($config_path);
}
// Should minified files be versioned?
$this->hashing = $hashing;
}
/**
* Load library configuration YAML from file $config_file.
*
* @param string $config_file Absolute configuration file path.
*
* @return self
*
* @codeCoverageIgnore
*/
public function loadConfigurationFile(string $config_file): self
{
// If configuration file doesn't exists, throw exception
if (!file_exists($config_file)) {
throw new Exception("AssetsCompressor configuration file {$config_file} doesn't exists.");
}
// Load configuration and store it as array
$this->path_root = pathinfo($config_file, PATHINFO_DIRNAME);
$this->config = Yaml::parse(file_get_contents($config_file));
return $this;
}
/**
* Creates new entry point.
*
* @param array $output_file Entry point (output file path)
* @param array $patterns File patterns (glob() patterns)
*
* @return self
*
* @codeCoverageIgnore
*/
public function addEntryPoint(array $output_file, array $patterns): self
{
$this->config[$output_file] = $patterns;
return $this;
}
/**
* Change root directory.
*
* If youre using configuration file, configuration directory is used as a root.
* If youre using addEntryPoint() method, set root directory using this method.
*
* @param string $path Absolute file path
*
* @return self
*
* @codeCoverageIgnore
*/
public function setRootDirectory(string $path): self
{
$this->path_root = $path;
return $this;
}
/**
* Set the file path where entry points hashes should be stored.
*
* @param string $path Absolute file path (wg. /busters.json)
*
* @return self
*
* @codeCoverageIgnore
*/
public function setHashesFilePath(string $path): self
{
$this->path_hashes = $path;
return $this;
}
/**
* Should output filenames contain content hash?
*
* @param bool $state Output files hashing state
*
* @return self
*
* @codeCoverageIgnore
*/
public function setHashing(bool $state = true): self
{
$this->hashing = $state;
return $this;
}
/**
* Run assets compressor
*
* @return self
*/
public function run(): self
{
// If there are no files in configuration, throw exception
if (empty($this->config)) {
throw new Exception('No configuration provided, add a configuration file or entry points directly.');
}
// If root directory wasn't provided, throw exception
if (empty($this->path_root)) {
throw new Exception('The root directory wasn\'t provided.');
}
// Process entries
foreach ($this->config AS $path_output => $patterns) {
// Pomiń puste sekcje
if (empty($patterns)) {
continue;
}
// Process single entry point
if (!is_array($patterns)) {
$patterns = [$patterns];
}
$this->processEntry($path_output, $patterns);
}
// If versioning is enabled, store hashes
if ($this->hashing AND ! empty($this->hashes)) {
// If there is no hashes file, place one in root directory
if (empty($this->path_hashes)) {
$this->path_hashes = $this->path_root.'/busters.json';
}
file_put_contents($this->path_hashes, json_encode($this->hashes));
}
return $this;
}
/**
* Bind Symfony/Console command output.
*
* @param OutputInterface $output Command output.
*
* @codeCoverageIgnore
*/
public function bindConsoleOutput(OutputInterface $output)
{
$this->console_output = $output;
}
/**
* Process a single entry in configuration file (end point file).
* Directory format: /assets/vender.js for the absolute path, or assets/vendor.js for relative path
*
* @param string $output_path Entry point file path
* @param array[string] $patterns
*
* @codeCoverageIgnore
*/
protected function processEntry(string $output_path, array $patterns)
{
$this->writeConsole('Processing:'."\t".$output_path);
// Extension (file type)
$ext = strtolower(pathinfo($output_path, PATHINFO_EXTENSION));
// Prepare end point file
$include_list = $this->buildFilesList($patterns);
$buffer = '';
foreach ($include_list AS $file) {
$buffer .= file_get_contents($file).($ext === 'js' ? ';' : '').PHP_EOL;
$this->writeConsole('- '.$file, OutputInterface::VERBOSITY_VERBOSE);
}
// Process the buffer
if (!empty($buffer)) {
// Save uncompressed version
$path_uncompressed = $this->path_root.$output_path;
file_put_contents($path_uncompressed, $buffer);
// Minify file name
$dir = pathinfo($path_uncompressed, PATHINFO_DIRNAME);
$filename = pathinfo($path_uncompressed, PATHINFO_FILENAME);
$path_minified = $dir.'/'.$filename.'.min.';
// If file shuld be versioned, add a hash
if ($this->hashing) {
$hash = hash('crc32b', $buffer);
$path_minified .= $hash.'.';
$this->hashes[$output_path] = $hash;
}
// Add file extension
$path_minified .= $ext;
// Process CSS
if ($ext === 'css') {
// Create compressor instance
$compressor = new CSSProcessor;
$compressor->setLineBreakPosition(1000);
$compressor->setMemoryLimit('256M');
$compressor->setMaxExecutionTime(120);
$compressor->setPcreBacktrackLimit(3000000);
$compressor->setPcreRecursionLimit(150000);
// Compress CSS and save the output
$output_css = $compressor->run($buffer);
file_put_contents($path_minified, $output_css);
$this->writeConsole('Processing:'."\t".$path_minified);
// Process JS
} elseif ($ext === 'js') {
// Compress JS file and save to file
(new JSProcessor($path_uncompressed))->minify($path_minified);
$this->writeConsole('Processing:'."\t".$path_minified);
}
}
$this->writeConsole('', OutputInterface::VERBOSITY_VERBOSE);
}
/**
* Build files lisst from provided patterns.
*
* @param array $patterns Files patterns
*
* @return array
*
* @codeCoverageIgnore
*/
protected function buildFilesList(array $patterns): array
{
$files = [];
$exclude_list = [];
// Process each pattern
foreach ($patterns AS $pattern) {
// If this is the exclude pattern
if (substr($pattern, 0, 1) === '!') {
// Filter only files, then add to exclude list
$path = glob($this->path_root.substr($pattern, 1));
$excludes = array_filter($path, 'is_file');
$exclude_list = array_replace($exclude_list, $excludes);
// If this is the include patern
} else {
// Find files from include pattern
$path = glob($this->path_root.$pattern);
$includes = array_filter($path, 'is_file');
$files = array_replace($files, $includes);
}
}
// Prepare files list and remove duplicates
$files = array_diff($files, $exclude_list);
return $files;
}
/**
* Write message into console command output (used only when application is run from console).
*
* @param string $text Console text to write
* @param int $verbosity Message verbosity level
*
* @codeCoverageIgnore
*/
private function writeConsole(string $text, int $verbosity = OutputInterface::VERBOSITY_NORMAL)
{
if (!is_null($this->console_output)) {
$this->console_output->writeln($text, $verbosity>0 ? $verbosity : null);
}
}
}