Completed
Push — master ( af82e4...61317a )
by Dmitry
08:41 queued 07:25
created

Menu   A

Complexity

Total Complexity 38

Size/Duplication

Total Lines 165
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 5

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
wmc 38
lcom 1
cbo 5
dl 0
loc 165
ccs 0
cts 98
cp 0
rs 9.36
c 0
b 0
f 0

6 Methods

Rating   Name   Duplication   Size   Complexity  
A guessModule() 0 19 6
A getModuleName() 0 14 3
C renderItems() 0 38 12
B renderItem() 0 18 11
A iconClass() 0 4 2
A normalizeItems() 0 10 4
1
<?php
2
/**
3
 * Menus for Yii2.
4
 *
5
 * @link      https://github.com/hiqdev/yii2-menus
6
 * @package   yii2-menus
7
 * @license   BSD-3-Clause
8
 * @copyright Copyright (c) 2016-2017, HiQDev (http://hiqdev.com/)
9
 */
10
11
namespace hiqdev\yii2\menus\widgets;
12
13
use Closure;
14
use Yii;
15
use yii\helpers\ArrayHelper;
16
use yii\helpers\Html;
17
use yii\helpers\Url;
18
19
/**
20
 * Enhanced menu widget with icons, visible callback.
21
 */
22
class Menu extends \yii\widgets\Menu
23
{
24
    /**
25
     * @var string Class that will be added for parents "li"
26
     */
27
    public $treeClass = 'treeview';
28
29
    /**
30
     * @var boolean activate parents by default
31
     */
32
    public $activateParents = true;
33
34
    /**
35
     * @var string default icon class
36
     */
37
    public $defaultIcon = null;
38
39
    /**
40
     * {@inheritdoc}
41
     */
42
    public $linkTemplate = '<a href="{url}" {linkOptions}>{icon}{iconSpace}{label}</a>';
43
44
    /**
45
     * {@inheritdoc}
46
     */
47
    public $labelTemplate = '{icon}{iconSpace}{label}';
48
49
    /**
50
     * Try to guess which module is parent for current page
51
     * and remain sidebarmenu accordion opened.
52
     * @param array $item
53
     * @return bool
54
     */
55
    protected function guessModule(array $item, $parentUrl = null)
56
    {
57
        $result = false;
58
        $moduleId = Yii::$app->controller->module->id;
59
        $parentModuleId = $this->getModuleName($parentUrl);
60
        if (!empty($item['items'])) {
61
            foreach ($item['items'] as $i) {
62
                if (isset($i['url'])) {
63
                    $itemModuleName = $this->getModuleName(reset($i['url']));
64
                    if ($itemModuleName === $moduleId && $parentModuleId === $moduleId) {
65
                        $result = true;
66
                        break;
67
                    }
68
                }
69
            }
70
        }
71
72
        return $result;
73
    }
74
75
    /**
76
     * Get module id from url string.
77
     * @param $route (like '/dns/zone/index')
78
     * @return null|string (like 'dns')
79
     */
80
    private function getModuleName($route)
81
    {
82
        if ($route) {
83
            if (strpos($route, '/') !== false) {
84
                [$id] = explode('/', ltrim($route, '/'), 2);
0 ignored issues
show
Bug introduced by
The variable $id seems only to be defined at a later point. Did you maybe move this code here without moving the variable definition?

This error can happen if you refactor code and forget to move the variable initialization.

Let’s take a look at a simple example:

function someFunction() {
    $x = 5;
    echo $x;
}

The above code is perfectly fine. Now imagine that we re-order the statements:

function someFunction() {
    echo $x;
    $x = 5;
}

In that case, $x would be read before it is initialized. This was a very basic example, however the principle is the same for the found issue.

Loading history...
85
            } else {
86
                $id = $route;
87
            }
88
89
            return $id;
0 ignored issues
show
Bug introduced by
The variable $id 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...
90
        }
91
92
        return null;
93
    }
94
95
    /**
96
     * {@inheritdoc}
97
     */
98
    protected function renderItems($items)
99
    {
100
        $n = count($items);
101
        $lines = [];
102
        foreach ($items as $i => $item) {
103
            $options = array_merge($this->itemOptions, ArrayHelper::getValue($item, 'options', []));
104
            $tag = ArrayHelper::remove($options, 'tag', 'li');
105
            $class = [];
106
            $parentModuleUrl = isset($item['items']) ? $item : null;
107
            $isAccordionOpen = $this->guessModule($item, $parentModuleUrl['url'][0]);
108
            if ($item['active'] || $isAccordionOpen) {
109
                $class[] = $this->activeCssClass;
110
            }
111
            if ($i === 0 && $this->firstItemCssClass !== null) {
112
                $class[] = $this->firstItemCssClass;
113
            }
114
            if ($i === $n - 1 && $this->lastItemCssClass !== null) {
115
                $class[] = $this->lastItemCssClass;
116
            }
117
            $menu = $this->renderItem($item);
118
            if (!empty($item['items'])) {
119
                $class[] = $this->treeClass;
120
                $menu .= strtr($this->submenuTemplate, [
121
                    '{items}' => $this->renderItems($item['items']),
122
                ]);
123
            }
124
            if (!empty($class)) {
125
                if (empty($options['class'])) {
126
                    $options['class'] = implode(' ', $class);
127
                } else {
128
                    $options['class'] .= ' ' . implode(' ', $class);
129
                }
130
            }
131
            $lines[] = Html::tag($tag, $menu, $options);
132
        }
133
134
        return implode("\n", $lines);
135
    }
136
137
    /**
138
     * {@inheritdoc}
139
     *
140
     * @param array $item
141
     * Additional data might be in the item:
142
     * - isNew: boolean, optional, marks this item new and should be highlighted
143
     * - linkOptions: array, optional, the HTML attributes for the menu link tag
144
     * - icon: string, optional, https://fontawesome.com icon
145
     * - iconSpace: boolean, optional, added space after icon
146
     *
147
     * @return string
148
     */
149
    protected function renderItem($item)
150
    {
151
        $icon = $item['icon'] ?? null;
152
        $no_icon = $icon ? false : ($icon === false || empty($item['url']) || empty($this->defaultIcon));
153
154
        return strtr(ArrayHelper::getValue($item, 'template', isset($item['url']) ? $this->linkTemplate : $this->labelTemplate), [
155
            '{url}' => isset($item['url']) ? Url::to($item['url']) : null,
156
            '{icon}' => $no_icon ? '' : sprintf('<i class="%s"></i>', static::iconClass($icon ?: $this->defaultIcon)),
157
            '{iconSpace}' => $no_icon ? '' : '&nbsp;',
158
            '{label}' => $item['label'],
159
            '{arrow}' => sprintf(
160
                '<span class="pull-right-container">%s %s</span>',
161
                !empty($item['items']) ? '<small class="fa fa-angle-left pull-right "></small>' : '',
162
                ($item['isNew'] ?? false) ? '<small class="label pull-right bg-red">new</small>' : ''
163
            ),
164
            '{linkOptions}' => Html::renderTagAttributes(ArrayHelper::getValue($item, 'linkOptions', [])),
165
        ]);
166
    }
167
168
    public static function iconClass($icon)
169
    {
170
        return (strpos($icon, 'fa-') === 0 ? 'fa fa-fw ' : '') . $icon;
171
    }
172
173
    /**
174
     * {@inheritdoc}
175
     */
176
    protected function normalizeItems($items, &$active)
177
    {
178
        foreach ($items as &$item) {
179
            if (isset($item['visible']) && $item['visible'] instanceof Closure) {
180
                $item['visible'] = call_user_func($item['visible']);
181
            }
182
        }
183
184
        return parent::normalizeItems($items, $active);
185
    }
186
}
187