View::compress()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 21
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 21
rs 9.3142
c 0
b 0
f 0
cc 1
eloc 10
nc 1
nop 1
1
<?php
2
3
namespace ogheo\htmlcompress;
4
5
/**
6
 * Class View
7
 * @package ogheo\htmlcompress
8
 */
9
class View extends \yii\web\View
10
{
11
    /**
12
     * Enable or disable compression, by default compression is enabled.
13
     *
14
     * @var bool
15
     */
16
    public $compress = true;
17
18
    /**
19
     * @inheritdoc
20
     */
21
    public function init()
22
    {
23
        parent::init();
24
25
        if ($this->compress === true) {
26
            \Yii::$app->response->on(\yii\web\Response::EVENT_BEFORE_SEND, function (\yii\base\Event $Event) {
27
                $Response = $Event->sender;
28
                if ($Response->format === \yii\web\Response::FORMAT_HTML) {
29
                    if (!empty($Response->data)) {
30
                        $Response->data = self::compress($Response->data);
31
                    }
32
                    if (!empty($Response->content)) {
33
                        $Response->content = self::compress($Response->content);
34
                    }
35
                }
36
            });
37
        }
38
    }
39
40
    /**
41
     * HTML compress function.
42
     *
43
     * @param $html
44
     * @return mixed
45
     */
46
    public static function compress($html)
47
    {
48
        $filters = array(
49
            // remove javascript comments
50
            '/(?:<script[^>]*>|\G(?!\A))(?:[^\'"\/<]+|"(?:[^\\"]+|\\.)*"|\'(?:[^\\\']+|\\.)*\'|\/(?!\/)|<(?!\/script))*+\K\/\/[^\n|<]*/xsu' => '',
51
            // remove html comments except IE conditions
52
            '/<!--(?!\s*(?:\[if [^\]]+]|<!|>))(?:(?!-->).)*-->/su' => '',
53
            // remove comments in the form /* */
54
            '/\/+?\s*\*[\s\S]*?\*\s*\/+/u' => '',
55
            // shorten multiple white spaces
56
            '/>\s{2,}</u' => '><',
57
            // shorten multiple white spaces
58
            '/\s{2,}/u' => ' ',
59
            // collapse new lines
60
            '/(\r?\n)/u' => '',
61
        );
62
63
        $output = preg_replace(array_keys($filters), array_values($filters), $html);
64
65
        return $output;
66
    }
67
}
68