Passed
Push — master ( b9481c...f3ee08 )
by Alexander
22:53 queued 11:45
created

Nav::dropdownOptions()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 3
nc 1
nop 1
dl 0
loc 6
ccs 4
cts 4
cp 1
crap 1
rs 10
c 0
b 0
f 0
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 $activeClass = null;
115
    private string $currentPath = '';
116
    private string $dropdownClass = Dropdown::class;
117
    private array $options = [];
118
    private array $itemOptions = [];
119
    private array $linkOptions = [];
120
    private array $dropdownOptions = [];
121
122 32
    protected function run(): string
123
    {
124 32
        if (!isset($this->options['id'])) {
125 18
            $this->options['id'] = "{$this->getId()}-nav";
126
        }
127
128 32
        Html::addCssClass($this->options, ['widget' => 'nav']);
129
130 32
        return $this->renderItems();
131
    }
132
133
    /**
134
     * List of items in the nav widget. Each array element represents a single  menu item which can be either a string
135
     * or an array with the following structure:
136
     *
137
     * - label: string, required, the nav item label.
138
     * - url: optional, the item's URL. Defaults to "#".
139
     * - visible: bool, optional, whether this menu item is visible. Defaults to true.
140
     * - linkOptions: array, optional, the HTML attributes of the item's link.
141
     * - options: array, optional, the HTML attributes of the item container (LI).
142
     * - active: bool, optional, whether the item should be on active state or not.
143
     * - dropdownOptions: array, optional, the HTML options that will passed to the {@see Dropdown} widget.
144
     * - items: array|string, optional, the configuration array for creating a {@see Dropdown} widget, or a string
145
     *   representing the dropdown menu. Note that Bootstrap does not support sub-dropdown menus.
146
     * - encode: bool, optional, whether the label will be HTML-encoded. If set, supersedes the $encodeLabels option for
147
     *   only this item.
148
     *
149
     * If a menu item is a string, it will be rendered directly without HTML encoding.
150
     *
151
     * @param array $value
152
     *
153
     * @return self
154
     */
155 32
    public function items(array $value): self
156
    {
157 32
        $new = clone $this;
158 32
        $new->items = $value;
159
160 32
        return $new;
161
    }
162
163
    /**
164
     * When tags Labels HTML should not be encoded.
165
     *
166
     * @return self
167
     */
168 3
    public function withoutEncodeLabels(): self
169
    {
170 3
        $new = clone $this;
171 3
        $new->encodeLabels = false;
172
173 3
        return $new;
174
    }
175
176
    /**
177
     * Disable activate items according to whether their currentPath.
178
     *
179
     * @return self
180
     *
181
     * {@see isItemActive}
182
     */
183 2
    public function withoutActivateItems(): self
184
    {
185 2
        $new = clone $this;
186 2
        $new->activateItems = false;
187
188 2
        return $new;
189
    }
190
191
    /**
192
     * Whether to activate parent menu items when one of the corresponding child menu items is active.
193
     *
194
     * @return self
195
     */
196 1
    public function activateParents(): self
197
    {
198 1
        $new = clone $this;
199 1
        $new->activateParents = true;
200
201 1
        return $new;
202
    }
203
204
    /**
205
     * Additional CSS class for active item. Like "bg-success", "bg-primary" etc
206
     *
207
     * @param string|null $className
208
     *
209
     * @return self
210
     */
211 1
    public function activeClass(?string $className): self
212
    {
213 1
        if ($this->activeClass === $className) {
214
            return $this;
215
        }
216
217 1
        $new = clone $this;
218 1
        $new->activeClass = $className;
219
220 1
        return $new;
221
    }
222
223
    /**
224
     * Allows you to assign the current path of the url from request controller.
225
     *
226
     * @param string $value
227
     *
228
     * @return self
229
     */
230 2
    public function currentPath(string $value): self
231
    {
232 2
        $new = clone $this;
233 2
        $new->currentPath = $value;
234
235 2
        return $new;
236
    }
