GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.
Completed
Push — master ( cd2d3a...6886d6 )
by Robert
09:38
created

Menu::renderItem()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 17
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 17
rs 9.4285
c 0
b 0
f 0
ccs 11
cts 11
cp 1
cc 2
eloc 10
nc 2
nop 1
crap 2
1
<?php
2
/**
3
 * @link http://www.yiiframework.com/
4
 * @copyright Copyright (c) 2008 Yii Software LLC
5
 * @license http://www.yiiframework.com/license/
6
 */
7
8
namespace yii\widgets;
9
10
use Yii;
11
use yii\base\Widget;
12
use yii\helpers\ArrayHelper;
13
use yii\helpers\Url;
14
use yii\helpers\Html;
15
16
/**
17
 * Menu displays a multi-level menu using nested HTML lists.
18
 *
19
 * The main property of Menu is [[items]], which specifies the possible items in the menu.
20
 * A menu item can contain sub-items which specify the sub-menu under that menu item.
21
 *
22
 * Menu checks the current route and request parameters to toggle certain menu items
23
 * with active state.
24
 *
25
 * Note that Menu only renders the HTML tags about the menu. It does do any styling.
26
 * You are responsible to provide CSS styles to make it look like a real menu.
27
 *
28
 * The following example shows how to use Menu:
29
 *
30
 * ```php
31
 * echo Menu::widget([
32
 *     'items' => [
33
 *         // Important: you need to specify url as 'controller/action',
34
 *         // not just as 'controller' even if default action is used.
35
 *         ['label' => 'Home', 'url' => ['site/index']],
36
 *         // 'Products' menu item will be selected as long as the route is 'product/index'
37
 *         ['label' => 'Products', 'url' => ['product/index'], 'items' => [
38
 *             ['label' => 'New Arrivals', 'url' => ['product/index', 'tag' => 'new']],
39
 *             ['label' => 'Most Popular', 'url' => ['product/index', 'tag' => 'popular']],
40
 *         ]],
41
 *         ['label' => 'Login', 'url' => ['site/login'], 'visible' => Yii::$app->user->isGuest],
42
 *     ],
43
 * ]);
44
 * ```
45
 *
46
 * @author Qiang Xue <[email protected]>
47
 * @since 2.0
48
 */
