Passed
Push — master ( 566566...d0f53d )
by Alexander
02:18
created

Nav::renderItem()   B

Complexity

Conditions 10
Paths 38

Size

Total Lines 50
Code Lines 33

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 33
CRAP Score 10

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 10
eloc 33
c 1
b 0
f 0
nc 38
nop 1
dl 0
loc 50
ccs 33
cts 33
cp 1
crap 10
rs 7.6666

How to fix   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
3
declare(strict_types=1);
4
5
namespace Yiisoft\Yii\Bootstrap5;
6
7
use JsonException;
8
use RuntimeException;
9
use Yiisoft\Arrays\ArrayHelper;
10
use Yiisoft\Html\Html;
11
12
use function is_array;
13
use function is_string;
14
15
/**
16
 * Nav renders a nav HTML component.
17
 *
18
 * For example:
19
 *
20
 * ```php
21
 *    if ($user->getId() !== null) {
22
 *        $menuItems = [
23
 *            [
24
 *                'label' => 'About',
25
 *                'url' => '/about',
26
 *            ],
27
 *            [
28
 *                'label' => 'Contact',
29
 *                'url' => '/contact',
30
 *            ],
31
 *            [
32
 *                'label' => 'Logout' . ' ' . '(' . $user->getUsername() . ')',
33
 *                'url' => '/logout'
34
 *            ],
35
 *        ];
36
 *    } else {
37
 *        $menuItems = [
38
 *            [
39
 *                'label' => 'About',
40
 *                'url' => '/about',
41
 *            ],
42
 *            [
43
 *                'label' => 'Contact',
44
 *                'url' => '/contact',
45
 *            ],
46
 *            [
47
 *                'label' => 'Login',
48
 *                'url' => '/login',
49
 *            ],
50
 *        ];
51
 *    }
52
 *
53
 *    echo Nav::widget()
54
 *        ->currentPath($currentPath)
55
 *        ->items($menuItems)
56
 *        ->options([
57
 *            'class' => 'navbar-nav float-right ml-auto'
58
 *        ]);
59
 *
60
 * Note: Multilevel dropdowns beyond Level 1 are not supported in Bootstrap 3.
61
 * Note: $currentPath it must be injected from each controller to the main controller.
62
 *
63
 * SiteController.php
64
 *
65
 * ```php
66
 *
67
 *    public function index(ServerRequestInterface $request): ResponseInterface
68
 *    {
69
 *        $response = $this->responseFactory->createResponse();
70
 *        $currentPath = $request->getUri()->getPath();
71
 *        $output = $this->render('index', ['currentPath' => $currentPath]);
72
 *        $response->getBody()->write($output);
73
 *
74
 *        return $response;
75
 *    }
76
 * ```
77
 *
78
 * Controller.php
79
 *
80
 * ```php
81
 *    private function renderContent($content, array $parameters = []): string
82
 *    {
83
 *        $user = $this->user->getIdentity();
84
 *        $layout = $this->findLayoutFile($this->layout);
85
 *
86
 *        if ($layout !== null) {
87
 *            return $this->view->renderFile(
88
 *                $layout,
89
 *                    [
90
 *                        'aliases' => $this->aliases,
91
 *                        'content' => $content,
92
 *                        'user' => $user,
93
 *                        'params' => $this->params,
94
 *                        'currentPath' => !isset($parameters['currentPath']) ?: $parameters['currentPath']
95
 *                    ],
96
 *                $this
97
 *            );
98
 *        }
99
 *
100
 *        return $content;
101
 *    }
102
 * ```
103
 *
104
 * {@see http://getbootstrap.com/components/#dropdowns}
105
 * {@see http://getbootstrap.com/components/#nav}
106
 */