237
238
    /**
239
     * Name of a class to use for rendering dropdowns within this widget. Defaults to {@see Dropdown}.
240
     *
241
     * @param string $value
242
     *
243
     * @return self
244
     */
245 15
    public function dropdownClass(string $value): self
246
    {
247 15
        $new = clone $this;
248 15
        $new->dropdownClass = $value;
249
250 15
        return $new;
251
    }
252
253
    /**
254
     * Options for dropdownClass if not present in current item
255
     *
256
     * {@see Nav::renderDropdown()} for details on how this options will be used
257
     *
258
     * @param array $options
259
     *
260
     * @return self
261
     */
262 1
    public function dropdownOptions(array $options): self
263
    {
264 1
        $new = clone $this;
265 1
        $new->dropdownOptions = $options;
266
267 1
        return $new;
268
    }
269
270
    /**
271
     * The HTML attributes for the widget container tag. The following special options are recognized.
272
     *
273
     * {@see Html::renderTagAttributes()} for details on how attributes are being rendered.
274
     *
275
     * @param array $value
276
     *
277
     * @return self
278
     */
279 16
    public function options(array $value): self
280
    {
281 16
        $new = clone $this;
282 16
        $new->options = $value;
283
284 16
        return $new;
285
    }
286
287
    /**
288
     * Options for each item if not present in self
289
     *
290
     * @param array $options
291
     *
292
     * @return self
293
     */
294 1
    public function itemOptions(array $options): self
295
    {
296 1
        $new = clone $this;
297 1
        $new->itemOptions = $options;
298
299 1
        return $new;
300
    }
301
302
    /**
303
     * Options for each item link if not present in current item
304
     *
305
     * @param array $options
306
     *
307
     * @return self
308
     */
309 1
    public function linkOptions(array $options): self
310
    {
311 1
        $new = clone $this;
312 1
        $new->linkOptions = $options;
313
314 1
        return $new;
315
    }
316
317
    /**
318
     * Renders widget items.
319
     *
320
     * @throws JsonException|RuntimeException
321
     *
322
     * @return string
323
     */
324 32
    private function renderItems(): string
325
    {
326 32
        $items = [];
327
328 32
        foreach ($this->items as $i => $item) {
329 31
            if (isset($item['visible']) && !$item['visible']) {
330 5
                continue;
331
            }
332
333 31
            $items[] = $this->renderItem($item);
334
        }
335
336 31
        return Html::tag('ul', implode("\n", $items), $this->options)
337 31
            ->encode($this->encodeTags)
338 31
            ->render();
339
    }
340
341
    /**
342
     * Renders a widget's item.
343
     *
344
     * @param array|string $item the item to render.
345
     *
346
     * @throws JsonException|RuntimeException
347
     *
348
     * @return string the rendering result.
349
     */
350 31
    private function renderItem($item): string
351
    {
352 31
        if (is_string($item)) {
353 2
            return $item;
354
        }
355
356 31
        if (!isset($item['label'])) {
357 1
            throw new RuntimeException("The 'label' option is required.");
358
        }
359
360 30
        $encodeLabel = $item['encode'] ?? $this->encodeLabels;
361 30
        $label = $encodeLabel ? Html::encode($item['label']) : $item['label'];
362 30
        $options = ArrayHelper::getValue($item, 'options', $this->itemOptions);
363 30
        $items = ArrayHelper::getValue($item, 'items');
364 30
        $url = ArrayHelper::getValue($item, 'url', '#');
365 30
        $linkOptions = ArrayHelper::getValue($item, 'linkOptions', $this->linkOptions);
366 30
        $disabled = ArrayHelper::getValue($item, 'disabled', false);
367 30
        $active = $this->isItemActive($item);
368
369 30
        if (empty($items)) {
370 24
            $items = '';
371
        } else {
372 15
            $linkOptions['data-bs-toggle'] = 'dropdown';
373
374 15
            Html::addCssClass($options, ['widget' => 'dropdown']);
375 15
            Html::addCssClass($linkOptions, ['widget' => 'dropdown-toggle']);
376
377 15
            if (is_array($items)) {
378 15
                $items = $this->isChildActive($items, $active);
379 15
                $items = $this->renderDropdown($items, $item);
380
            }
381
        }
382
383 30
        Html::addCssClass($options, ['nav' => 'nav-item']);
384 30
        Html::addCssClass($linkOptions, ['linkOptions' => 'nav-link']);
385
386 30
        if ($disabled) {
387 3
            $linkOptions['tabindex'] = '-1';
388 3
            $linkOptions['aria-disabled'] = 'true';
389 3
            Html::addCssClass($linkOptions, ['disabled' => 'disabled']);
390 30
        } elseif ($this->activateItems && $active) {
391 16
            Html::addCssClass($linkOptions, ['active' => rtrim('active ' . $this->activeClass)]);
392
        }
393
394 30
        return Html::tag(
395 30
            'li',
396 30
            Html::a($label, $url, $linkOptions)->encode($this->encodeTags) . $items,
397 30
            $options
398 30
        )->encode($this->encodeTags)->render();
399
    }
