forked from skeeks-semenov/yii2-assets-auto-compress
-
Notifications
You must be signed in to change notification settings - Fork 0
/
AssetsAutoCompressComponent.php
645 lines (532 loc) · 18.1 KB
/
AssetsAutoCompressComponent.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
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
<?php
/**
* @author Semenov Alexander <[email protected]>
* @link http://skeeks.com/
* @copyright 2010 SkeekS (СкикС)
* @date 05.08.2015
*/
namespace skeeks\yii2\assetsAuto;
use skeeks\yii2\assetsAuto\components\HtmlCompressor;
use yii\helpers\FileHelper;
use yii\base\BootstrapInterface;
use yii\base\Component;
use yii\base\Event;
use yii\helpers\ArrayHelper;
use yii\helpers\Html;
use yii\helpers\Json;
use yii\helpers\Url;
use yii\web\Application;
use yii\web\JsExpression;
use yii\web\Response;
use yii\web\View;
/**
* Class AssetsAutoCompressComponent
* @package skeeks\yii2\assetsAuto
*/
class AssetsAutoCompressComponent extends Component implements BootstrapInterface
{
/**
* Enable or disable the component
* @var bool
*/
public $enabled = true;
/**
* Time in seconds for reading each asset file
* @var int
*/
public $readFileTimeout = 3;
/**
* Enable minification js in html code
* @var bool
*/
public $jsCompress = true;
/**
* Cut comments during processing js
* @var bool
*/
public $jsCompressFlaggedComments = true;
/**
* Enable minification css in html code
* @var bool
*/
public $cssCompress = true;
public $cssOptions = [];
/**
* Turning association css files
* @var bool
*/
public $cssFileCompile = true;
/**
* Trying to get css files to which the specified path as the remote file, skchat him to her.
* @var bool
*/
public $cssFileRemouteCompile = false;
/**
* Enable compression and processing before being stored in the css file
* @var bool
*/
public $cssFileCompress = true;
/**
* Moving down the page css files
* @var bool
*/
public $cssFileBottom = false;
/**
* Transfer css file down the page and uploading them using js
* @var bool
*/
public $cssFileBottomLoadOnJs = false;
/**
* Turning association js files
* @var bool
*/
public $jsFileCompile = true;
public $jsOptions = [];
/**
* Trying to get a js files to which the specified path as the remote file, skchat him to her.
* @var bool
*/
public $jsFileRemouteCompile = false;
/**
* Enable compression and processing js before saving a file
* @var bool
*/
public $jsFileCompress = true;
/**
* Cut comments during processing js
* @var bool
*/
public $jsFileCompressFlaggedComments = true;
/**
* Enable compression html
* @var bool
*/
public $htmlCompress = true;
/**
* @var array options for compressing output result
* * extra - use more compact algorithm
* * no-comments - cut all the html comments
*/
public $htmlCompressOptions = [
'extra' => false,
'no-comments' => true
];
/**
* Do not connect the js files when all pjax requests.
* @var bool
*/
public $noIncludeJsFilesOnPjax = true;
/**
* @param \yii\base\Application $app
*/
public function bootstrap($app)
{
if ($app instanceof \yii\web\Application)
{
$app->view->on(View::EVENT_END_PAGE, function(Event $e) use ($app)
{
/**
* @var $view View
*/
$view = $e->sender;
if ($this->enabled && $view instanceof View && $app->response->format == Response::FORMAT_HTML && !$app->request->isAjax && !$app->request->isPjax)
{
\Yii::beginProfile('Compress assets');
$this->_processing($view);
\Yii::endProfile('Compress assets');
}
//TODO:: Think about it
if ($this->enabled && $app->request->isPjax && $this->noIncludeJsFilesOnPjax)
{
\Yii::$app->view->jsFiles = null;
}
});
//Html compressing
$app->response->on(\yii\web\Response::EVENT_BEFORE_SEND, function (\yii\base\Event $event) use ($app)
{
$response = $event->sender;
if ($this->enabled && $this->htmlCompress && $response->format == \yii\web\Response::FORMAT_HTML && !$app->request->isAjax && !$app->request->isPjax)
{
if (!empty($response->data))
{
$response->data = $this->_processingHtml($response->data);
}
if (!empty($response->content))
{
$response->content = $this->_processingHtml($response->content);
}
}
});
}
}
/**
* @return string
*/
public function getSettingsHash()
{
return serialize((array) $this);
}
/**
* @param View $view
*/
protected function _processing(View $view)
{
//Компиляция файлов js в один.
if ($view->jsFiles && $this->jsFileCompile)
{
\Yii::beginProfile('Compress js files');
foreach ($view->jsFiles as $pos => $files)
{
if ($files)
{
$view->jsFiles[$pos] = $this->_processingJsFiles($files);
}
}
\Yii::endProfile('Compress js files');
}
//Компиляция js кода который встречается на странице
if ($view->js && $this->jsCompress)
{
\Yii::beginProfile('Compress js code');
foreach ($view->js as $pos => $parts)
{
if ($parts)
{
$view->js[$pos] = $this->_processingJs($parts);
}
}
\Yii::endProfile('Compress js code');
}
//Компиляция css файлов который встречается на странице
if ($view->cssFiles && $this->cssFileCompile)
{
\Yii::beginProfile('Compress css files');
$view->cssFiles = $this->_processingCssFiles($view->cssFiles);
\Yii::endProfile('Compress css files');
}
//Компиляция css файлов который встречается на странице
if ($view->css && $this->cssCompress)
{
\Yii::beginProfile('Compress css code');
$view->css = $this->_processingCss($view->css);
\Yii::endProfile('Compress css code');
}
//Компиляция css файлов который встречается на странице
if ($view->css && $this->cssCompress)
{
\Yii::beginProfile('Compress css code');
$view->css = $this->_processingCss($view->css);
\Yii::endProfile('Compress css code');
}
//Перенос файлов css вниз страницы, где файлы js View::POS_END
if ($view->cssFiles && $this->cssFileBottom)
{
\Yii::beginProfile('Moving css files bottom');
if ($this->cssFileBottomLoadOnJs)
{
\Yii::beginProfile('load css on js');
$cssFilesString = implode("", $view->cssFiles);
$view->cssFiles = [];
$script = Html::script(new JsExpression(<<<JS
document.write('{$cssFilesString}');
JS
));
if (ArrayHelper::getValue($view->jsFiles, View::POS_END))
{
$view->jsFiles[View::POS_END] = ArrayHelper::merge($view->jsFiles[View::POS_END], [$script]);
} else
{
$view->jsFiles[View::POS_END][] = $script;
}
\Yii::endProfile('load css on js');
} else
{
if (ArrayHelper::getValue($view->jsFiles, View::POS_END))
{
$view->jsFiles[View::POS_END] = ArrayHelper::merge($view->cssFiles, $view->jsFiles[View::POS_END]);
} else
{
$view->jsFiles[View::POS_END] = $view->cssFiles;
}
$view->cssFiles = [];
}
\Yii::endProfile('Moving css files bottom');
}
}
/**
* @param $html
* @return string
*/
protected function _processingHtml($html)
{
//$options = ['no-comments' => true];
$options = $this->htmlCompressOptions;
return HtmlCompressor::compress($html, $options);
}
/**
* @param $parts
* @return array
* @throws \Exception
*/
protected function _processingJs($parts)
{
$result = [];
if ($parts)
{
foreach ($parts as $key => $value)
{
$result[$key] = \JShrink\Minifier::minify($value, ['flaggedComments' => $this->jsCompressFlaggedComments]);
}
}
return $result;
}
/**
* @param array $files
* @return array
*/
protected function _processingJsFiles($files = [])
{
$fileName = md5( implode(array_keys($files)) . $this->getSettingsHash()) . '.js';
$publicUrl = \Yii::getAlias('@web/assets/js-compress/' . $fileName);
$rootDir = \Yii::getAlias('@webroot/assets/js-compress');
$rootUrl = $rootDir . '/' . $fileName;
if (file_exists($rootUrl))
{
$resultFiles = [];
foreach ($files as $fileCode => $fileTag)
{
if (!Url::isRelative($fileCode))
{
$resultFiles[$fileCode] = $fileTag;
} else
{
if ($this->jsFileRemouteCompile)
{
$resultFiles[$fileCode] = $fileTag;
}
}
}
$publicUrl = $publicUrl . "?v=" . filemtime($rootUrl);
$resultFiles[$publicUrl] = Html::jsFile($publicUrl, $this->jsOptions);
return $resultFiles;
}
//Reading the contents of the files
try
{
$resultContent = [];
$resultFiles = [];
foreach ($files as $fileCode => $fileTag)
{
if (Url::isRelative($fileCode))
{
$contentFile = $this->fileGetContents( Url::to(\Yii::getAlias($fileCode), true) );
$resultContent[] = trim($contentFile) . "\n;";;
} else
{
if ($this->jsFileRemouteCompile)
{
//Пытаемся скачать удаленный файл
$contentFile = $this->fileGetContents( $fileCode );
$resultContent[] = trim($contentFile);
} else
{
$resultFiles[$fileCode] = $fileTag;
}
}
}
} catch (\Exception $e)
{
\Yii::error($e->getMessage(), static::className());
return $files;
}
if ($resultContent)
{
$content = implode($resultContent, ";\n");
if (!is_dir($rootDir))
{
if (!FileHelper::createDirectory($rootDir, 0777))
{
return $files;
}
}
if ($this->jsFileCompress)
{
$content = \JShrink\Minifier::minify($content, ['flaggedComments' => $this->jsFileCompressFlaggedComments]);
}
$page = \Yii::$app->request->absoluteUrl;
$useFunction = function_exists('curl_init') ? 'curl extension' : 'php file_get_contents';
$filesString = implode(', ', array_keys($files));
\Yii::info("Create js file: {$publicUrl} from files: {$filesString} to use {$useFunction} on page '{$page}'", static::className());
$file = fopen($rootUrl, "w");
fwrite($file, $content);
fclose($file);
}
if (file_exists($rootUrl))
{
$publicUrl = $publicUrl . "?v=" . filemtime($rootUrl);
$resultFiles[$publicUrl] = Html::jsFile($publicUrl, $this->jsOptions);
return $resultFiles;
} else
{
return $files;
}
}
/**
* @param array $files
* @return array
*/
protected function _processingCssFiles($files = [])
{
$fileName = md5( implode(array_keys($files)) . $this->getSettingsHash() ) . '.css';
$publicUrl = \Yii::getAlias('@web/assets/css-compress/' . $fileName);
$rootDir = \Yii::getAlias('@webroot/assets/css-compress');
$rootUrl = $rootDir . '/' . $fileName;
if (file_exists($rootUrl))
{
$resultFiles = [];
foreach ($files as $fileCode => $fileTag)
{
if (Url::isRelative($fileCode))
{
} else
{
if (!$this->cssFileRemouteCompile)
{
$resultFiles[$fileCode] = $fileTag;
}
}
}
$publicUrl = $publicUrl . "?v=" . filemtime($rootUrl);
$resultFiles[$publicUrl] = Html::cssFile($publicUrl, $this->cssOptions);
return $resultFiles;
}
//Reading the contents of the files
try
{
$resultContent = [];
$resultFiles = [];
foreach ($files as $fileCode => $fileTag)
{
if (Url::isRelative($fileCode))
{
$contentTmp = trim($this->fileGetContents( Url::to(\Yii::getAlias($fileCode), true) ));
$fileCodeTmp = explode("/", $fileCode);
unset($fileCodeTmp[count($fileCodeTmp) - 1]);
$prependRelativePath = implode("/", $fileCodeTmp) . "/";
$contentTmp = \Minify_CSS::minify($contentTmp, [
"prependRelativePath" => $prependRelativePath,
'compress' => true,
'removeCharsets' => true,
'preserveComments' => true,
]);
//$contentTmp = \CssMin::minify($contentTmp);
$resultContent[] = $contentTmp;
} else
{
if ($this->cssFileRemouteCompile)
{
//Пытаемся скачать удаленный файл
$resultContent[] = trim($this->fileGetContents( $fileCode ));
} else
{
$resultFiles[$fileCode] = $fileTag;
}
}
}
} catch (\Exception $e)
{
\Yii::error($e->getMessage(), static::className());
return $files;
}
if ($resultContent)
{
$content = implode($resultContent, "\n");
if (!is_dir($rootDir))
{
if (!FileHelper::createDirectory($rootDir, 0777))
{
return $files;
}
}
if ($this->cssFileCompress)
{
$content = \CssMin::minify($content);
}
$page = \Yii::$app->request->absoluteUrl;
$useFunction = function_exists('curl_init') ? 'curl extension' : 'php file_get_contents';
$filesString = implode(', ', array_keys($files));
\Yii::info("Create css file: {$publicUrl} from files: {$filesString} to use {$useFunction} on page '{$page}'", static::className());
$file = fopen($rootUrl, "w");
fwrite($file, $content);
fclose($file);
}
if (file_exists($rootUrl))
{
$publicUrl = $publicUrl . "?v=" . filemtime($rootUrl);
$resultFiles[$publicUrl] = Html::cssFile($publicUrl, $this->cssOptions);
return $resultFiles;
} else
{
return $files;
}
}
/**
* @param array $css
* @return array
*/
protected function _processingCss($css = [])
{
$newCss = [];
foreach ($css as $code => $value)
{
$newCss[] = preg_replace_callback('/<style\b[^>]*>(.*)<\/style>/is', function($match)
{
return $match[1];
}, $value);
}
$css = implode($newCss, "\n");
$css = \CssMin::minify($css);
return [md5($css) => "<style>" . $css . "</style>"];
}
/**
* Read file contents
*
* @param $file
* @return string
*/
public function fileGetContents($file)
{
if (function_exists('curl_init'))
{
$url = $file;
$ch = curl_init();
$timeout = (int) $this->readFileTimeout;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$result = curl_exec($ch);
if ($result === false)
{
$errorMessage = curl_error($ch);
curl_close($ch);
throw new \Exception($errorMessage);
}
$info = curl_getinfo($ch);
if (ArrayHelper::getValue($info, 'http_code') == 404)
{
curl_close($ch);
throw new \Exception("File not found: {$file}");
}
curl_close($ch);
return $result;
} else
{
$ctx = stream_context_create(array('http'=>
array(
'timeout' => (int) $this->readFileTimeout, //3 Seconds
)
));
return file_get_contents($file, false, $ctx);
}
}
}