SludioExtension::fileExists()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 3
rs 10
c 0
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
17
    protected $appDir;
18
    protected $param;
19
    protected $order;
20
    protected $request;
21
    protected $paths = [];
22
23
    public function __construct($shortFunctions, $appDir, RequestStack $requestStack)
24
    {
25
        $this->shortFunctions = $shortFunctions;
26
        $this->appDir = $appDir;
27
        $this->request = $requestStack->getCurrentRequest();
28
    }
29
30
    public function getFilters()
31
    {
32
        $input = [
33
            'beautify' => 'beautify',
34
            'urldecode' => 'urlDecode',
35
            'parse' => 'parse',
36
            'file_exists' => 'fileExists',
37
            'html_entity_decode' => 'htmlEntityDecode',
38
            'strip_descr' => 'stripDescr',
39
            'pretty_print' => 'prettyPrint',
40
            'status_code_class' => 'statusCodeClass',
41
            'format_duration' => 'formatDuration',
42
            'short_uri' => 'shorthenUri',
43
            'is_ie' => 'isIE',
44
            'asset_version' => 'getAssetVersion',
45
            'usort' => 'usortFunction',
46
            'route_exists' => 'routeExists',
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 urlDecode($string)
62
    {
63
        return urldecode($string);
64
    }
65
66
    public function parse($string)
67
    {
68
        $str = parse_url($string);
69
70
        $arguments = [];
71
        if (isset($str['query'])) {
72
            foreach (explode('&', $str['query']) as $arg) {
73
                $tmp = explode('=', $arg, 2);
74
                $arguments[$tmp[0]] = $tmp[1];
75
            }
76
        }
77
78
        return $arguments;
79
    }
80
81
    public function fileExists($file)
82
    {
83
        return file_exists(getcwd().$file);
84
    }
85
86
    public function beautify($string)
87
    {
88
        return \mb_str_replace('/', ' / ', \strip_tags($string));
0 ignored issues
show
Bug introduced by
The function mb_str_replace was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

88
        return /** @scrutinizer ignore-call */ \mb_str_replace('/', ' / ', \strip_tags($string));
Loading history...
89
    }
90
91
    public function htmlEntityDecode($str)
92
    {
93
        $str = html_entity_decode($str);
94
        $str = preg_replace('#\R+#', '', $str);
95
96
        return $str;
97
    }
98
99
    public function stripDescr($body, $fallback = null, $type = null, $lengthIn = 300)
100
    {
101
        $length = null;
102
103
        if ($type && $fallback) {
104
            $length = isset($fallback[$type]) ? $fallback[$type] : null;
105
        }
106
        if ($length === null) {
107
            $length = $lengthIn;
108
        }
109
110
        if (\strlen($body) > $length) {
111
            $spacePosition = strpos($body, ' ', $length) ?: $length;
112
            $body = substr($body, 0, $spacePosition).'...';
113
        }
114
115
        return $body;
116
    }
117
118
    public function detectLang($body)
119
    {
120
        switch (true) {
121
            case 0 === strpos($body, '<?xml'):
122
                return 'xml';
123
            case 0 === strpos($body, '{'):
124
            case 0 === strpos($body, '['):
125
                return 'json';
126
            default:
127
                return 'markup';
128
        }
129
    }
130
131
    public function prettyPrint($code, $lang)
132
    {
133
        switch ($lang) {
134
            case 'json':
135
                return json_encode(json_decode($code), JSON_PRETTY_PRINT);
136
            case 'xml':
137
                $xml = new \DomDocument('1.0', 'UTF-8');
138
                $xml->preserveWhiteSpace = false;
139
                $xml->formatOutput = true;
140
                $xml->loadXML($code);
141
142
                return $xml->saveXML();
143
            default:
144
                return $code;
145
        }
146
    }
147
148
    public function statusCodeClass($statusCode)
149
    {
150
        $codes = [
151
            1 => self::INFO,
152
            2 => self::SUCCESS,
153
            3 => self::REDIRECT,
154
            4 => self::CLIENT,
155
            5 => self::SERVER,
156
        ];
157
        $code = (int)floor((int)$statusCode) / 100;
158
159
        return isset($codes[$code]) ? $codes[$code] : 'unknown';
160
    }
161
162
    public function formatDuration($seconds)
163
    {
164
        $formats = [
165
            '%.2f s',
166
            '%d ms',
167
            '%d µs',
168
        ];
169
170
        while ($format = array_shift($formats)) {
171
            if ($seconds > 1) {
172
                break;
173
            }
174
175
            $seconds *= 1000;
176
        }
177
178
        return sprintf($format, $seconds);
179
    }
180
181
    public function shortenUri($uri)
182
    {
183
        $parts = parse_url($uri);
184
185
        return sprintf('%s://%s%s', isset($parts['scheme']) ? $parts['scheme'] : 'http', $parts['host'], isset($parts['port']) ? (':'.$parts['port']) : '');
186
    }
187
188
    public function isIE()
189
    {
190
        $agent = $this->request->server->get('HTTP_USER_AGENT');
191
        if (strpos($agent, 'MSIE') || strpos($agent, 'Edge') || strpos($agent, 'Trident/7')) {
192
            return 1;
193
        }
194
195
        return 0;
196
    }
197
198
    public function getAssetVersion($filename)
199
    {
200
        if (\count($this->paths) === 0) {
201
            $manifestPath = $this->appDir.'/Resources/assets/rev-manifest.json';
202
            if (!file_exists($manifestPath)) {
203
                return $filename;
204
            }
205
            $this->paths = json_decode(file_get_contents($manifestPath), true);
206
            if (!isset($this->paths[$filename])) {
207
                return $filename;
208
            }
209
        }
210
211
        return $this->paths[$filename];
212
    }
213
214
    public function cmpOrderBy($aVar, $bVar)
215
    {
216
        $aValue = $aVar->{'get'.ucfirst($this->param)}();
217
        $bValue = $bVar->{'get'.ucfirst($this->param)}();
218
        switch ($this->order) {
219
            case 'asc':
220
                return $aValue > $bValue;
221
            case 'desc':
222
                return $aValue < $bValue;
223
        }
224
    }
225
226
    public function usortFunction($objects, $parameter, $order = 'asc')
227
    {
228
        $this->param = $parameter;
229
        $this->order = strtolower($order);
230
231
        if (\is_object($objects)) {
232
            $objects = $objects->toArray();
233
        }
234
        usort($objects, [
235
            __CLASS__,
236
            'cmpOrderBy',
237
        ]);
238
239
        return $objects;
240
    }
241
    
242
    public function routeExists($route)
243
    {
244
        return null !== $this->router->getRouteCollection()->get($route);
0 ignored issues
show
Bug Best Practice introduced by
The property router does not exist on Sludio\HelperBundle\Script\Twig\SludioExtension. Did you maybe forget to declare it?
Loading history...
245
    }
246
}
247