Utility   F
last analyzed

Complexity

Total Complexity 77

Size/Duplication

Total Lines 389
Duplicated Lines 0 %

Importance

Changes 7
Bugs 0 Features 1
Metric Value
eloc 206
dl 0
loc 389
rs 2.24
c 7
b 0
f 1
wmc 77

13 Methods

Rating   Name   Duplication   Size   Complexity  
A getPathTree() 0 18 3
A convertFileSize() 0 18 5
A convertStringToSize() 0 19 5
A cleanVars() 0 15 6
B convertSizeToString() 0 30 10
A getPopularImage() 0 19 4
A getFileSize() 0 21 5
B returnBytes() 0 14 7
B getStatusImage() 0 32 8
A getItemIds() 0 14 4
B getPathTreeUrl() 0 47 10
A prettifyBytes() 0 14 4
A getNumbersOfEntries() 0 19 6

How to fix   Complexity   

Complex Class

Complex classes like Utility often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use Utility, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
declare(strict_types=1);
4
5
namespace XoopsModules\Tdmdownloads;
6
7
/*
8
 Utility Class Definition
9
10
 You may not change or alter any portion of this comment or credits of
11
 supporting developers from this source code or any supporting source code
12
 which is considered copyrighted (c) material of the original comment or credit
13
 authors.
14
15
 This program is distributed in the hope that it will be useful, but
16
 WITHOUT ANY WARRANTY; without even the implied warranty of
17
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
18
 */
19
20
/**
21
 * Class Utility
22
 */
