Passed
Push — master ( 55c7d5...aed71d )
by Dāvis
03:01
created

SludioExtension::__call()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 4
nc 1
nop 2
dl 0
loc 6
rs 9.4285
c 0
b 0
f 0
1
<?php
2
3
namespace Sludio\HelperBundle\Script\Twig;
4
5
use Symfony\Component\HttpFoundation\Request;
6
use Sludio\HelperBundle\Script\Utils\Helper;
7
8
class SludioExtension extends \Twig_Extension
9
{
10
    use TwigTrait;
11
12
    const INFO = 'info';
13
    const SUCCESS = 'success';
14
    const REDIRECT = 'redirect';
15
    const CLIENT = 'client_error';
16
    const SERVER = 'server_error';
17
18
    protected $appDir;
19
    private $paths = [];
20
    protected $param;
21
    protected $order;
22
    protected $detector;
23
24
    public function __construct($shortFunctions)
25
    {
26
        global $kernel;
27
28
        $this->shortFunctions = $shortFunctions;
29
        $this->appDir = $kernel->getRootDir();
30
        $this->detector = new \Mobile_Detect();
31
    }
32
33
    public function getName()
34
    {
35
        return 'sludio_helper.twig.extension';
36
    }
37
38
    public function getFilters()
39
    {
40
        $input = [
41
            'beautify' => 'beautify',
42
            'urldecode' => 'url_decode',
43
            'parse' => 'parse',
44
            'file_exists' => 'file_exists',
45
            'html_entity_decode' => 'html_entity_decode',
46
            'strip_descr' => 'strip_descr',
47
            'pretty_print' => 'prettyPrint',
48
            'status_code_class' => 'statusCodeClass',
49
            'format_duration' => 'formatDuration',
50
            'short_uri' => 'shorthenUri',
51
            'is_ie' => 'isIE',
52
            'asset_version' => 'getAssetVersion',
53
            'usort' => 'usortFunction',
54
        ];
55
56
        return $this->makeArray($input);
57
    }
58
59
    public function getFunctions()
60
    {
61
        $input = [
62
            'detect_lang' => 'detectLang',
63
            'get_available_devices' => 'getAvailableDevices',
64
            'is_mobile' => 'isMobile',
65
            'is_tablet' => 'isTablet',
66
        ];
67
        foreach ($this->getAvailableDevices() as $device => $fixed) {
68
            $input['is_'.$fixed] = 'is'.$device;
69
        }
70
71
        return $this->makeArray($input, 'function');
72
    }
73
74
    public function getAvailableDevices()
75
    {
76
        $availableDevices = [];
77
        $phones = $this->detector->getPhoneDevices();
78
        $tablets = $this->detector->getTabletDevices();
79
        $rules = array_keys(array_change_key_case(array_merge($phones, $tablets)));
80
81
        foreach ($rules as $device) {
82
            $availableDevices[$device] = Helper::fromCamelCase($device);
83
        }
84
85
        return $availableDevices;
86
    }
87
88
    public function __call($name, $arguments)
89
    {
90
        return call_user_func_array([
91
            $this->detector,
92
            $name,
93
        ], $arguments);
94
    }
95
96
    public function url_decode($string)
97
    {
98
        return urldecode($string);
99
    }
100
101
    public function parse($string)
102
    {
103
        $str = parse_url($string);
104
105
        $argv = [];
106
        if (isset($str['query'])) {
107
            $args = explode('&', $str['query']);
108
109
            foreach ($args as $arg) {
110
                $tmp = explode('=', $arg, 2);
111
                $argv[$tmp[0]] = $tmp[1];
112
            }
113
        }
114
115
        return $argv;
116
    }
117
118
    public function file_exists($file)
119
    {
120
        return file_exists(getcwd().$file);
121
    }
122
123
    public function beautify($string)
124
    {
125
        $explode = explode('/', strip_tags($string));
126
        $string = implode(' / ', $explode);
127
128
        return $string;
129
    }
130
131
    public function html_entity_decode($str)
132
    {
133
        $str = html_entity_decode($str);
134
        $str = preg_replace('#\R+#', '', $str);
135
136
        return $str;
137
    }
138
139
    public function strip_descr($body, $fallback = null, $type = null, $lengthIn = 300)
140
    {
141
        if ($type && $fallback) {
142
            $length = isset($fallback[$type]) ? $fallback[$type] : null;
143
        }
144
        if (!isset($length)) {
145
            $length = $lengthIn;
146
        }
147
148
        if (strlen($body) > $length) {
149
            $body = substr($body, 0, strpos($body, ' ', $length)).'...';
150
        }
151
152
        return $body;
153
    }
154
155
    public function detectLang($body)
156
    {
157
        switch (true) {
158
            case 0 === strpos($body, '<?xml'):
159
                return 'xml';
160
            case 0 === strpos($body, '{'):
161
            case 0 === strpos($body, '['):
162
                return 'json';
163
            default:
164
                return 'markup';
165
        }
166
    }
167
168
    public function prettyPrint($code, $lang)
169
    {
170
        switch ($lang) {
171
            case 'json':
172
                return json_encode(json_decode($code), JSON_PRETTY_PRINT);
173
            case 'xml':
174
                $xml = new \DomDocument('1.0');
175
                $xml->preserveWhiteSpace = false;
176
                $xml->formatOutput = true;
177
                $xml->loadXml($code);
178
179
                return $xml->saveXml();
180
            default:
181
                return $code;
182
        }
183
    }
184
185
    public function statusCodeClass($statusCode)
186
    {
187
        $codes = [
188
            5 => self::SERVER,
189
            4 => self::CLIENT,
190
            3 => self::REDIRECT,
191
            2 => self::SUCCESS,
192
            1 => self::INFO,
193
        ];
194
        $code = (int)floor(intval($statusCode) / 100);
195
196
        return isset($codes[$code]) ? $codes[$code] : 'unknown';
197
    }
198
199
    public function formatDuration($seconds)
200
    {
201
        $formats = [
202
            '%.2f s',
203
            '%d ms',
204
            '%d µs',
205
        ];
206
207
        while ($format = array_shift($formats)) {
208
            if ($seconds > 1) {
209
                break;
210
            }
211
212
            $seconds *= 1000;
213
        }
214
215
        return sprintf($format, $seconds);
216
    }
217
218
    public function shortenUri($uri)
219
    {
220
        $parts = parse_url($uri);
221
222
        return sprintf('%s://%s%s', isset($parts['scheme']) ? $parts['scheme'] : 'http', $parts['host'], isset($parts['port']) ? (':'.$parts['port']) : '');
223
    }
224
225
    public function isIE()
226
    {
227
        $request = Request::createFromGlobals();
228
        $agent = $request->server->get('HTTP_USER_AGENT');
229
        if (strpos($agent, 'MSIE') || strpos($agent, 'Edge') || strpos($agent, 'Trident/7')) {
230
            return 1;
231
        }
232
233
        return 0;
234
    }
235
236
    public function getAssetVersion($filename)
237
    {
238
        if (count($this->paths) === 0) {
239
            $manifestPath = $this->appDir.'/Resources/assets/rev-manifest.json';
240
            if (!file_exists($manifestPath)) {
241
                return $filename;
242
            }
243
            $this->paths = json_decode(file_get_contents($manifestPath), true);
244
            if (!isset($this->paths[$filename])) {
245
                return $filename;
246
            }
247
        }
248
249
        return $this->paths[$filename];
250
    }
251
252
    public function cmpOrderBy($aVar, $bVar)
253
    {
254
        $aValue = $aVar->{'get'.ucfirst($this->param)}();
255
        $bValue = $bVar->{'get'.ucfirst($this->param)}();
256
        switch ($this->order) {
257
            case 'asc':
258
                return $aValue > $bValue;
259
            case 'desc':
260
                return $aValue < $bValue;
261
        }
262
    }
263
264
    public function usortFunction($objects, $parameter, $order = 'asc')
265
    {
266
        $this->param = $parameter;
267
        $this->order = strtolower($order);
268
269
        if (is_object($objects)) {
270
            $objects = $objects->toArray();
271
        }
272
        usort($objects, [
273
            __CLASS__,
274
            'cmpOrderBy',
275
        ]);
276
277
        return $objects;
278
    }
279
}
280