This repository has been archived by the owner on Jan 30, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
MinifyManager.php
80 lines (66 loc) · 1.87 KB
/
MinifyManager.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
<?php
namespace maybeworks\minify;
use yii\base\Component;
use yii\base\Event;
use yii\web\Response;
use yii\web\View;
use maybeworks\minify\MinifyHelper;
class MinifyManager extends Component
{
/**
* Minify html. Process before response send
* @var bool
*/
public $html = true;
/**
* Minify css on page, added by registerCss. Process before render page in view component
* @var bool
*/
public $css = true;
/**
* Minify css on page. Process before render page in view component
* @var bool
*/
public $js = true;
/**
* Response formats list, where enable minify html
* @var array
*/
public $formats = [
Response::FORMAT_HTML
];
public function init()
{
/** @var $this View */
\Yii::$app->view->on(View::EVENT_END_PAGE, [$this, 'onEventEndPage']);
\Yii::$app->response->on(Response::EVENT_BEFORE_SEND, [$this, 'onEventBeforeSend']);
}
public function onEventEndPage(Event $event)
{
$view = $event->sender;
if ($this->css && !empty($view->css)) {
foreach ($view->css as &$css) {
$css = MinifyHelper::css($css);
}
}
if ($this->js && !empty($view->js)) {
foreach ($view->js as &$list) {
foreach ($list as &$js) {
$js = MinifyHelper::js($js);
}
}
}
}
public function onEventBeforeSend(Event $event)
{
$response = $event->sender;
if ($this->html & in_array($response->format, $this->formats)) {
if (!empty($response->data)) {
$response->data = MinifyHelper::html($response->data);
}
if (!empty($response->content)) {
$response->content = MinifyHelper::html($response->content);
}
}
}
}