Issues (17)

src/Nav.php (1 issue)

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