49
class Menu extends Widget
50
{
51
    /**
52
     * @var array list of menu items. Each menu item should be an array of the following structure:
53
     *
54
     * - label: string, optional, specifies the menu item label. When [[encodeLabels]] is true, the label
55
     *   will be HTML-encoded. If the label is not specified, an empty string will be used.
56
     * - encode: boolean, optional, whether this item`s label should be HTML-encoded. This param will override
57
     *   global [[encodeLabels]] param.
58
     * - url: string or array, optional, specifies the URL of the menu item. It will be processed by [[Url::to]].
59
     *   When this is set, the actual menu item content will be generated using [[linkTemplate]];
60
     *   otherwise, [[labelTemplate]] will be used.
61
     * - visible: boolean, optional, whether this menu item is visible. Defaults to true.
62
     * - items: array, optional, specifies the sub-menu items. Its format is the same as the parent items.
63
     * - active: boolean, optional, whether this menu item is in active state (currently selected).
64
     *   If a menu item is active, its CSS class will be appended with [[activeCssClass]].
65
     *   If this option is not set, the menu item will be set active automatically when the current request
66
     *   is triggered by `url`. For more details, please refer to [[isItemActive()]].
67
     * - template: string, optional, the template used to render the content of this menu item.
68
     *   The token `{url}` will be replaced by the URL associated with this menu item,
69
     *   and the token `{label}` will be replaced by the label of the menu item.
70
     *   If this option is not set, [[linkTemplate]] or [[labelTemplate]] will be used instead.
71
     * - submenuTemplate: string, optional, the template used to render the list of sub-menus.
72
     *   The token `{items}` will be replaced with the rendered sub-menu items.
73
     *   If this option is not set, [[submenuTemplate]] will be used instead.
74
     * - options: array, optional, the HTML attributes for the menu container tag.
75
     */
76
    public $items = [];
77
    /**
78
     * @var array list of HTML attributes shared by all menu [[items]]. If any individual menu item
79
     * specifies its `options`, it will be merged with this property before being used to generate the HTML
80
     * attributes for the menu item tag. The following special options are recognized:
81
     *
82
     * - tag: string, defaults to "li", the tag name of the item container tags.
83
     *   Set to false to disable container tag.
84
     *   See also [[\yii\helpers\Html::tag()]].
85
     *
86
     * @see \yii\helpers\Html::renderTagAttributes() for details on how attributes are being rendered.
87
     */
88
    public $itemOptions = [];
89
    /**
90
     * @var string the template used to render the body of a menu which is a link.
91
     * In this template, the token `{url}` will be replaced with the corresponding link URL;
92
     * while `{label}` will be replaced with the link text.
93
     * This property will be overridden by the `template` option set in individual menu items via [[items]].
94
     */
95
    public $linkTemplate = '<a href="{url}">{label}</a>';
96
    /**
97
     * @var string the template used to render the body of a menu which is NOT a link.
98
     * In this template, the token `{label}` will be replaced with the label of the menu item.
99
     * This property will be overridden by the `template` option set in individual menu items via [[items]].
100
     */
101
    public $labelTemplate = '{label}';
102
    /**
103
     * @var string the template used to render a list of sub-menus.
104
     * In this template, the token `{items}` will be replaced with the rendered sub-menu items.
105
     */
106
    public $submenuTemplate = "\n<ul>\n{items}\n</ul>\n";
107
    /**
108
     * @var boolean whether the labels for menu items should be HTML-encoded.
109
     */
110
    public $encodeLabels = true;
111
    /**
112
     * @var string the CSS class to be appended to the active menu item.
113
     */
114
    public $activeCssClass = 'active';
115
    /**
116
     * @var boolean whether to automatically activate items according to whether their route setting
117
     * matches the currently requested route.
118
     * @see isItemActive()
119
     */
120
    public $activateItems = true;
121
    /**
122
     * @var boolean whether to activate parent menu items when one of the corresponding child menu items is active.
123
     * The activated parent menu items will also have its CSS classes appended with [[activeCssClass]].
124
     */
125
    public $activateParents = false;
126
    /**
127
     * @var boolean whether to hide empty menu items. An empty menu item is one whose `url` option is not
128
     * set and which has no visible child menu items.
129
     */
130
    public $hideEmptyItems = true;
131
    /**
132
     * @var array the HTML attributes for the menu's container tag. The following special options are recognized:
133
     *
134
     * - tag: string, defaults to "ul", the tag name of the item container tags. Set to false to disable container tag.
135
     *   See also [[\yii\helpers\Html::tag()]].
136
     *
137
     * @see \yii\helpers\Html::renderTagAttributes() for details on how attributes are being rendered.
138
     */
139
    public $options = [];
140
    /**
141
     * @var string the CSS class that will be assigned to the first item in the main menu or each submenu.
142
     * Defaults to null, meaning no such CSS class will be assigned.
143
     */
144
    public $firstItemCssClass;
145
    /**
146
     * @var string the CSS class that will be assigned to the last item in the main menu or each submenu.
147
     * Defaults to null, meaning no such CSS class will be assigned.
148
     */
149
    public $lastItemCssClass;
150
    /**
151
     * @var string the route used to determine if a menu item is active or not.
152
     * If not set, it will use the route of the current request.
153
     * @see params
154
     * @see isItemActive()
155
     */
156
    public $route;
157
    /**
158
     * @var array the parameters used to determine if a menu item is active or not.
159
     * If not set, it will use `$_GET`.
160
     * @see route
161
     * @see isItemActive()
162
     */
163
    public $params;
164
165
166
    /**
167
     * Renders the menu.
168
     */
169 4
    public function run()
170
    {
171 4
        if ($this->route === null && Yii::$app->controller !== null) {
172
            $this->route = Yii::$app->controller->getRoute();
173
        }
174 4
        if ($this->params === null) {
175 1
            $this->params = Yii::$app->request->getQueryParams();
176 1
        }
177 4
        $items = $this->normalizeItems($this->items, $hasActiveChild);
178 4
        if (!empty($items)) {
179 4
            $options = $this->options;
180 4
            $tag = ArrayHelper::remove($options, 'tag', 'ul');
181
182 4
            echo Html::tag($tag, $this->renderItems($items), $options);
183 4
        }
184 4
    }
185
186
    /**
187
     * Recursively renders the menu items (without the container tag).
188
     * @param array $items the menu items to be rendered recursively
189
     * @return string the rendering result
190
     */
191 4
    protected function renderItems($items)
192
    {
193 4
        $n = count($items);
194 4
        $lines = [];
195 4
        foreach ($items as $i => $item) {
196 4
            $options = array_merge($this->itemOptions, ArrayHelper::getValue($item, 'options', []));
197 4
            $tag = ArrayHelper::remove($options, 'tag', 'li');
198 4
            $class = [];
199 4
            if ($item['active']) {
200
                $class[] = $this->activeCssClass;
201
            }
202 4
            if ($i === 0 && $this->firstItemCssClass !== null) {
203
                $class[] = $this->firstItemCssClass;
204
            }
205 4
            if ($i === $n - 1 && $this->lastItemCssClass !== null) {
206
                $class[] = $this->lastItemCssClass;
207
            }
208 4
            if (!empty($class)) {
209
                if (empty($options['class'])) {
210
                    $options['class'] = implode(' ', $class);
211
                } else {
212
                    $options['class'] .= ' ' . implode(' ', $class);
213
                }
214
            }
215
216 4
            $menu = $this->renderItem($item);
217 4
            if (!empty($item['items'])) {
218
                $submenuTemplate = ArrayHelper::getValue($item, 'submenuTemplate', $this->submenuTemplate);
219
                $menu .= strtr($submenuTemplate, [
220
                    '{items}' => $this->renderItems($item['items']),
221
                ]);
222
            }
223 4
            $lines[] = Html::tag($tag, $menu, $options);
224 4
        }
225
226 4
        return implode("\n", $lines);
227
    }
228
229
    /**
230
     * Renders the content of a menu item.
231
     * Note that the container and the sub-menus are not rendered here.
232
     * @param array $item the menu item to be rendered. Please refer to [[items]] to see what data might be in the item.
233
     * @return string the rendering result
234
     */
235 4
    protected function renderItem($item)
236
    {
237 4
        if (isset($item['url'])) {
238 4
            $template = ArrayHelper::getValue($item, 'template', $this->linkTemplate);
239
240 4
            return strtr($template, [
241 4
                '{url}' => Html::encode(Url::to($item['url'])),
242 4
                '{label}' => $item['label'],
243 4
            ]);
244
        } else {
245 1
            $template = ArrayHelper::getValue($item, 'template', $this->labelTemplate);
246
247 1
            return strtr($template, [
248 1
                '{label}' => $item['label'],
249 1
            ]);
250
        }
251
    }
252
253
    /**
254
     * Normalizes the [[items]] property to remove invisible items and activate certain items.
255
     * @param array $items the items to be normalized.
256
     * @param boolean $active whether there is an active child menu item.
257
     * @return array the normalized menu items
258
     */
259 4
    protected function normalizeItems($items, &$active)
260
    {
261 4
        foreach ($items as $i => $item) {
262 4
            if (isset($item['visible']) && !$item['visible']) {
263
                unset($items[$i]);
264
                continue;
265
            }
266 4
            if (!isset($item['label'])) {
267
                $item['label'] = '';
268
            }
269 4
            $encodeLabel = isset($item['encode']) ? $item['encode'] : $this->encodeLabels;
270 4
            $items[$i]['label'] = $encodeLabel ? Html::encode($item['label']) : $item['label'];
271 4
            $hasActiveChild = false;
272 4
            if (isset($item['items'])) {
273
                $items[$i]['items'] = $this->normalizeItems($item['items'], $hasActiveChild);
274
                if (empty($items[$i]['items']) && $this->hideEmptyItems) {
275
                    unset($items[$i]['items']);
276
                    if (!isset($item['url'])) {
277
                        unset($items[$i]);
278
                        continue;
279
                    }
280
                }
281
            }
282 4
            if (!isset($item['active'])) {
283 4
                if ($this->activateParents && $hasActiveChild || $this->activateItems && $this->isItemActive($item)) {
284
                    $active = $items[$i]['active'] = true;
285
                } else {
286 4
                    $items[$i]['active'] = false;
287
                }
288 4
            } elseif ($item['active']) {
289
                $active = true;
290
            }
291 4
        }
292
293 4
        return array_values($items);
294
    }
295
296
    /**
297
     * Checks whether a menu item is active.
298
     * This is done by checking if [[route]] and [[params]] match that specified in the `url` option of the menu item.
299
     * When the `url` option of a menu item is specified in terms of an array, its first element is treated
300
     * as the route for the item and the rest of the elements are the associated parameters.
301
     * Only when its route and parameters match [[route]] and [[params]], respectively, will a menu item
302
     * be considered active.
303
     * @param array $item the menu item to be checked
304
     * @return boolean whether the menu item is active
305
     */
306 4
    protected function isItemActive($item)
307
    {
308 4
        if (isset($item['url']) && is_array($item['url']) && isset($item['url'][0])) {
309 1
            $route = Yii::getAlias($item['url'][0]);
310 1
            if ($route[0] !== '/' && Yii::$app->controller) {
311
                $route = Yii::$app->controller->module->getUniqueId() . '/' . $route;
312
            }
313 1
            if (ltrim($route, '/') !== $this->route) {
314 1
                return false;
315
            }
316
            unset($item['url']['#']);
317
            if (count($item['url']) > 1) {
318
                $params = $item['url'];
319
                unset($params[0]);
320
                foreach ($params as $name => $value) {
321
                    if ($value !== null && (!isset($this->params[$name]) || $this->params[$name] != $value)) {
322
                        return false;
323
                    }
324
                }
325
            }
326
327
            return true;
328
        }
329
330 3
        return false;
331
    }
332
}
333