Completed
Push — master ( 55b92e...48ecb4 )
by Michael
01:50
created

InstructionTree::_makeCatsAdminOptions()   C

Complexity

Conditions 10
Paths 99

Size

Total Lines 59
Code Lines 33

Duplication

Lines 5
Ratio 8.47 %

Importance

Changes 0
Metric Value
cc 10
eloc 33
nc 99
nop 6
dl 5
loc 59
rs 6.5919
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
// Автор: andrey3761
3
// Вывод древообразного списка страниц в панели администрирования
4
5
//defined('XOOPS_ROOT_PATH') || exit('Restricted access');
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...
6
define('INST_DIRNAME', basename(dirname(__DIR__)));
7
8
include_once $GLOBALS['xoops']->path('include/common.php');
9
// Подключаем трей
10
include_once $GLOBALS['xoops']->path('class/tree.php');
11
12
// Наследник класса XoopsObjectTree
13
class InstructionTree extends XoopsObjectTree
14
{
15
//    public function __construct()
0 ignored issues
show
Unused Code Comprehensibility introduced by
43% 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...
16
//    {
17
//    }
18
19
    public function _makePagesAdminOptions($key, &$ret, $prefix_orig, $objInsinstr, $class = 'odd', $prefix_curr = '')
20
    {
21
        if ($key > 0) {
22
23
            //
24
            $class = ('even' == $class) ? 'odd' : 'even';
25
            // ID инструкции ( Можно сделать статической )
26
            $instrid = $objInsinstr->getVar('instrid');
27
28
            // ID страницы
29
            $pageid = $this->tree[$key]['obj']->getVar('pageid');
30
            // Название страницы
31
            $pagetitle = $this->tree[$key]['obj']->getVar('title');
32
            // Вес
33
            $pageweight = $this->tree[$key]['obj']->getVar('weight');
34
            // Статус
35
            $pagestatus = $this->tree[$key]['obj']->getVar('status');
36
            // Тип страницы
37
            $pagetype = $this->tree[$key]['obj']->getVar('type');
38
39
            // Дочернии страницы
40
            $page_childs = $this->getAllChild($pageid);
41
            // Число дочерних страниц
42
            $num_childs = count($page_childs);
43
44
            // Действие - удаление
45
            $act_del = ($num_childs > 0) ? '<img src="../assets/icons/no_delete_mini.png" alt="' . _AM_INSTR_NODELPAGE . '" title="' . _AM_INSTR_NODELPAGE . '" />' : '<a href="instr.php?op=delpage&pageid='
46
                                                                                                                                                                      . $pageid
47
                                                                                                                                                                      . '"><img src="../assets/icons/delete_mini.png" alt="'
48
                                                                                                                                                                      . _AM_INSTRUCTION_DEL
49
                                                                                                                                                                      . '" title="'
50
                                                                                                                                                                      . _AM_INSTRUCTION_DEL
51
                                                                                                                                                                      . '"></a>';
52
            //
53
            $page_link = '<a name="pageid_' . $pageid . '" ' . ($pagetype ? 'href="' . XOOPS_URL . '/modules/' . INST_DIRNAME . '/page.php?id=' . $pageid . '#pagetext"' : '') . '>' . $pagetitle . '</a>';
54
55
            $ret .= '<tr class="' . $class . '">
56
      <td>' . $prefix_curr . ' ' . $page_link . '</td>
57
      <td align="center" width="50">
58
        <input type="text" name="weights[]" size="2" value="' . $pageweight . '" />
59
        <input type="hidden" name="pageids[]" value="' . $pageid . '" />
60
      </td>
61
      <td align="center" width="180">';
62
            // Просмотре без кэша
63
            $ret .= ' <a href="' . XOOPS_URL . '/modules/' . INST_DIRNAME . '/page.php?id=' . $pageid . '&amp;nocache=1"><img src="../assets/icons/no_cache.png" alt="' . _AM_INSTR_DISPLAY_NOCACHE . '" title="' . _AM_INSTR_DISPLAY_NOCACHE . '" /></a> ';
64
            // Добавить подстраницу
65
            $ret .= ' <a href="instr.php?op=editpage&instrid=' . $instrid . '&pid=' . $pageid . '"><img src="../assets/icons/add_mini.png" alt="' . _AM_INSTRUCTION_ADDSUBPAGE . '" title="' . _AM_INSTRUCTION_ADDSUBPAGE . '" /></a> ';
66
67
            if ($pagestatus) {
68
                $ret .= ' <img src="../assets/icons/lock_mini.png" alt="' . _AM_INSTRUCTION_LOCK . '" title="' . _AM_INSTRUCTION_LOCK . '"> ';
69
            } else {
70
                $ret .= ' <img src="../assets/icons/unlock_mini.png" alt="' . _AM_INSTRUCTION_UNLOCK . '" title="' . _AM_INSTRUCTION_UNLOCK . '"> ';
71
            }
72
73
            $ret .= ' <a href="instr.php?op=editpage&pageid=' . $pageid . '"><img src="../assets/icons/edit_mini.png" alt="' . _AM_INSTRUCTION_EDIT . '" title="' . _AM_INSTRUCTION_EDIT . '"></a> ' . $act_del . '
74
      </td>
75
    </tr>';
76
77
            // Устанавливаем префикс
78
            $prefix_curr .= $prefix_orig;
79
        }
80
81 View Code Duplication
        if (isset($this->tree[$key]['child']) && !empty($this->tree[$key]['child'])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
82
            foreach ($this->tree[$key]['child'] as $childkey) {
83
                $this->_makePagesAdminOptions($childkey, $ret, $prefix_orig, $objInsinstr, $class, $prefix_curr);
84
            }
85
        }
86
    }
87
88
    public function makePagesAdmin(&$objInsinstr, $prefix = '-', $key = 0)
89
    {
90
        $ret = '<form name="inspages" action="instr.php" method="post">
91
  <table width="100%" cellspacing="1" class="outer">
92
    <tr>
93
      <th align="center" colspan="3">' . sprintf(_AM_INSTRUCTION_LISTPAGESININSTR, $objInsinstr->getVar('title')) . '</th>
94
    </tr>
95
    <tr>
96
      <td class="head" align="center">' . _AM_INSTRUCTION_TITLE . '</td>
97
      <td class="head" align="center" width="50">' . _AM_INSTRUCTION_WEIGHT . '</td>
98
      <td class="head" align="center" width="180">' . _AM_INSTRUCTION_ACTION . '</td>
99
    </tr>';
100
101
        // Выводим все страницы
102
        $this->_makePagesAdminOptions($key, $ret, $prefix, $objInsinstr);
103
104
        $ret .= '<tr class="foot">
105
      <td><a href="instr.php?op=editpage&instrid=' . $objInsinstr->getVar('instrid') . '"><img src="../assets/icons/add_mini.png" alt="' . _AM_INSTRUCTION_ADDPAGE . '" title="' . _AM_INSTRUCTION_ADDPAGE . '"></a></td>
106
      <td colspan="2">
107
        <input type="hidden" name="instrid" value="' . $objInsinstr->getVar('instrid') . '" />
108
        <input type="hidden" name="op" value="updpage" />
109
        <input type="submit" value="' . _SUBMIT . '" />
110
      </td>
111
    </tr>
112
  </table>
113
</form>';
114
115
        return $ret;
116
    }
117
118
    // ==================================
119
    // === Дерево категорий в админке ===
120
    // ==================================
121
122
    public function _makeCatsAdminOptions($key, &$ret, $prefix_orig, $cidinstrids = [], &$class = 'odd', $prefix_curr = '')
123
    {
124
        if ($key > 0) {
125
126
            //
127
            $class = ('even' == $class) ? 'odd' : 'even';
128
129
            // ID категории
130
            $catid = $this->tree[$key]['obj']->getVar('cid');
131
            // Название категории
132
            $cattitle = $this->tree[$key]['obj']->getVar('title');
133
            // Вес
134
            $catweight = $this->tree[$key]['obj']->getVar('weight');
135
            // Статус
136
            $pagestatus = $this->tree[$key]['obj']->getVar('status');
0 ignored issues
show
Unused Code introduced by
$pagestatus 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...
137
138
            // Дочернии категории
139
            $cat_childs = $this->getAllChild($catid);
140
            // Число дочерних категорий
141
            $num_childs = count($cat_childs);
142
            // Число инструкций
143
            $num_instrs = isset($cidinstrids[$catid]) ? $cidinstrids[$catid] : 0;
144
145
            // Действие - удаление
146
            $act_del = (($num_instrs > 0) || ($num_childs > 0)) ? '<img src="../assets/icons/no_delete_mini.png" alt="' . _AM_INSTR_NODELCAT . '" title="' . _AM_INSTR_NODELCAT . '" />' : '<a href="cat.php?op=delcat&cid='
147
                                                                                                                                                                                           . $catid
148
                                                                                                                                                                                           . '"><img src="../assets/icons/delete_mini.png" alt="'
149
                                                                                                                                                                                           . _AM_INSTRUCTION_DEL
150
                                                                                                                                                                                           . '" title="'
151
                                                                                                                                                                                           . _AM_INSTRUCTION_DEL
152
                                                                                                                                                                                           . '" /></a>';
153
            // Действие - просмотр
154
            $act_view = ($num_instrs > 0) ? '<a href="instr.php?cid=' . $catid . '"><img src="../assets/icons/view_mini.png" alt="' . _AM_INSTR_VIEWINSTR . '" title="' . _AM_INSTR_VIEWINSTR . '" /></a>' : '<img src="../assets/icons/no_view_mini.png" alt="'
155
                                                                                                                                                                                                             . _AM_INSTR_NOVIEWINSTR
156
                                                                                                                                                                                                             . '" title="'
157
                                                                                                                                                                                                             . _AM_INSTR_NOVIEWINSTR
158
                                                                                                                                                                                                             . '" />';
159
160
            $ret .= '<tr class="' . $class . '">
161
      <td>' . $prefix_curr . ' <a href="' . XOOPS_URL . '/modules/' . INST_DIRNAME . '/index.php?cid=' . $catid . '">' . $cattitle . '</a></td>
162
      <td align="center" width="50">' . $catweight . '</td>
163
      <td align="center" width="100">' . $num_instrs . '</td>
164
      <td align="center" width="150">
165
        ' . $act_view . '
166
        <a href="cat.php?op=editcat&cid=' . $catid . '"><img src="../assets/icons/edit_mini.png" alt="' . _AM_INSTRUCTION_EDIT . '" title="' . _AM_INSTRUCTION_EDIT . '"></a>
167
        ' . $act_del . '
168
      </td>
169
    </tr>';
170
171
            // Устанавливаем префикс
172
            $prefix_curr .= $prefix_orig;
173
        }
174
175 View Code Duplication
        if (isset($this->tree[$key]['child']) && !empty($this->tree[$key]['child'])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
176
            foreach ($this->tree[$key]['child'] as $childkey) {
177
                $this->_makeCatsAdminOptions($childkey, $ret, $prefix_orig, $cidinstrids, $class, $prefix_curr);
178
            }
179
        }
180
    }
181
182
    public function makeCatsAdmin($prefix = '-', $cidinstrids = [], $key = 0)
183
    {
184
        $ret = '<table width="100%" cellspacing="1" class="outer">
185
    <tr>
186
      <th align="center" colspan="4">' . _AM_INSTR_LISTALLCATS . '</th>
187
    </tr>
188
    <tr>
189
      <td class="head">' . _AM_INSTRUCTION_TITLE . '</td>
190
      <td class="head" align="center" width="50">' . _AM_INSTRUCTION_WEIGHT . '</td>
191
	  <td class="head" align="center" width="100">' . _AM_INSTR_INSTRS . '</td>
192
      <td class="head" align="center" width="150">' . _AM_INSTRUCTION_ACTION . '</td>
193
    </tr>';
194
195
        // Выводим все страницы
196
        $this->_makeCatsAdminOptions($key, $ret, $prefix, $cidinstrids);
197
198
        $ret .= '</table>';
199
200
        return $ret;
201
    }
202
203
    // ======================================
204
    // Список страниц на стороне пользователя
205
    // ======================================
206
207
    public function _makePagesUserTree($key, &$ret, $currpageid = 0, &$lastpageids = [], $level = 0)
208
    {
209
210
        // Сохраняем значение предыдущей страницы
211
        //static $stat_prevpages;
212
213
        if ($key > 0) {
214
215
            // ID страницы
216
            $pageid = $this->tree[$key]['obj']->getVar('pageid');
217
            // Название страницы
218
            $pagetitle = $this->tree[$key]['obj']->getVar('title');
219
            // Тип страницы
220
            $pagetype = $this->tree[$key]['obj']->getVar('type');
221
222
            // Дочернии категории
223
            $page_childs = $this->getAllChild($pageid);
224
            // Число дочерних страниц
225
            $num_childs = count($page_childs);
226
227
            // Генерируем класс
228
            // InstrTreeNode InstrTreeIsRoot InstrTreeExpandClosed InstrTreeIsLast
229
            $class = [];
230
            // Данный класс должен быть у любого узла
231
            $class[] = 'InstrTreeNode';
232
            // Если узел нулевого уровня, добавляем InstrTreeIsRoot
233
            if (0 === $level) {
234
                $class[] = 'InstrTreeIsRoot';
235
            }
236
            // Тип узла InstrTreeExpandClosed|InstrTreeExpandLeaf
237
            // Если у узла нет потомков - InstrTreeExpandLeaf
238
            if (0 == $num_childs) {
239
                $class[] = 'InstrTreeExpandLeaf';
240
                // Если у искомого элемента есть потомки - открываем список
241
            } elseif ($currpageid == $pageid) {
242
                $class[] = 'InstrTreeExpandOpen';
243
                // Если искомый элемент есть в потомках текущего, то ставим класс InstrTreeExpandOpen
244
            } elseif (in_array($currpageid, array_keys($page_childs))) {
245
                $class[] = 'InstrTreeExpandOpen';
246
                //
247
            } else {
248
                $class[] = 'InstrTreeExpandClosed';
249
            }
250
251
            // Данный класс нужно добавлять последнему узлу в каждом уровне
252
253
            if (isset($lastpageids[$level]) && ($pageid == $lastpageids[$level])) {
254
                $class[] = 'InstrTreeIsLast';
255
            }
256
257
            //$class[] = 'InstrTreeIsLast';
0 ignored issues
show
Unused Code Comprehensibility introduced by
63% 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...
258
259
            // Test
260
            //$ret .= '<div id="' . $pageid . '">';
261
262
            // Создаём запись
263
            $ret .= '<li class="' . implode(' ', $class) . '">';
264
            //
265
            $ret .= '<div class="InstrTreeExpand"></div>';
266
            //
267
            $ret .= '<div class="InstrTreeContent">';
268
269
            // Если это лист дерева
270
            if (0 == $pagetype) {
271
                $ret .= '<span class="InstrTreeEmptyPage">' . $pagetitle . '</span>';
272
                //
273
            } elseif ($currpageid == $pageid) {
274
                $ret .= $pagetitle;
275
                //
276
            } else {
277
                $ret .= '<a href="' . XOOPS_URL . '/modules/' . INST_DIRNAME . '/page.php?id=' . $pageid . '#pagetext">' . $pagetitle . '</a>';
278
            }
279
280
            $ret .= '</div>';
281
282
            // Если есть потомки
283
            if ($num_childs > 0) {
284
                $ret .= '<ul class="InstrTreeContainer">';
285
            }
286
287
            // Инкримент уровня
288
            $level++;
289
        }
290
291
        // Рекурсия
292 View Code Duplication
        if (isset($this->tree[$key]['child']) && !empty($this->tree[$key]['child'])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
293
            foreach ($this->tree[$key]['child'] as $childkey) {
294
                $this->_makePagesUserTree($childkey, $ret, $currpageid, $lastpageids, $level);
295
            }
296
        }
297
298
        // Test
299
        if ($key > 0) {
300
            // Если есть потомки
301
            if ($num_childs > 0) {
0 ignored issues
show
Bug introduced by
The variable $num_childs does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
302
                $ret .= '</ul>';
303
            }
304
            // Конец текущей записи
305
            $ret .= '</li>';
306
        }
307
    }
308
309
    // Находим предыдущую и следующую страницы.
310
    // Находим последнии страницы на каждом уровне.
311
    public function _makePagesUserCalc($key, $currpageid = 0, &$prevpages = [], &$nextpages = [], &$lastpageids = [], $level = 0)
312
    {
313
314
        // Сохраняем значение предыдущей страницы
315
        static $stat_prevpages;
316
317
        if ($key > 0) {
318
            // ID страницы
319
            $pageid = $this->tree[$key]['obj']->getVar('pageid');
320
            // Название страницы
321
            $pagetitle = $this->tree[$key]['obj']->getVar('title');
322
            // Тип страницы
323
            $pagetype = $this->tree[$key]['obj']->getVar('type');
324
325
            // Если мы передали ID текущей страницы, то находить предыдудую и следующую страницы
326
            // Не находить предыдущие и следующие для "Пустой страницы"
327
            if ($currpageid && $pagetype) {
328
                // Если элемент равен текущей странице
329
                if (isset($stat_prevpages) && ($currpageid == $pageid)) {
330
                    // Забиваем массив предыдущей страницы
331
                    $prevpages['pageid'] = $stat_prevpages['pageid'];
332
                    $prevpages['title']  = $stat_prevpages['title'];
333
334
                    // Если предыдущий равен текущей странице
335
                } elseif (isset($stat_prevpages) && ($currpageid == $stat_prevpages['pageid'])) {
336
                    // Забиваем массив следующей страницы
337
                    $nextpages['pageid'] = $pageid;
338
                    $nextpages['title']  = $pagetitle;
339
                }
340
                // Заносим текущие данные в массив предыдущей страницы
341
                $stat_prevpages['pageid'] = $pageid;
342
                $stat_prevpages['title']  = $pagetitle;
343
            }
344
345
            // Заносим текущую страницу в массив "последних страний"
346
            $lastpageids[$level] = $pageid;
347
348
            // Инкримент уровня
349
            $level++;
350
        }
351
352
        // Рекурсия
353 View Code Duplication
        if (isset($this->tree[$key]['child']) && !empty($this->tree[$key]['child'])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
354
            foreach ($this->tree[$key]['child'] as $childkey) {
355
                $this->_makePagesUserCalc($childkey, $currpageid, $prevpages, $nextpages, $lastpageids, $level);
356
            }
357
        }
358
    }
359
360
    //
361
362
    public function makePagesUser($currpageid = 0, &$prevpages = [], &$nextpages = [], $key = 0)
363
    {
364
365
        // Массив последней страницы на каждом уровне
366
        // level => pageid
367
        $lastpageids = [];
368
369
        // Расчёт
370
        $this->_makePagesUserCalc($key, $currpageid, $prevpages, $nextpages, $lastpageids);
371
372
        $ret = '<div onclick="instr_tree_toggle(arguments[0])">
373
<div>' . _MD_INSTRUCTION_LISTPAGES . '</div>
374
<div><ul class="InstrTreeContainer">';
375
376
        // Генерируем дерево
377
        $this->_makePagesUserTree($key, $ret, $currpageid, $lastpageids);
378
379
        $ret .= '</ul>
380
</div>';
381
382
        return $ret;
383
    }
384
}
385