Passed
Push — master ( b38da1...a59646 )
by Dāvis
04:33
created

SludioExtension::getName()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

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