Passed
Pull Request — master (#62)
by
unknown
14:13 queued 10s
created

Nav::linkOptions()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

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

437
            return ArrayHelper::getValue(/** @scrutinizer ignore-type */ $item, 'active', false);
Loading history...
438
        }
439
440 22
        return isset($item['url'])
441 22
            && $this->currentPath !== '/'
442 22
            && $item['url'] === $this->currentPath
443 22
            && $this->activateItems;
444
    }
445
}
446