Completed
Push — master ( 73fd8c...52e26d )
by Rougin
01:31
created

InlineMinifier   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 94
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Importance

Changes 0
Metric Value
wmc 8
lcom 1
cbo 0
dl 0
loc 94
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 2
A filter() 0 20 3
A elements() 0 16 2
A minify() 0 20 1
1
<?php
2
3
namespace Staticka\Filter;
4
5
/**
6
 * Inline Minifier
7
 *
8
 * @package Staticka
9
 * @author  Rougin Royce Gutib <[email protected]>
10
 */
11
class InlineMinifier implements FilterInterface
12
{
13
    /**
14
     * @var string
15
     */
16
    protected $tagname = '';
17
18
    /**
19
     * Initializes the filter instance.
20
     *
21
     * @param string $tagname
22
     */
23
    public function __construct($tagname = '')
24
    {
25
        $tagname !== '' && $this->tagname = $tagname;
26
    }
27
28
    /**
29
     * Filters the specified code.
30
     *
31
     * @param  string $code
32
     * @return string
33
     */
34
    public function filter($code)
35
    {
36
        $elements = (array) $this->elements($code);
37
38
        if (count($elements) === 0) {
39
            $code = trim(preg_replace('/\s\s+/', '', $code));
40
41
            return (string) ltrim($this->minify($code));
42
        }
43
44
        foreach ((array) $elements as $element) {
45
            $original = (string) $element->nodeValue;
46
47
            $minified = $this->minify($original);
48
49
            $code = str_replace($original, $minified, $code);
50
        }
51
52
        return $code;
53
    }
54
55
    /**
56
     * Returns elements by a tag name.
57
     *
58
     * @param  string $code
59
     * @return \DOMNodeList
60
     */
61
    protected function elements($code)
62
    {
63
        libxml_use_internal_errors(true);
64
65
        $doc = new \DOMDocument;
66
67
        $doc->loadHTML((string) $code);
68
69
        $tag = (string) $this->tagname;
70
71
        $items = $doc->getElementsByTagName($tag);
72
73
        $items = iterator_to_array($items);
74
75
        return count($items) > 0 ? $items : array();
76
    }
77
78
    /**
79
     * Minifies the specified code.
80
     *
81
     * @param  string $code
82
     * @return string
83
     */
84
    protected function minify($code)
85
    {
86
        $pattern = (string) '!/\*[^*]*\*+([^/][^*]*\*+)*/!';
87
88
        $minified = preg_replace('/^\\s+/m', '', $code);
89
90
        $minified = preg_replace($pattern, '', $minified);
91
92
        $minified = preg_replace('/( )?}( )?/', '}', $minified);
93
94
        $minified = preg_replace('/( )?{( )?/', '{', $minified);
95
96
        $minified = preg_replace('/( )?:( )?/', ':', $minified);
97
98
        $minified = preg_replace('/( )?;( )?/', ';', $minified);
99
100
        $minified = preg_replace('/( )?,( )?/', ',', $minified);
101
102
        return $minified;
103
    }
104
}
105