EquipmentUtility   B
last analyzed

Complexity

Total Complexity 47

Size/Duplication

Total Lines 282
Duplicated Lines 7.8 %

Coupling/Cohesion

Components 0
Dependencies 0

Importance

Changes 0
Metric Value
dl 22
loc 282
rs 8.439
c 0
b 0
f 0
wmc 47
lcom 0
cbo 0

12 Methods

Rating   Name   Duplication   Size   Complexity  
B selectSorting() 0 29 5
A block_addCatSelect() 0 14 3
A meta_keywords() 11 11 3
A meta_description() 11 11 3
A enumerate() 0 19 2
A cloneRecord() 0 18 4
B createFolder() 0 14 5
A copyFile() 0 4 1
B recurseCopy() 0 15 5
D checkVerXoops() 0 39 9
A checkVerPhp() 0 16 4
A getQueryDataToJSON() 0 14 3

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like EquipmentUtility 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. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

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 EquipmentUtility, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
/*
4
 You may not change or alter any portion of this comment or credits
5
 of supporting developers from this source code or any supporting source code
6
 which is considered copyrighted (c) material of the original comment or credit authors.
7
8
 This program is distributed in the hope that it will be useful,
9
 but WITHOUT ANY WARRANTY; without even the implied warranty of
10
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
11
*/
12
13
/**
14
 * Module: Equipment
15
 *
16
 * @category        Module
17
 * @package         equipment
18
 * @author          XOOPS Development Team <[email protected]> - <http://xoops.org>
19
 * @copyright       {@link https://xoops.org/ XOOPS Project}
20
 * @license         GPL 2.0 or later
21
 * @link            https://xoops.org/
22
 * @since           1.0.0
23
 */
24
25
use Xmf\Request;
26
27
require_once __DIR__ . '/../include/config.php';
28
29
/**
30
 * Class EquipmentUtility
31
 */
