/
View.php
184 lines (161 loc) · 5.67 KB
/
View.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
<?php
namespace slinstj\AssetsOptimizer;
use MatthiasMullie\Minify;
use yii\helpers\FileHelper;
use yii\helpers\Html;
/**
* A modified View class capable of optimizing (minify and combine) assets bundles.
* @author Sidney Lins (slinstj@gmail.com)
*/
class View extends \yii\web\View
{
/** @var bool */
public $minify = true;
/** @var bool */
public $combine = true;
/**
* @var string Path where optimized files will be published in. If you change this,
* you *must* change [[publishUrl]] accordingly.
* Optional. Defaults to '@webroot/yao'.
*/
public $publishPath = '@webroot/yao';
/**
* @var string Web acessible Url where optimized files will be published in.
* *Must* be in according to [[publishPath]].
* Optional. Defaults to '@web/yao'.
*/
public $publishUrl = '@web/yao';
protected $filesToMinify;
public function init()
{
parent::init();
$this->publishPath = \Yii::getAlias($this->publishPath);
$this->publishUrl = \Yii::getAlias($this->publishUrl);
}
/**
* @inheritdoc
*/
public function endPage($ajaxMode = false)
{
$this->trigger(self::EVENT_END_PAGE);
$content = ob_get_clean();
if ($this->minify === true && !\Yii::$app->request->isAjax) {
$this->resolveAllAssetPaths();
$this->optimizeCss();
$this->optimizeJs();
}
echo strtr(
$content,
[
self::PH_HEAD => $this->renderHeadHtml(),
self::PH_BODY_BEGIN => $this->renderBodyBeginHtml(),
self::PH_BODY_END => $this->renderBodyEndHtml($ajaxMode),
]
);
$this->clear();
}
/**
* @return self
*/
protected function resolveAllAssetPaths()
{
foreach (array_keys($this->cssFiles) as $filePath) {
if (!$this->isExternalSchema($filePath)) {
$resolvedPath = $this->resolvePath($filePath);
$this->filesToMinify['css'][] = $resolvedPath;
unset($this->cssFiles[$filePath]);
}
}
foreach ($this->jsFiles as $position => $files) {
foreach (array_keys($files) as $filePath) {
if (!$this->isExternalSchema($filePath)) {
$resolvedPath = $this->resolvePath($filePath);
$this->filesToMinify['js'][$position][] = $resolvedPath;
unset($this->jsFiles[$position][$filePath]);
}
}
}
}
protected function optimizeCss()
{
if (($cache = $this->getAppCache())) {
if (!($result = $cache->get('cssResult'))) {
$cache->set('cssResult', ($result = $this->minifyFiles($this->filesToMinify['css'], 'css')));
}
} else {
$result = $this->minifyFiles($this->filesToMinify['css'], 'css');
}
$this->saveOptimizedCssFile($result);
}
protected function optimizeJs()
{
foreach ($this->filesToMinify['js'] as $jsPosition => $files) {
if (($cache = $this->getAppCache())) {
if (!($result = $cache->get('jsResult' . $jsPosition))) {
$cache->set('jsResult' . $jsPosition, ($result = $this->minifyFiles($files, 'js')));
}
} else {
$result = $this->minifyFiles($files, 'js');
}
$this->saveOptimizedJsFile($result, $jsPosition);
}
}
protected function minifyFiles($fileUrls, $type)
{
$min = ($type = strtolower($type)) === 'css' ? new Minify\CSS() : new Minify\JS;
foreach ($fileUrls as $resolvedPath) {
$min->add($resolvedPath);
}
return $min->minify();
}
protected function isExternalSchema($path)
{
$schemas = ['http://', 'https://', 'ftp://', '//'];
$mainRegex = '((' . implode('|', $schemas) . ').*?)';
preg_match($mainRegex, $path, $matches);
return isset($matches[1]);
}
protected function resolvePath($path)
{
$webroot = \Yii::getAlias('@webroot');
$web = str_replace(\Yii::getAlias('@web'), '', $path);
return realpath(FileHelper::normalizePath($webroot . DIRECTORY_SEPARATOR . $web));
}
protected function saveOptimizedCssFile($content)
{
$finalPath = $this->saveFile($content, $this->publishPath, 'css');
$finalUrl = $this->publishUrl . DIRECTORY_SEPARATOR . basename($finalPath);
$this->cssFiles[$finalPath] = Html::cssFile($finalUrl);
}
protected function saveOptimizedJsFile($content, $jsPosition)
{
$finalPath = $this->saveFile($content, $this->publishPath, 'js');
$finalUrl = $this->publishUrl . DIRECTORY_SEPARATOR . basename($finalPath);
$this->jsFiles[$jsPosition][$finalPath] = Html::jsFile($finalUrl);
}
protected function saveFile($content, $filePath, $ext)
{
$filename = substr(sha1($content), 0, 15) . '.yao.' . $ext;
FileHelper::createDirectory($filePath);
$finalPath = $filePath . DIRECTORY_SEPARATOR . $filename;
if (is_file($finalPath) && filesize($finalPath)) {
return $finalPath;
}
if (file_put_contents($finalPath, $content, LOCK_EX) !== false) {
return $finalPath;
} else {
throw new \Exception("It was not possible to save the file '$finalPath'.");
}
}
protected function isCacheEnabled()
{
return isset(\Yii::$app->cache);
}
/**
* @return \yii\caching\Cache;
*/
protected function getAppCache()
{
return $this->isCacheEnabled() ? \Yii::$app->cache : null;
}
}