107
final class Nav extends Widget
108
{
109
    private array $items = [];
110
    private bool $encodeLabels = true;
111
    private bool $encodeTags = false;
112
    private bool $activateItems = true;
113
    private bool $activateParents = false;
114
    private string $currentPath = '';
115
    private string $dropdownClass = Dropdown::class;
116
    private array $options = [];
117
118 30
    protected function run(): string
119
    {
120 30
        if (!isset($this->options['id'])) {
121 15
            $this->options['id'] = "{$this->getId()}-nav";
122
        }
123
124
        /** @psalm-suppress InvalidArgument */
125 30
        Html::addCssClass($this->options, ['widget' => 'nav']);
126
127 30
        if ($this->encodeTags === false) {
128 29
            $this->options['encode'] = false;
129
        }
130
131 30
        return $this->renderItems();
132
    }
133
134
    /**
135
     * List of items in the nav widget. Each array element represents a single  menu item which can be either a string
136
     * or an array with the following structure:
137
     *
138
     * - label: string, required, the nav item label.
139
     * - url: optional, the item's URL. Defaults to "#".
140
     * - visible: bool, optional, whether this menu item is visible. Defaults to true.
141
     * - linkOptions: array, optional, the HTML attributes of the item's link.
142
     * - options: array, optional, the HTML attributes of the item container (LI).
143
     * - active: bool, optional, whether the item should be on active state or not.
144
     * - dropdownOptions: array, optional, the HTML options that will passed to the {@see Dropdown} widget.
145
     * - items: array|string, optional, the configuration array for creating a {@see Dropdown} widget, or a string
146
     *   representing the dropdown menu. Note that Bootstrap does not support sub-dropdown menus.
147
     * - encode: bool, optional, whether the label will be HTML-encoded. If set, supersedes the $encodeLabels option for
148
     *   only this item.
149
     *
150
     * If a menu item is a string, it will be rendered directly without HTML encoding.
151
     *
152
     * @param array $value
153
     *
154
     * @return $this
155
     */
156 30
    public function items(array $value): self
157
    {
158 30
        $new = clone $this;
159 30
        $new->items = $value;
160
161 30
        return $new;
162
    }
163
164
    /**
165
     * When tags Labels HTML should not be encoded.
166
     *
167
     * @return $this
168
     */
169 3
    public function withoutEncodeLabels(): self
170
    {
171 3
        $new = clone $this;
172 3
        $new->encodeLabels = false;
173
174 3
        return $new;
175
    }
176
177
    /**
178
     * Disable activate items according to whether their currentPath.
179
     *
180
     * @return $this
181
     *
182
     * {@see isItemActive}
183
     */
184 2
    public function withoutActivateItems(): self
185
    {
186 2
        $new = clone $this;
187 2
        $new->activateItems = false;
188
189 2
        return $new;
190
    }
191
192
    /**
193
     * Whether to activate parent menu items when one of the corresponding child menu items is active.
194
     *
195
     * @return $this
196
     */
197 1
    public function activateParents(): self
198
    {
199 1
        $new = clone $this;
200 1
        $new->activateParents = true;
201
202 1
        return $new;
203
    }
204
205
    /**
206
     * Allows you to assign the current path of the url from request controller.
207
     *
208
     * @param string $value
209
     *
210
     * @return $this
211
     */
212 2
    public function currentPath(string $value): self
213
    {
214 2
        $new = clone $this;
215 2
        $new->currentPath = $value;
216
217 2
        return $new;
218
    }
219
220
    /**
221
     * Name of a class to use for rendering dropdowns within this widget. Defaults to {@see Dropdown}.
222
     *
223
     * @param string $value
224
     *
225
     * @return $this
226
     */
227 16
    public function dropdownClass(string $value): self
228
    {
229 16
        $new = clone $this;
230 16
        $new->dropdownClass = $value;
231
232 16
        return $new;
233
    }
234
235
    /**
236
     * The HTML attributes for the widget container tag. The following special options are recognized.
237
     *
238
     * {@see Html::renderTagAttributes()} for details on how attributes are being rendered.
239
     *
240
     * @param array $value
241
     *
242
     * @return $this
243
     */
244 17
    public function options(array $value): self
245
    {
246 17
        $new = clone $this;
247 17
        $new->options = $value;
248
249 17
        return $new;
250
    }
251
252
    /**
253
     * Allows you to enable the encoding tags html.
254
     *
255
     * @return self
256
     */
257 1
    public function encodeTags(): self
258
    {
259 1
        $new = clone $this;
260 1
        $new->encodeTags = true;
261
262 1
        return $new;
263
    }
264
265
    /**
266
     * Renders widget items.
267
     *
268
     * @throws JsonException|RuntimeException
269
     *
270
     * @return string
271
     */
272 30
    private function renderItems(): string
273
    {
274 30
        $items = [];
275
276 30
        foreach ($this->items as $i => $item) {
277 29
            if (isset($item['visible']) && !$item['visible']) {
278 5
                continue;
279
            }
280
281 29
            $items[] = $this->renderItem($item);
282
        }
283
284 29
        return Html::tag('ul', implode("\n", $items), $this->options);
285
    }
286
287
    /**
288
     * Renders a widget's item.
289
     *
290
     * @param array|string $item the item to render.
291
     *
292
     * @throws JsonException|RuntimeException
293
     *
294
     * @return string the rendering result.
295
     */
296 29
    private function renderItem($item): string
297
    {
298 29
        if (is_string($item)) {
299 2
            return $item;
300
        }
301
302 29
        if (!isset($item['label'])) {
303 1
            throw new RuntimeException("The 'label' option is required.");
304
        }
305
306 28
        $encodeLabel = $item['encode'] ?? $this->encodeLabels;
307 28
        $label = $encodeLabel ? Html::encode($item['label']) : $item['label'];
308 28
        $options = ArrayHelper::getValue($item, 'options', []);
309 28
        $items = ArrayHelper::getValue($item, 'items');
310 28
        $url = ArrayHelper::getValue($item, 'url', '#');
311 28
        $linkOptions = ArrayHelper::getValue($item, 'linkOptions', []);
312 28
        $disabled = ArrayHelper::getValue($item, 'disabled', false);
313 28
        $active = $this->isItemActive($item);
314
315 28
        if (empty($items)) {
316 26
            $items = '';
317
        } else {
318 11
            $linkOptions['data-bs-toggle'] = 'dropdown';
319
320 11
            Html::addCssClass($options, ['widget' => 'dropdown']);
321 11
            Html::addCssClass($linkOptions, ['widget' => 'dropdown-toggle']);
322
323 11
            if (is_array($items)) {
324 11
                $items = $this->isChildActive($items, $active);
325 11
                $items = $this->renderDropdown($items, $item);
326
            }
327
        }
328
329 28
        Html::addCssClass($options, ['nav' => 'nav-item']);
330 28
        Html::addCssClass($linkOptions, ['linkOptions' => 'nav-link']);
331
332 28
        if ($disabled) {
333 3
            $linkOptions['tabindex'] = '-1';
334 3
            $linkOptions['aria-disabled'] = 'true';
335 3
            Html::addCssClass($linkOptions, ['disabled' => 'disabled']);
336 28
        } elseif ($this->activateItems && $active) {
337 16
            Html::addCssClass($linkOptions, ['active' => 'active']);
338
        }
339
340 28
        if ($this->encodeTags === false) {
341 27
            $linkOptions['encode'] = false;
342 27
            $options['encode'] = false;
343
        }
344
345 28
        return Html::tag('li', Html::a($label, $url, $linkOptions) . $items, $options);
346
    }
347
348
    /**
349
     * Renders the given items as a dropdown.
350
     *
351
     * This method is called to create sub-menus.
352
     *
353
     * @param array $items the given items. Please refer to {@see Dropdown::items} for the array structure.
354
     * @param array $parentItem the parent item information. Please refer to {@see items} for the structure of this
355
     * array.
356
     *
357
     * @return string the rendering result.
358
     */
359 11
    private function renderDropdown(array $items, array $parentItem): string
360
    {
361 11
        $dropdownClass = $this->dropdownClass;
362
363 11
        $dropdown = $dropdownClass::widget()
364 11
            ->items($items)
365 11
            ->options(ArrayHelper::getValue($parentItem, 'dropdownOptions', []));
366
367 11
        if ($this->encodeLabels === false) {
368 1
            $dropdown->withoutEncodeLabels();
369
        }
370
371 11
        return $dropdown->render();
372
    }
373
374
    /**
375
     * Check to see if a child item is active optionally activating the parent.
376
     *
377
     * @param array $items
378
     * @param bool $active should the parent be active too
379
     *
380
     * @return array
381
     *
382
     * {@see items}
383
     */
384 11
    private function isChildActive(array $items, bool &$active): array
385
    {
386 11
        foreach ($items as $i => $child) {
387 11
            if ($this->isItemActive($child)) {
388 3
                ArrayHelper::setValue($items[$i], 'active', true);
389 3
                if ($this->activateParents) {
390 1
                    $active = true;
391
                }
392
            }
393
394 11
            if (is_array($child) && ($childItems = ArrayHelper::getValue($child, 'items')) && is_array($childItems)) {
395 1
                $activeParent = false;
396 1
                $items[$i]['items'] = $this->isChildActive($childItems, $activeParent);
397
398 1
                if ($activeParent) {
399 1
                    $items[$i]['options'] ??= [];
400 1
                    Html::addCssClass($items[$i]['options'], ['active' => 'active']);
401 1
                    $active = true;
402
                }
403
            }
404
        }
405
406 11
        return $items;
407
    }
408
409
    /**
410
     * Checks whether a menu item is active.
411
     *
412
     * This is done by checking if {@see currentPath} match that specified in the `url` option of the menu item. When
413
     * the `url` option of a menu item is specified in terms of an array, its first element is treated as the
414
     * currentPath for the item and the rest of the elements are the associated parameters. Only when its currentPath
415
     * and parameters match {@see currentPath}, respectively, will a menu item be considered active.
416
     *
417
     * @param array|string $item the menu item to be checked
418
     *
419
     * @return bool whether the menu item is active
420
     */
421 28
    private function isItemActive($item): bool
422
    {
423 28
        if (isset($item['active'])) {
424 19
            return ArrayHelper::getValue($item, 'active', false);
0 ignored issues
show
Bug introduced by
It seems like $item can also be of type string; however, parameter $array of Yiisoft\Arrays\ArrayHelper::getValue() does only seem to accept array|object, maybe add an additional type check? ( Ignorable by Annotation )

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

424
            return ArrayHelper::getValue(/** @scrutinizer ignore-type */ $item, 'active', false);
Loading history...
425
        }
426
427 23
        return isset($item['url']) && $this->currentPath !== '/' && $item['url'] === $this->currentPath && $this->activateItems;
428
    }
429
}
430