Test Setup Failed
Push — master ( 4545e6...c58229 )
by Revin
01:43
created

View::compressOutput()   A

Complexity

Conditions 4
Paths 5

Size

Total Lines 17

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 1
CRAP Score 4

Importance

Changes 0
Metric Value
dl 0
loc 17
ccs 1
cts 1
cp 1
rs 9.7
c 0
b 0
f 0
cc 4
nc 5
nop 1
crap 4
1
<?php
2
/**
3
 * View.php
4
 * @author Revin Roman
5
 * @link https://rmrevin.ru
6
 */
7
8
namespace rmrevin\yii\minify;
9
10
use yii\base\Event;
11
use yii\helpers\FileHelper;
12
use yii\web\AssetBundle;
13
use yii\web\Response;
14
15
/**
16
 * Class View
17
 * @package rmrevin\yii\minify
18
 */
19
class View extends \yii\web\View
20
{
21
22
    /**
23
     * @var bool
24
     */
25
    public $enableMinify = true;
26
27
    /**
28
     * @var string filemtime or sha1
29
     */
30
    public $fileCheckAlgorithm = 'hash';
31
32
    /**
33
     * @var bool
34
     */
35
    public $concatCss = true;
36
37
    /**
38
     * @var bool
39
     */
40
    public $minifyCss = true;
41
42
    /**
43
     * @var array
44
     */
45
    public $cssOptions = [];
46
47
    /**
48
     * @var bool
49
     */
50
    public $concatJs = true;
51
52
    /**
53
     * @var bool
54
     */
55
    public $minifyJs = true;
56
57
    /**
58
     * @var bool
59
     */
60
    public $minifyOutput = false;
61
62
    /**
63
     * @var string path alias to web base (in url)
64
     */
65
    public $webPath = '@web';
66
67
    /**
68
     * @var string path alias to web base (absolute)
69
     */
70
    public $basePath = '@webroot';
71
72
    /**
73
     * @var string path alias to save minify result
74
     */
75
    public $minifyPath = '@webroot/minify';
76
77
    /**
78
     * @var array positions of js files to be minified
79
     */
80
    public $jsPosition = [self::POS_END, self::POS_HEAD];
81
82
    /**
83
     * @var array options of minified js files
84
     */
85
    public $jsOptions = [];
86
87
    /**
88
     * @var bool|string charset forcibly assign, otherwise will use all of the files found charset
89
     */
90
    public $forceCharset = false;
91
92
    /**
93
     * @var bool whether to change @import on content
94
     */
95
    public $expandImports = true;
96
97
    /**
98
     * @var int|bool chmod of minified file. If false chmod not set
99
     */
100
    public $fileMode = 0664;
101
102
    /**
103
     * @var array schemes that will be ignored during normalization url
104
     */
105
    public $schemas = ['//', 'http://', 'https://', 'ftp://'];
106
107
    /**
108
     * @var array options for compressing output result
109
     *
110
     * 'cssMinifier' : (optional) callback function to process content of STYLE
111
     * elements.
112
     *
113
     * 'jsMinifier' : (optional) callback function to process content of SCRIPT
114
     * elements. Note: the type attribute is ignored.
115
     *
116
     * 'xhtml' : (optional boolean) should content be treated as XHTML1.0? If
117
     * unset, minify will sniff for an XHTML doctype.
118
     */
119
    public $compressOptions = [];
120
121
    /**
122
     * @var array
123
     */
124
    public $excludeBundles = [];
125
126
    /**
127
     * @var array
128
     */
129
    public $excludeFiles = [];
130
131
    /**
132
     * @var array
133
     */
134
    public $hashAlgos = ['md5', 'tiger160,3', 'sha1', 'tiger192,4'];
135
136
    /**
137
     * @var null|string
138
     */
139
    public $currentHashAlgo;
140
141
    /**
142
     * @var \yii\caching\CacheInterface|string|null
143
     */
144
    public $cache;
145
146
    /**
147 11
     * @throws \rmrevin\yii\minify\Exception
148
     * @throws \yii\base\InvalidConfigException
149 11
     * @throws \yii\base\InvalidParamException
150
     * @throws \yii\base\Exception
151 11
     */
152 11
    public function init()
153 11
    {
154
        parent::init();
155 11
156 11
        $this->basePath = \Yii::getAlias($this->basePath);
0 ignored issues
show
Documentation Bug introduced by
It seems like \Yii::getAlias($this->basePath) can also be of type boolean. However, the property $basePath is declared as type string. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
157 11
        $this->webPath = \Yii::getAlias($this->webPath);
0 ignored issues
show
Documentation Bug introduced by
It seems like \Yii::getAlias($this->webPath) can also be of type boolean. However, the property $webPath is declared as type string. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
158
        $this->minifyPath = \Yii::getAlias($this->minifyPath);
0 ignored issues
show
Documentation Bug introduced by
It seems like \Yii::getAlias($this->minifyPath) can also be of type boolean. However, the property $minifyPath is declared as type string. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
159 11
160 1
        if (null !== $this->cache && is_string($this->cache)) {
161
            $this->cache = \Yii::$app->get($this->cache);
162
        }
163
164
        foreach ($this->excludeBundles as $bundleClass) {
165 1
            if (!class_exists($bundleClass)) {
166
                continue;
167 1
            }
168 1
169 1
            /** @var AssetBundle $Bundle */
170
            $Bundle = new $bundleClass;
171 1
172 1
            if (!empty($Bundle->css)) {
173 1
                $this->excludeFiles = array_merge($this->excludeFiles, $Bundle->css);
174 11
            }
175
176 11
            if (!empty($Bundle->js)) {
177
                $this->excludeFiles = array_merge($this->excludeFiles, $Bundle->js);
178 11
            }
179 11
        }
180
181
        $hashAlgos = hash_algos();
182
183 11
        foreach ($this->hashAlgos as $alog) {
184 11
            if (!in_array($alog, $hashAlgos, true)) {
185 11
                continue;
186
            }
187 11
188
            $this->currentHashAlgo = $alog;
189
            break;
190
        }
191 11
192
        if (null === $this->currentHashAlgo) {
193 11
            throw new Exception('Unable to determine the hash algorithm.');
194 11
        }
195 11
196
        $minifyPath = $this->minifyPath;
197 11
198
        if (!file_exists($minifyPath)) {
199
            FileHelper::createDirectory($minifyPath);
0 ignored issues
show
Bug introduced by
It seems like $minifyPath defined by $this->minifyPath on line 196 can also be of type boolean; however, yii\helpers\BaseFileHelper::createDirectory() does only seem to accept string, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
200
        }
201 11
202
        if (!is_readable($minifyPath)) {
203
            throw new Exception('Directory for compressed assets is not readable.');
204
        }
205 11
206
        if (!is_writable($minifyPath)) {
207
            throw new Exception('Directory for compressed assets is not writable.');
208 11
        }
209
210
        if (true === $this->enableMinify && true === $this->minifyOutput) {
211
            \Yii::$app->response->on(Response::EVENT_BEFORE_SEND, [$this, 'compressOutput']);
212
        }
213
    }
214
215
    /**
216
     * @param \yii\base\Event $event
217
     * @codeCoverageIgnore
218
     */
219
    public function compressOutput(Event $event)
220
    {
221
        /** @var Response $Response */
222
        $Response = $event->sender;
223
224
        if (Response::FORMAT_HTML !== $Response->format) {
225
            return;
226
        }
227
228
        if (!empty($Response->data)) {
229
            $Response->data = \Minify_HTML::minify($Response->data, $this->compressOptions);
230
        }
231
232
        if (!empty($Response->content)) {
233
            $Response->content = \Minify_HTML::minify($Response->content, $this->compressOptions);
234
        }
235 9
    }
236
237 9
    /**
238
     * @inheritdoc
239 9
     */
240
    public function endBody()
241 9
    {
242 9
        $this->trigger(self::EVENT_END_BODY);
243 9
244
        echo self::PH_BODY_END;
245 9
246 9
        foreach (array_keys($this->assetBundles) as $bundle) {
247 9
            $this->registerAssetFiles($bundle);
248 9
        }
249 9
250
        if (true === $this->enableMinify) {
251
            (new components\CSS($this))->export();
252
            (new components\JS($this))->export();
253
        }
254
    }
255
}
256