23
class Utility extends Common\SysUtility
24
{
25
    //--------------- Custom module methods -----------------------------
26
    /**
27
     * @param $permtype
28
     * @param $dirname
29
     * @return mixed
30
     */
31
    public function getItemIds($permtype, $dirname)
32
    {
33
        global $xoopsUser;
34
        static $permissions = [];
35
        if (\is_array($permissions) && \array_key_exists($permtype, $permissions)) {
36
            return $permissions[$permtype];
37
        }
38
        /** @var \XoopsModuleHandler $moduleHandler */
39
        $moduleHandler = \xoops_getHandler('module');
40
        $tdmModule     = $moduleHandler->getByDirname($dirname);
41
        $groups        = \is_object($xoopsUser) ? $xoopsUser->getGroups() : XOOPS_GROUP_ANONYMOUS;
42
        /** @var \XoopsGroupPermHandler $grouppermHandler */
43
        $grouppermHandler = \xoops_getHandler('groupperm');
44
        return $grouppermHandler->getItemIds($permtype, $groups, $tdmModule->getVar('mid'));
45
    }
46
47
    /**
48
     * retourne le nombre de téléchargements dans le catégories enfants d'une catégorie
49
     * @param \XoopsModules\Tdmdownloads\Tree        $mytree
50
     * @param                                        $categories
51
     * @param                                        $entries
52
     * @param                                        $cid
53
     * @return int
54
     */
55
    public function getNumbersOfEntries($mytree, $categories, $entries, $cid)
56
    {
57
        $count     = 0;
58
        $child_arr = [];
0 ignored issues
show
Unused Code introduced by
The assignment to $child_arr is dead and can be removed.
Loading history...
59
        if (\in_array($cid, $categories)) {
60
            $child = $mytree->getAllChild($cid);
61
            foreach (\array_keys($entries) as $i) {
62
                /** @var \XoopsModules\Tdmdownloads\Downloads[] $entries */
63
                if ($entries[$i]->getVar('cid') == $cid) {
64
                    $count++;
65
                }
66
                foreach (\array_keys($child) as $j) {
67
                    if ($entries[$i]->getVar('cid') == $j) {
68
                        $count++;
69
                    }
70
                }
71
            }
72
        }
73
        return $count;
74
    }
75
76
    /**
77
     * retourne une image "nouveau" ou "mise à jour"
78
     * @param $time
79
     * @param $status
80
     * @return string
81
     */
82
    public function getStatusImage($time, $status)
83
    {
84
        global $xoopsModuleConfig;
85
        $moduleDirName = \basename(\dirname(__DIR__));
86
        $helper        = Helper::getInstance();
0 ignored issues
show
Unused Code introduced by
The assignment to $helper is dead and can be removed.
Loading history...
87
        $count         = 7;
88
        $new           = '';
89
        $startdate     = \time() - (86400 * $count);
90
        if (1 == $xoopsModuleConfig['showupdated']) {
91
            if ($startdate < $time) {
92
                $language = $GLOBALS['xoopsConfig']['language'];
93
                if (!\is_dir(XOOPS_ROOT_PATH . '/modules/' . $moduleDirName . '/language/' . $language . '/')) {
94
                    $language = 'english';
95
                }
96
                $img_path = XOOPS_ROOT_PATH . '/modules/' . $moduleDirName . '/language/' . $language . '/';
97
                $img_url  = XOOPS_URL . '/modules/' . $moduleDirName . '/language/' . $language . '/';
98
                if (1 == $status) {
99
                    if (\is_readable($img_path . 'new.png')) {
100
                        $new = '&nbsp;<img src="' . $img_url . 'new.png" alt="' . _MD_TDMDOWNLOADS_INDEX_NEWTHISWEEK . '" title="' . _MD_TDMDOWNLOADS_INDEX_NEWTHISWEEK . '">';
101
                    } else {
102
                        $new = '&nbsp;<img src="' . XOOPS_URL . '/modules/' . $moduleDirName . '/language/english/new.png" alt="' . _MD_TDMDOWNLOADS_INDEX_NEWTHISWEEK . '" title="' . _MD_TDMDOWNLOADS_INDEX_NEWTHISWEEK . '">';
103
                    }
104
                } elseif (2 == $status) {
105
                    if (\is_readable($img_path . 'updated.png')) {
106
                        $new = '&nbsp;<img src="' . $img_url . 'updated.png" alt="' . _MD_TDMDOWNLOADS_INDEX_UPTHISWEEK . '" title="' . _MD_TDMDOWNLOADS_INDEX_UPTHISWEEK . '">';
107
                    } else {
108
                        $new = '&nbsp;<img src="' . XOOPS_URL . '/modules/' . $moduleDirName . '/language/english/updated.png" alt="' . _MD_TDMDOWNLOADS_INDEX_UPTHISWEEK . '" title="' . _MD_TDMDOWNLOADS_INDEX_UPTHISWEEK . '">';
109
                    }
110
                }
111
            }
112
        }
113
        return $new;
114
    }
115
116
    /**
117
     * retourne une image "populaire"
118
     * @param $hits
119
     * @return string
120
     */
121
    public function getPopularImage($hits)
122
    {
123
        global $xoopsModuleConfig;
124
        $moduleDirName = \basename(\dirname(__DIR__));
125
        $pop           = '';
126
        if ($hits >= $xoopsModuleConfig['popular']) {
127
            $language = $GLOBALS['xoopsConfig']['language'];
128
            if (!\is_dir(XOOPS_ROOT_PATH . '/modules/' . $moduleDirName . '/language/' . $language . '/')) {
129
                $language = 'english';
130
            }
131
            $img_path = XOOPS_ROOT_PATH . '/modules/' . $moduleDirName . '/language/' . $language . '/';
132
            $img_url  = XOOPS_URL . '/modules/' . $moduleDirName . '/language/' . $language . '/';
133
            if (\is_readable($img_path . 'popular.png')) {
134
                $pop = '&nbsp;<img src="' . $img_url . 'popular.png" alt="' . _MD_TDMDOWNLOADS_INDEX_POPULAR . '" title="' . _MD_TDMDOWNLOADS_INDEX_POPULAR . '">';
135
            } else {
136
                $pop = '&nbsp;<img src ="' . XOOPS_URL . '/modules/' . $moduleDirName . '/language/english/popular.png" alt="' . _MD_TDMDOWNLOADS_INDEX_POPULAR . '" title="' . _MD_TDMDOWNLOADS_INDEX_POPULAR . '">';
137
            }
138
        }
139
        return $pop;
140
    }
141
142
    /**
143
     * @param int $size
144
     * @return string
145
     */
146
    public static function prettifyBytes($size)
147
    {
148
        if ($size > 0) {
149
            $mb = 1024 * 1024;
150
            if ($size > $mb) {
151
                $mysize = \sprintf('%01.2f', $size / $mb) . ' MB';
152
            } elseif ($size >= 1024) {
153
                $mysize = \sprintf('%01.2f', $size / 1024) . ' KB';
154
            } else {
155
                $mysize = \sprintf(_AM_TDMDOWNLOADS_NUMBYTES, $size);
156
            }
157
            return $mysize;
158
        }
159
        return '';
160
    }
161
162
    /**
163
     * @param        $global
164
     * @param        $key
165
     * @param string $default
166
     * @param string $type
167
     * @return mixed|string
168
     */
169
    public static function cleanVars($global, $key, $default = '', $type = 'int')
170
    {
171
        switch ($type) {
172
            case 'string':
173
                $ret = isset($global[$key]) ? \filter_var($global[$key], \FILTER_SANITIZE_MAGIC_QUOTES) : $default;
0 ignored issues
show
introduced by
The constant FILTER_SANITIZE_MAGIC_QUOTES has been deprecated: 7.4 ( Ignorable by Annotation )

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

173
                $ret = isset($global[$key]) ? \filter_var($global[$key], /** @scrutinizer ignore-deprecated */ \FILTER_SANITIZE_MAGIC_QUOTES) : $default;
Loading history...
174
                break;
175
            case 'int':
176
            default:
177
                $ret = isset($global[$key]) ? \filter_var($global[$key], \FILTER_SANITIZE_NUMBER_INT) : $default;
178
                break;
179
        }
180
        if (false === $ret) {
181
            return $default;
182
        }
183
        return $ret;
184
    }
185
186
    /**
187
     * @param        $mytree
188
     * @param        $key
189
     * @param        $category_array
190
     * @param        $title
191
     * @param string $prefix
192
     * @return string
193
     */
194
    public static function getPathTree($mytree, $key, $category_array, $title, $prefix = '')
195
    {
196
        /** @var \XoopsObjectTree $mytree */
197
        $categoryParent = $mytree->getAllParent($key);
198
        $categoryParent = \array_reverse($categoryParent);
199
        $path           = '';
200
        foreach (\array_keys($categoryParent) as $j) {
201
            /** @var \XoopsModules\Tdmdownloads\Category[] $categoryParent */
202
            $path .= $categoryParent[$j]->getVar($title) . $prefix;
203
        }
204
        if (\array_key_exists($key, $category_array)) {
205
            /** @var \XoopsModules\Tdmdownloads\Category[] $category_array */
206
            $firstCategory = $category_array[$key]->getVar($title);
207
        } else {
208
            $firstCategory = '';
209
        }
210
        $path .= $firstCategory;
211
        return $path;
212
    }
213
214
    /**
215
     * @param \XoopsModules\Tdmdownloads\Tree $mytree
216
     * @param                                 $key
217
     * @param                                 $category_array
218
     * @param                                 $title
219
     * @param string                          $prefix
220
     * @param bool                            $link
221
     * @param string                          $order
222
     * @param bool                            $lasturl
223
     * @return string
224
     */
225
    public static function getPathTreeUrl($mytree, $key, $category_array, $title, $prefix = '', $link = false, $order = 'ASC', $lasturl = false)
226
    {
227
        global $xoopsModule;
228
        $categoryParent = $mytree->getAllParent($key);
229
        if ('ASC' === $order) {
230
            $categoryParent = \array_reverse($categoryParent);
231
            if ($link) {
232
                $path = '<a href="index.php">' . $xoopsModule->name() . '</a>' . $prefix;
233
            } else {
234
                $path = $xoopsModule->name() . $prefix;
235
            }
236
        } else {
237
            if (\array_key_exists($key, $category_array)) {
238
                /** @var \XoopsModules\Tdmdownloads\Category[] $category_array */
239
                $firstCategory = $category_array[$key]->getVar($title);
240
            } else {
241
                $firstCategory = '';
242
            }
243
            $path = $firstCategory . $prefix;
244
        }
245
        foreach (\array_keys($categoryParent) as $j) {
246
            /** @var \XoopsModules\Tdmdownloads\Category[] $categoryParent */
247
            if ($link) {
248
                $path .= '<a href="viewcat.php?cid=' . $categoryParent[$j]->getVar('cat_cid') . '">' . $categoryParent[$j]->getVar($title) . '</a>' . $prefix;
249
            } else {
250
                $path .= $categoryParent[$j]->getVar($title) . $prefix;
251
            }
252
        }
253
        if ('ASC' === $order) {
254
            if (\array_key_exists($key, $category_array)) {
255
                if ($lasturl) {
256
                    $firstCategory = '<a href="viewcat.php?cid=' . $category_array[$key]->getVar('cat_cid') . '">' . $category_array[$key]->getVar($title) . '</a>';
257
                } else {
258
                    $firstCategory = $category_array[$key]->getVar($title);
259
                }
260
            } else {
261
                $firstCategory = '';
262
            }
263
            $path .= $firstCategory;
264
        } else {
265
            if ($link) {
266
                $path .= '<a href="index.php">' . $xoopsModule->name() . '</a>';
267
            } else {
268
                $path .= $xoopsModule->name();
269
            }
270
        }
271
        return $path;
272
    }
273
274
    /**
275
     * Utility::convertStringToSize()
276
     *
277
     * @param mixed $stringSize
278
     * @return mixed|int
279
     */
280
    public static function convertStringToSize($stringSize)
281
    {
282
        if ('' != $stringSize) {
283
            $kb             = 1024;
284
            $mb             = 1024 * 1024;
285
            $gb             = 1024 * 1024 * 1024;
286
            $size_value_arr = \explode(' ', $stringSize);
287
            if ('B' == $size_value_arr[1]) {
288
                $mysize = $size_value_arr[0];
289
            } elseif ('K' == $size_value_arr[1]) {
290
                $mysize = $size_value_arr[0] * $kb;
291
            } elseif ('M' == $size_value_arr[1]) {
292
                $mysize = $size_value_arr[0] * $mb;
293
            } else {
294
                $mysize = $size_value_arr[0] * $gb;
295
            }
296
            return $mysize;
297
        }
298
        return 0;
299
    }
300
301
    /**
302
     * Utility::convertSizeToString()
303
     *
304
     * @param mixed $sizeString
305
     * @return string
306
     */
307
    public static function convertSizeToString($sizeString)
308
    {
309
        $mysizeString = '';
310
        if ('' != $sizeString) {
311
            $size_value_arr = \explode(' ', $sizeString);
312
            if (\array_key_exists(0, $size_value_arr) && \array_key_exists(1, $size_value_arr)) {
313
                if ('' != $size_value_arr[0]) {
314
                    $mysizeString = '';
315
                    switch ($size_value_arr[1]) {
316
                        case 'B':
317
                            $mysizeString = $size_value_arr[0] . ' ' . _AM_TDMDOWNLOADS_BYTES;
318
                            break;
319
                        case 'K':
320
                            $mysizeString = $size_value_arr[0] . ' ' . _AM_TDMDOWNLOADS_KBYTES;
321
                            break;
322
                        case 'M':
323
                            $mysizeString = $size_value_arr[0] . ' ' . _AM_TDMDOWNLOADS_MBYTES;
324
                            break;
325
                        case 'G':
326
                            $mysizeString = $size_value_arr[0] . ' ' . _AM_TDMDOWNLOADS_GBYTES;
327
                            break;
328
                        case 'T':
329
                            $mysizeString = $size_value_arr[0] . ' ' . _AM_TDMDOWNLOADS_TBYTES;
330
                            break;
331
                    }
332
                    return $mysizeString;
333
                }
334
            }
335
        }
336
        return $mysizeString;
337
    }
338
339
    /**
340
     * Utility::getFileSize()
341
     *
342
     * @param mixed $url
343
     * @return mixed|string
344
     */
345
    public static function getFileSize($url)
346
    {
347
        if (\function_exists('curl_init') && false !== ($curlHandle = \curl_init($url))) {
348
            \curl_setopt($curlHandle, \CURLOPT_RETURNTRANSFER, true);
349
            \curl_setopt($curlHandle, \CURLOPT_HEADER, true);
350
            \curl_setopt($curlHandle, \CURLOPT_NOBODY, true);
351
            \curl_setopt($curlHandle, \CURLOPT_SSL_VERIFYPEER, true); //TODO: how to avoid an error when 'Peer's Certificate issuer is not recognized'
352
            $curlReturn = \curl_exec($curlHandle);
353
            if (false === $curlReturn) {
354
                \trigger_error(\curl_error($curlHandle));
355
                $size = 0;
356
            } else {
357
                $size = \curl_getinfo($curlHandle, \CURLINFO_CONTENT_LENGTH_DOWNLOAD);
358
            }
359
            \curl_close($curlHandle);
360
            if ($size <= 0) {
361
                return 0;
362
            }
363
            return self::convertFileSize($size);
364
        }
365
        return 0;
366
    }
367
368
    /**
369
     * Utility::convertFileSize()
370
     *
371
     * @param mixed $size
372
     * @return string
373
     */
374
    public static function convertFileSize($size)
375
    {
376
        if ($size > 0) {
377
            $kb = 1024;
378
            $mb = 1024 * 1024;
379
            $gb = 1024 * 1024 * 1024;
380
            if ($size >= $gb) {
381
                $mysize = \sprintf('%01.2f', $size / $gb) . ' ' . 'G';
382
            } elseif ($size >= $mb) {
383
                $mysize = \sprintf('%01.2f', $size / $mb) . ' ' . 'M';
384
            } elseif ($size >= $kb) {
385
                $mysize = \sprintf('%01.2f', $size / $kb) . ' ' . 'K';
386
            } else {
387
                $mysize = \sprintf('%01.2f', $size) . ' ' . 'B';
388
            }
389
            return $mysize;
390
        }
391
        return '';
392
    }
393
394
    /**
395
     * @param $val
396
     * @return float|int
397
     */
398
    public static function returnBytes($val)
399
    {
400
        switch (\mb_substr($val, -1)) {
401
            case 'K':
402
            case 'k':
403
                return (int)$val * 1024;
404
            case 'M':
405
            case 'm':
406
                return (int)$val * 1048576;
407
            case 'G':
408
            case 'g':
409
                return (int)$val * 1073741824;
410
            default:
411
                return $val;
412
        }
413
    }
414
}
415