400
401
    /**
402
     * Renders the given items as a dropdown.
403
     *
404
     * This method is called to create sub-menus.
405
     *
406
     * @param array $items the given items. Please refer to {@see Dropdown::items} for the array structure.
407
     * @param array $parentItem the parent item information. Please refer to {@see items} for the structure of this
408
     * array.
409
     *
410
     * @return string the rendering result.
411
     */
412 15
    private function renderDropdown(array $items, array $parentItem): string
413
    {
414 15
        $dropdownClass = $this->dropdownClass;
415
416 15
        $dropdown = $dropdownClass::widget()
417 15
            ->items($items)
418 15
            ->options(ArrayHelper::getValue($parentItem, 'dropdownOptions', $this->dropdownOptions));
419
420 15
        if ($this->encodeLabels === false) {
421 1
            $dropdown->withoutEncodeLabels();
422
        }
423
424 15
        return $dropdown->render();
425
    }
426
427
    /**
428
     * Check to see if a child item is active optionally activating the parent.
429
     *
430
     * @param array $items
431
     * @param bool $active should the parent be active too
432
     *
433
     * @return array
434
     *
435
     * {@see items}
436
     */
437 15
    private function isChildActive(array $items, bool &$active): array
438
    {
439 15
        foreach ($items as $i => $child) {
440 15
            if ($this->isItemActive($child)) {
441 3
                ArrayHelper::setValue($items[$i], 'active', true);
442 3
                if ($this->activateParents) {
443 1
                    $active = true;
444
                }
445
            }
446
447 15
            if (is_array($child) && ($childItems = ArrayHelper::getValue($child, 'items')) && is_array($childItems)) {
448 1
                $activeParent = false;
449 1
                $items[$i]['items'] = $this->isChildActive($childItems, $activeParent);
450
451 1
                if ($activeParent) {
452 1
                    $items[$i]['options'] ??= [];
453 1
                    Html::addCssClass($items[$i]['options'], ['active' => 'active']);
454 1
                    $active = true;
455
                }
456
            }
457
        }
458
459 15
        return $items;
460
    }
461
462
    /**
463
     * Checks whether a menu item is active.
464
     *
465
     * This is done by checking if {@see currentPath} match that specified in the `url` option of the menu item. When
466
     * the `url` option of a menu item is specified in terms of an array, its first element is treated as the
467
     * currentPath for the item and the rest of the elements are the associated parameters. Only when its currentPath
468
     * and parameters match {@see currentPath}, respectively, will a menu item be considered active.
469
     *
470
     * @param array|string $item the menu item to be checked
471
     *
472
     * @return bool whether the menu item is active
473
     */
474 30
    private function isItemActive($item): bool
475
    {
476 30
        if (isset($item['active'])) {
477 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

477
            return ArrayHelper::getValue(/** @scrutinizer ignore-type */ $item, 'active', false);
Loading history...
478
        }
479
480 26
        return isset($item['url'])
481 26
            && $this->currentPath !== '/'
482 26
            && $item['url'] === $this->currentPath
483 26
            && $this->activateItems;
484
    }
485
}
486