Passed
Push — master ( e66282...39a592 )
by Dāvis
02:46
created

BeautifyExtension::getAssetVersion()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 14
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 8
nc 4
nop 1
dl 0
loc 14
rs 9.2
c 0
b 0
f 0
1
<?php
2
3
namespace Sludio\HelperBundle\Script\Twig;
4
5
class BeautifyExtension extends \Twig_Extension
6
{
7
    use TwigTrait;
8
9
    const INFO = 'info';
10
    const SUCCESS = 'success';
11
    const REDIRECT = 'redirect';
12
    const CLIENT = 'client_error';
13
    const SERVER = 'server_error';
14
15
    protected $appDir;
16
    private $paths = [];
17
18
    public function __construct($shortFunctions)
19
    {
20
        global $kernel;
21
22
        $this->shortFunctions = $shortFunctions;
23
        $this->appDir = $kernel->getRootDir();
24
    }
25
26
    public function getName()
27
    {
28
        return 'sludio_helper.twig.beautify_extension';
29
    }
30
31
    public function getFilters()
32
    {
33
        $input = [
34
            'beautify' => 'beautify',
35
            'urldecode' => 'url_decode',
36
            'parse' => 'parse',
37
            'file_exists' => 'file_exists',
38
            'html_entity_decode' => 'html_entity_decode',
39
            'strip_descr' => 'strip_descr',
40
            'pretty_print' => 'prettyPrint',
41
            'status_code_class' => 'statusCodeClass',
42
            'format_duration' => 'formatDuration',
43
            'short_uri' => 'shorthenUri',
44
            'is_ie' => 'isIE',
45
            'asset_version' => 'getAssetVersion',
46
            'usort' => 'usortFunction',
47
        ];
48
49
        return $this->makeArray($input);
50
    }
51
52
    public function getFunctions()
53
    {
54
        $input = [
55
            'detect_lang' => 'detectLang',
56
        ];
57
58
        return $this->makeArray($input, 'function');
59
    }
60
61
    public function url_decode($string)
62
    {
63
        return urldecode($string);
64
    }
65
66
    public function parse($string)
67
    {
68
        $str = parse_url($string);
69
70
        $argv = [];
71
        if (isset($str['query'])) {
72
            $args = explode('&', $str['query']);
73
74
            foreach ($args as $arg) {
75
                $tmp = explode('=', $arg, 2);
76
                $argv[$tmp[0]] = $tmp[1];
77
            }
78
        }
79
80
        return $argv;
81
    }
82
83
    public function file_exists($file)
84
    {
85
        return file_exists(getcwd().$file);
86
    }
87
88
    public function beautify($string)
89
    {
90
        $explode = explode('/', strip_tags($string));
91
        $string = implode(' / ', $explode);
92
93
        return $string;
94
    }
95
96
    public function html_entity_decode($str)
97
    {
98
        $str = html_entity_decode($str);
99
        $str = preg_replace('#\R+#', '', $str);
100
101
        return $str;
102
    }
103
104
    public function strip_descr($body, $fallback = null, $type = null, $lengthIn = 300)
105
    {
106
        if ($type && $fallback) {
107
            $length = isset($fallback[$type]) ? $fallback[$type] : null;
108
        }
109
        if (!isset($length)) {
110
            $length = $lengthIn;
111
        }
112
113
        if (strlen($body) > $length) {
114
            $body = substr($body, 0, strpos($body, ' ', $length)).'...';
115
        }
116
117
        return $body;
118
    }
119
120
    public function detectLang($body)
121
    {
122
        switch (true) {
123
            case 0 === strpos($body, '<?xml'):
124
                return 'xml';
125
            case 0 === strpos($body, '{'):
126
            case 0 === strpos($body, '['):
127
                return 'json';
128
            default:
129
                return 'markup';
130
        }
131
    }
132
133
    public function prettyPrint($code, $lang)
134
    {
135
        switch ($lang) {
136
            case 'json':
137
                return json_encode(json_decode($code), JSON_PRETTY_PRINT);
138
            case 'xml':
139
                $xml = new \DomDocument('1.0');
140
                $xml->preserveWhiteSpace = false;
141
                $xml->formatOutput = true;
142
                $xml->loadXml($code);
143
144
                return $xml->saveXml();
145
            default:
146
                return $code;
147
        }
148
    }
149
150
    public function statusCodeClass($statusCode)
151
    {
152
        $codes = [
153
            5 => self::SERVER,
154
            4 => self::CLIENT,
155
            3 => self::REDIRECT,
156
            2 => self::SUCCESS,
157
            1 => self::INFO,
158
        ];
159
        $code = (int)floor(intval($statusCode) / 100);
160
161
        return isset($codes[$code]) ? $codes[$code] : 'unknown';
162
    }
163
164
    public function formatDuration($seconds)
165
    {
166
        $formats = [
167
            '%.2f s',
168
            '%d ms',
169
            '%d µs',
170
        ];
171
172
        while ($format = array_shift($formats)) {
173
            if ($seconds > 1) {
174
                break;
175
            }
176
177
            $seconds *= 1000;
178
        }
179
180
        return sprintf($format, $seconds);
181
    }
182
183
    public function shortenUri($uri)
184
    {
185
        $parts = parse_url($uri);
186
187
        return sprintf('%s://%s%s', isset($parts['scheme']) ? $parts['scheme'] : 'http', $parts['host'], isset($parts['port']) ? (':'.$parts['port']) : '');
188
    }
189
190
    public function isIE()
191
    {
192
        $request = Request::createFromGlobals();
0 ignored issues
show
Bug introduced by
The type Sludio\HelperBundle\Script\Twig\Request was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
193
        $agent = $request->server->get('HTTP_USER_AGENT');
194
        if (strpos($agent, 'MSIE') || strpos($agent, 'Edge') || strpos($agent, 'Trident/7')) {
195
            return 1;
196
        }
197
198
        return 0;
199
    }
200
201
    public function getAssetVersion($filename)
202
    {
203
        if (count($this->paths) === 0) {
204
            $manifestPath = $this->appDir.'/Resources/assets/rev-manifest.json';
205
            if (!file_exists($manifestPath)) {
206
                return $filename;
207
            }
208
            $this->paths = json_decode(file_get_contents($manifestPath), true);
209
            if (!isset($this->paths[$filename])) {
210
                return $filename;
211
            }
212
        }
213
214
        return $this->paths[$filename];
215
    }
216
217
    public function cmpOrderBy($aVar, $bVar)
218
    {
219
        $aValue = $aVar->{'get'.ucfirst($this->param)}();
220
        $bValue = $bVar->{'get'.ucfirst($this->param)}();
221
        switch ($this->order) {
222
            case 'asc':
223
                return $aValue > $bValue;
224
            case 'desc':
225
                return $aValue < $bValue;
226
        }
227
    }
228
229
    public function usortFunction($objects, $parameter, $order = 'asc')
230
    {
231
        $this->param = $parameter;
0 ignored issues
show
Bug Best Practice introduced by
The property param does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
232
        $this->order = strtolower($order);
0 ignored issues
show
Bug Best Practice introduced by
The property order does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
233
234
        if (is_object($objects)) {
235
            $objects = $objects->toArray();
236
        }
237
        usort($objects, [
238
            __CLASS__,
239
            'cmpOrderBy',
240
        ]);
241
242
        return $objects;
243
    }
244
}
245