Passed
Push — master ( 2301b1...386ec7 )
by Alexander
14:22 queued 11:36
created

Nav::render()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2

Importance

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