32
class EquipmentUtility
33
{
34
    /**
35
     * @param $text
36
     * @param $form_sort
37
     * @return string
38
     */
39
    public static function selectSorting($text, $form_sort)
40
    {
41
        global $start, $order, $file_cat, $sort, $xoopsModule;
42
43
        $select_view   = '';
0 ignored issues
show
Unused Code introduced by
$select_view is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
44
        $moduleDirName = basename(dirname(__DIR__));
45
46
        if (false !== ($moduleHelper = Xmf\Module\Helper::getHelper($moduleDirName))) {
0 ignored issues
show
Unused Code introduced by
This if statement is empty and can be removed.

This check looks for the bodies of if statements that have no statements or where all statements have been commented out. This may be the result of changes for debugging or the code may simply be obsolete.

These if bodies can be removed. If you have an empty if but statements in the else branch, consider inverting the condition.

if (rand(1, 6) > 3) {
//print "Check failed";
} else {
    print "Check succeeded";
}

could be turned into

if (rand(1, 6) <= 3) {
    print "Check succeeded";
}

This is much more concise to read.

Loading history...
47
        } else {
48
            $moduleHelper = Xmf\Module\Helper::getHelper('system');
49
        }
50
51
        $pathModIcon16 = XOOPS_URL . '/modules/' . $moduleDirName . '/' . $moduleHelper->getModule()->getInfo('modicons16');
52
53
        $select_view = '<form name="form_switch" id="form_switch" action="' . Request::getString('REQUEST_URI', '', 'SERVER') . '" method="post"><span style="font-weight: bold;">' . $text . '</span>';
54
        //$sorts =  $sort ==  'asc' ? 'desc' : 'asc';
0 ignored issues
show
Unused Code Comprehensibility introduced by
45% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
55
        if ($form_sort == $sort) {
56
            $sel1 = $order === 'asc' ? 'selasc.png' : 'asc.png';
57
            $sel2 = $order === 'desc' ? 'seldesc.png' : 'desc.png';
58
        } else {
59
            $sel1 = 'asc.png';
60
            $sel2 = 'desc.png';
61
        }
62
        $select_view .= '  <a href="' . Request::getString('PHP_SELF', '', 'SERVER') . '?start=' . $start . '&sort=' . $form_sort . '&order=asc" /><img src="' . $pathModIcon16 . '/' . $sel1 . '" title="ASC" alt="ASC"></a>';
63
        $select_view .= '<a href="' . Request::getString('PHP_SELF', '', 'SERVER') . '?start=' . $start . '&sort=' . $form_sort . '&order=desc" /><img src="' . $pathModIcon16 . '/' . $sel2 . '" title="DESC" alt="DESC"></a>';
64
        $select_view .= '</form>';
65
66
        return $select_view;
67
    }
68
69
70
71
    /***************Blocks***************/
72
    /**
73
     * @param array $cats
74
     * @return string
75
     */
76
    public static function block_addCatSelect($cats)
77
    {
78
        $cat_sql = '';
79
        if (is_array($cats)) {
80
            $cat_sql = '(' . current($cats);
81
            array_shift($cats);
82
            foreach ($cats as $cat) {
83
                $cat_sql .= ',' . $cat;
84
            }
85
            $cat_sql .= ')';
86
        }
87
88
        return $cat_sql;
89
    }
90
91
    /**
92
     * @param $content
93
     */
94 View Code Duplication
    public static function meta_keywords($content)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
95
    {
96
        global $xoopsTpl, $xoTheme;
97
        $myts    = MyTextSanitizer::getInstance();
98
        $content = $myts->undoHtmlSpecialChars($myts->displayTarea($content));
99
        if (null !== $xoTheme && is_object($xoTheme)) {
100
            $xoTheme->addMeta('meta', 'keywords', strip_tags($content));
101
        } else {    // Compatibility for old Xoops versions
102
            $xoopsTpl->assign('xoops_meta_keywords', strip_tags($content));
103
        }
104
    }
105
106
    /**
107
     * @param $content
108
     */
109 View Code Duplication
    public static function meta_description($content)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
110
    {
111
        global $xoopsTpl, $xoTheme;
112
        $myts    = MyTextSanitizer::getInstance();
113
        $content = $myts->undoHtmlSpecialChars($myts->displayTarea($content));
114
        if (null !== $xoTheme && is_object($xoTheme)) {
115
            $xoTheme->addMeta('meta', 'description', strip_tags($content));
116
        } else {    // Compatibility for old Xoops versions
117
            $xoopsTpl->assign('xoops_meta_description', strip_tags($content));
118
        }
119
    }
120
121
    /**
122
     * @param $tableName
123
     * @param $columnName
124
     *
125
     * @return array
126
     */
127
    public static function enumerate($tableName, $columnName)
128
    {
129
        $table = $GLOBALS['xoopsDB']->prefix($tableName);
130
131
        //    $result = $GLOBALS['xoopsDB']->query("SELECT COLUMN_TYPE FROM INFORMATION_SCHEMA.COLUMNS
132
        //        WHERE TABLE_NAME = '" . $table . "' AND COLUMN_NAME = '" . $columnName . "'")
133
        //    || exit ($GLOBALS['xoopsDB']->error());
0 ignored issues
show
Unused Code Comprehensibility introduced by
75% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
134
135
        $sql    = 'SELECT COLUMN_TYPE FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = "' . $table . '" AND COLUMN_NAME = "' . $columnName . '"';
136
        $result = $GLOBALS['xoopsDB']->query($sql);
137
        if (!$result) {
138
            exit($GLOBALS['xoopsDB']->error());
139
        }
140
141
        $row      = $GLOBALS['xoopsDB']->fetchBoth($result);
142
        $enumList = explode(',', str_replace("'", '', substr($row['COLUMN_TYPE'], 5, strlen($row['COLUMN_TYPE']) - 6)));
143
144
        return $enumList;
145
    }
146
147
    /**
148
     * @param array|string $tableName
149
     * @param int          $id_field
150
     * @param int          $id
151
     *
152
     * @return mixed
153
     */
154
    public static function cloneRecord($tableName, $id_field, $id)
155
    {
156
        $new_id = false;
157
        $table  = $GLOBALS['xoopsDB']->prefix($tableName);
158
        // copy content of the record you wish to clone 
159
        $tempTable = $GLOBALS['xoopsDB']->fetchArray($GLOBALS['xoopsDB']->query("SELECT * FROM $table WHERE $id_field='$id' "), MYSQLI_ASSOC) or exit('Could not select record');
160
        // set the auto-incremented id's value to blank.
161
        unset($tempTable[$id_field]);
162
        // insert cloned copy of the original  record 
163
        $result = $GLOBALS['xoopsDB']->queryF("INSERT INTO $table (" . implode(', ', array_keys($tempTable)) . ") VALUES ('" . implode("', '", array_values($tempTable)) . "')") or exit($GLOBALS['xoopsDB']->error());
164
165
        if ($result) {
166
            // Return the new id
167
            $new_id = $GLOBALS['xoopsDB']->getInsertId();
168
        }
169
170
        return $new_id;
171
    }
172
173
    /**
174
     * Function responsible for checking if a directory exists, we can also write in and create an index.html file
175
     *
176
     * @param string $folder The full path of the directory to check
177
     *
178
     * @return void
179
     */
180
    public static function createFolder($folder)
181
    {
182
        try {
183
            if (!file_exists($folder)) {
184
                if (!mkdir($folder) && !is_dir($folder)) {
185
                    throw new \RuntimeException(sprintf('Unable to create the %s directory', $folder));
186
                }
187
                file_put_contents($folder . '/index.html', '<script>history.go(-1);</script>');
188
            }
189
        }
190
        catch (Exception $e) {
191
            echo 'Caught exception: ', $e->getMessage(), '', '<br>';
192
        }
193
    }
194
195
    /**
196
     * @param $file
197
     * @param $folder
198
     * @return bool
199
     */
200
    public static function copyFile($file, $folder)
201
    {
202
        return copy($file, $folder);
203
    }
204
205
    /**
206
     * @param $src
207
     * @param $dst
208
     */
209
    public static function recurseCopy($src, $dst)
210
    {
211
        $dir = opendir($src);
212
        //    @mkdir($dst);
213
        while (false !== ($file = readdir($dir))) {
214
            if (($file !== '.') && ($file !== '..')) {
215
                if (is_dir($src . '/' . $file)) {
216
                    static::recurseCopy($src . '/' . $file, $dst . '/' . $file);
217
                } else {
218
                    copy($src . '/' . $file, $dst . '/' . $file);
219
                }
220
            }
221
        }
222
        closedir($dir);
223
    }
224
225
    /**
226
     *
227
     * Verifies XOOPS version meets minimum requirements for this module
228
     * @static
229
     * @param XoopsModule $module
230
     *
231
     * @param null|string $requiredVer
232
     * @return bool true if meets requirements, false if not
233
     */
234
    public static function checkVerXoops(XoopsModule $module = null, $requiredVer = null)
235
    {
236
        $moduleDirName = basename(dirname(__DIR__));
237
        if (null === $module) {
238
            $module = XoopsModule::getByDirname($moduleDirName);
239
        }
240
        xoops_loadLanguage('admin', $moduleDirName);
241
        //check for minimum XOOPS version
242
        $currentVer = substr(XOOPS_VERSION, 6); // get the numeric part of string
243
        $currArray  = explode('.', $currentVer);
244
        if (null === $requiredVer) {
245
            $requiredVer = '' . $module->getInfo('min_xoops'); //making sure it's a string
246
        }
247
        $reqArray = explode('.', $requiredVer);
248
        $success  = true;
249
        foreach ($reqArray as $k => $v) {
250
            if (isset($currArray[$k])) {
251
                if ($currArray[$k] > $v) {
252
                    break;
253
                } elseif ($currArray[$k] == $v) {
254
                    continue;
255
                } else {
256
                    $success = false;
257
                    break;
258
                }
259
            } else {
260
                if ((int)$v > 0) { // handles things like x.x.x.0_RC2
261
                    $success = false;
262
                    break;
263
                }
264
            }
265
        }
266
267
        if (!$success) {
268
            $module->setErrors(sprintf(AM_EQUIPMENT_ERROR_BAD_XOOPS, $requiredVer, $currentVer));
269
        }
270
271
        return $success;
272
    }
273
274
    /**
275
     *
276
     * Verifies PHP version meets minimum requirements for this module
277
     * @static
278
     * @param XoopsModule $module
279
     *
280
     * @return bool true if meets requirements, false if not
281
     */
282
    public static function checkVerPhp(XoopsModule $module)
283
    {
284
        xoops_loadLanguage('admin', $module->dirname());
285
        // check for minimum PHP version
286
        $success = true;
287
        $verNum  = PHP_VERSION;
288
        $reqVer  = $module->getInfo('min_php');
289
        if (false !== $reqVer && '' !== $reqVer) {
290
            if (version_compare($verNum, $reqVer, '<')) {
291
                $module->setErrors(sprintf(AM_EQUIPMENT_ERROR_BAD_PHP, $reqVer, $verNum));
292
                $success = false;
293
            }
294
        }
295
296
        return $success;
297
    }
298
299
    public static function getQueryDataToJSON($sql)
300
    {
301
        global $xoopsDB;
302
        $query      = $xoopsDB->query($sql);
303
        $query_rows = [];
304
305
        if ($xoopsDB->getRowsNum($query) > 0) {
306
            while ($row = $xoopsDB->fetchArray($query)) {
307
                $query_rows[] = $row;
308
            }
309
        }
310
311
        return json_encode($query_rows);
312
    }
313
}
314