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

NavBar::render()   A

Complexity

Conditions 4
Paths 6

Size

Total Lines 20
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 4

Importance

Changes 0
Metric Value
cc 4
eloc 11
nc 6
nop 0
dl 0
loc 20
ccs 12
cts 12
cp 1
crap 4
rs 9.9
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Yii\Bootstrap5;
6
7
use Stringable;
8
use JsonException;
9
use Yiisoft\Arrays\ArrayHelper;
10
use Yiisoft\Html\Html;
11
12
/**
13
 * NavBar renders a navbar HTML component.
14
 *
15
 * Any content enclosed between the {@see begin()} and {@see end()} calls of NavBar is treated as the content of the
16
 * navbar. You may use widgets such as {@see Nav} or {@see \Yiisoft\Widget\Menu} to build up such content. For example,
17
 *
18
 * ```php
19
 *    if ($user->getId() !== null) {
20
 *        $menuItems = [
21
 *            [
22
 *                'label' => 'About',
23
 *                'url' => '/about',
24
 *            ],
25
 *            [
26
 *                'label' => 'Contact',
27
 *                'url' => '/contact',
28
 *            ],
29
 *            [
30
 *                'label' => 'Logout' . ' ' . '(' . $user->getUsername() . ')',
31
 *                'url' => '/logout'
32
 *            ],
33
 *        ];
34
 *    } else {
35
 *        $menuItems = [
36
 *            [
37
 *                'label' => 'About',
38
 *                'url' => '/about',
39
 *            ],
40
 *            [
41
 *                'label' => 'Contact',
42
 *                'url' => '/contact',
43
 *            ],
44
 *            [
45
 *                'label' => 'Login',
46
 *                'url' => '/login',
47
 *            ],
48
 *        ];
49
 *    }
50
 *
51
 *    <?= NavBar::widget()
52
 *        ->brandText('My Application Basic')
53
 *        ->brandUrl('/')
54
 *        ->options([
55
 *            'class' => 'navbar navbar-dark bg-dark navbar-expand-lg text-white',
56
 *        ])
57
 *        ->begin();
58
 *
59
 *        echo Nav::widget()
60
 *            ->currentPath($currentPath)
61
 *            ->items($menuItems)
62
 *            ->options([
63
 *                'class' => 'navbar-nav float-right ml-auto'
64
 *            ]);
65
 *
66
 *    echo NavBar::end(); ?>
67
 * ```
68
 * Note: $currentPath it must be injected from each controller to the main controller.
69
 *
70
 * SiteController.php
71
 *
72
 * ```php
73
 *
74
 *    public function index(ServerRequestInterface $request): ResponseInterface
75
 *    {
76
 *        $response = $this->responseFactory->createResponse();
77
 *        $currentPath = $request
78
 *            ->getUri()
79
 *            ->getPath();
80
 *        $output = $this->render('index', ['currentPath' => $currentPath]);
81
 *        $response
82
 *            ->getBody()
83
 *            ->write($output);
84
 *
85
 *        return $response;
86
 *    }
87
 * ```
88
 *
89
 * Controller.php
90
 *
91
 * ```php
92
 *    private function renderContent($content, array $parameters = []): string
93
 *    {
94
 *        $user = $this->user->getIdentity();
95
 *        $layout = $this->findLayoutFile($this->layout);
96
 *
97
 *        if ($layout !== null) {
98
 *            return $this->view->renderFile(
99
 *                $layout,
100
 *                    [
101
 *                        'aliases' => $this->aliases,
102
 *                        'content' => $content,
103
 *                        'user' => $user,
104
 *                        'params' => $this->params,
105
 *                        'currentPath' => !isset($parameters['currentPath']) ?: $parameters['currentPath']
106
 *                    ],
107
 *                $this
108
 *            );
109
 *        }
110
 *
111
 *        return $content;
112
 *    }
113
 * ```
114
 */
115
final class NavBar extends Widget
116
{
117
    public const EXPAND_SM = 'navbar-expand-sm';
118
    public const EXPAND_MD = 'navbar-expand-md';
119
    public const EXPAND_LG = 'navbar-expand-lg';
120
    public const EXPAND_XL = 'navbar-expand-xl';
121
    public const EXPAND_XXL = 'navbar-expand-xxl';
122
123
    public const THEME_LIGHT = 'navbar-light';
124
    public const THEME_DARK = 'navbar-dark';
125
126
    private array $collapseOptions = [];
127
    private ?string $brandText = null;
128
    private ?string $brandImage = null;
129
    private array $brandImageAttributes = [];
130
    private ?string $brandUrl = '/';
131
    private array $brandOptions = [];
132
    private string $screenReaderToggleText = 'Toggle navigation';
133
    private string $togglerContent = '<span class="navbar-toggler-icon"></span>';
134
    private array $togglerOptions = [];
135
    private bool $renderInnerContainer = true;
136
    private array $innerContainerOptions = [];
137
    private array $options = [];
138
    private bool $encodeTags = false;
139
    private ?string $expandSize = self::EXPAND_LG;
140
    private ?string $theme = self::THEME_LIGHT;
141
    private ?Offcanvas $offcanvas = null;
142
143 20
    public function getId(?string $suffix = '-navbar'): ?string
144
    {
145 20
        return $this->options['id'] ?? parent::getId($suffix);
146
    }
147
148 20
    public function begin(): string
149
    {
150
        /** Run Offcanvas::begin before NavBar parent::begin for right stack order */
151 20
        $offcanvas = $this->offcanvas ? $this->offcanvas->begin() : null;
152
153 20
        parent::begin();
154
155 20
        $options = $this->options;
156 20
        $options['id'] = $this->getId();
157 20
        $navTag = ArrayHelper::remove($options, 'tag', 'nav');
158 20
        $classNames = ['widget' => 'navbar'];
159
160 20
        if ($this->expandSize) {
161 17
            $classNames['size'] = $this->expandSize;
162
        }
163
164 20
        if ($this->theme) {
165 19
            $classNames['theme'] = $this->theme;
166
        }
167
168 20
        Html::addCssClass($options, $classNames);
169
170 20
        if (!isset($this->innerContainerOptions['class'])) {
171 18
            Html::addCssClass($this->innerContainerOptions, ['innerContainerOptions' => 'container']);
172
        }
173
174 20
        $htmlStart = Html::openTag($navTag, $options);
175
176 20
        if ($this->renderInnerContainer) {
177 19
            $htmlStart .= Html::openTag('div', $this->innerContainerOptions);
178
        }
179
180 20
        $htmlStart .= $this->renderBrand();
181
182 20
        if ($offcanvas) {
183 2
            $offcanvasId = $this->offcanvas ? $this->offcanvas->getId() : null;
184 2
            $htmlStart .= $this->renderToggleButton($offcanvasId);
185 2
            $htmlStart .= $offcanvas;
186 18
        } elseif ($this->expandSize) {
187 16
            $collapseOptions = $this->collapseOptions;
188 16
            $collapseTag = ArrayHelper::remove($collapseOptions, 'tag', 'div');
189
190 16
            if (!isset($collapseOptions['id'])) {
191 16
                $collapseOptions['id'] = $options['id'] . '-collapse';
192
            }
193
194 16
            Html::addCssClass($collapseOptions, ['collapse' => 'collapse', 'widget' => 'navbar-collapse']);
195
196 16
            $htmlStart .= $this->renderToggleButton($collapseOptions['id']);
197 16
            $htmlStart .= Html::openTag($collapseTag, $collapseOptions);
198 2
        } elseif ($this->togglerOptions) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->togglerOptions of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
199 1
            $htmlStart .= $this->renderToggleButton(null);
200
        }
201
202 20
        return $htmlStart;
203
    }
204
205 20
    public function render(): string
206
    {
207 20
        $htmlRun = '';
208
209 20
        if ($this->offcanvas) {
210 2
            $htmlRun = $this->offcanvas::end();
211 18
        } elseif ($this->expandSize) {
212 16
            $tag = ArrayHelper::getValue($this->collapseOptions, 'tag', 'div');
213 16
            $htmlRun = Html::closeTag($tag);
214
        }
215
216 20
        if ($this->renderInnerContainer) {
217 19
            $htmlRun .= Html::closeTag('div');
218
        }
219
220 20
        $tag = ArrayHelper::getValue($this->options, 'tag', 'nav');
221
222 20
        $htmlRun .= Html::closeTag($tag);
223
224 20
        return $htmlRun;
225
    }
226
227
    /**
228
     * Set size before then content will be expanded
229
     */
230 5
    public function expandSize(?string $size): self
231
    {
232 5
        $new = clone $this;
233 5
        $new->expandSize = $size;
234
235 5
        return $new;
236
    }
237
238
    /**
239
     * Set color theme for NavBar
240
     */
241 2
    public function theme(?string $theme): self
242
    {
243 2
        $new = clone $this;
244 2
        $new->theme = $theme;
245
246 2
        return $new;
247
    }
248
249
    /**
250
     * Short method for light navbar theme
251
     */
252
    public function light(): self
253
    {
254
        return $this->theme(self::THEME_LIGHT);
255
    }
256
257
    /**
258
     * Short method for dark navbar theme
259
     */
260
    public function dark(): self
261
    {
262
        return $this->theme(self::THEME_DARK);
263
    }
264
265
    /**
266
     * The HTML attributes for the container tag. The following special options are recognized.
267
     *
268
     * @param array $value
269
     *
270
     * {@see Html::renderTagAttributes()} for details on how attributes are being rendered.
271
     */
272 1
    public function collapseOptions(array $value): self
273
    {
274 1
        $new = clone $this;
275 1
        $new->collapseOptions = $value;
276
277 1
        return $new;
278
    }
279
280
    /**
281
     * Set/remove Offcanvas::widget instead of collapse
282
     */
283 2
    public function offcanvas(?Offcanvas $offcanvas): self
284
    {
285 2
        $new = clone $this;
286 2
        $new->offcanvas = $offcanvas;
287
288 2
        return $new;
289
    }
290
291
    /**
292
     * The text of the brand or empty if it's not used. Note that this is not HTML-encoded.
293
     *
294
     * @link https://getbootstrap.com/docs/5.0/components/navbar/#text
295
     */
296 7
    public function brandText(?string $value): self
297
    {
298 7
        $new = clone $this;
299 7
        $new->brandText = $value;
300
301 7
        return $new;
302
    }
303
304
    /**
305
     * Src of the brand image or empty if it's not used. Note that this param will override `$this->brandText` param.
306
     *
307
     * @link https://getbootstrap.com/docs/5.0/components/navbar/#image
308
     */
309 3
    public function brandImage(?string $value): self
310
    {
311 3
        $new = clone $this;
312 3
        $new->brandImage = $value;
313
314 3
        return $new;
315
    }
316
317
    /**
318
     * Set attributes for brandImage
319
     *
320
     * {@see Html::renderTagAttributes()} for details on how attributes are being rendered.
321
     *
322
     * @param array $attributes
323
     */
324 1
    public function brandImageAttributes(array $attributes): self
325
    {
326 1
        $new = clone $this;
327 1
        $new->brandImageAttributes = $attributes;
328
329 1
        return $new;
330
    }
331
332
    /**
333
     * The URL for the brand's hyperlink tag and will be used for the "href" attribute of the brand link. Default value
334
     * is "/". You may set it to empty string if you want no link at all.
335
     *
336
     * @link https://getbootstrap.com/docs/5.0/components/navbar/#text
337
     */
338 6
    public function brandUrl(?string $value): self
339
    {
340 6
        $new = clone $this;
341 6
        $new->brandUrl = $value;
342
343 6
        return $new;
344
    }
345
346
    /**
347
     * The HTML attributes of the brand link.
348
     *
349
     * {@see Html::renderTagAttributes()} for details on how attributes are being rendered.
350
     *
351
     * @param array $value
352
     */
353 1
    public function brandOptions(array $value): self
354
    {
355 1
        $new = clone $this;
356 1
        $new->brandOptions = $value;
357
358 1
        return $new;
359
    }
360
361
    /**
362
     * Text to show for screen readers for the button to toggle the navbar.
363
     */
364 1
    public function screenReaderToggleText(string $value): self
365
    {
366 1
        $new = clone $this;
367 1
        $new->screenReaderToggleText = $value;
368
369 1
        return $new;
370
    }
371
372
    /**
373
     * The toggle button content. Defaults to bootstrap 4 default `<span class="navbar-toggler-icon"></span>`.
374
     */
375 1
    public function togglerContent(string $value): self
376
    {
377 1
        $new = clone $this;
378 1
        $new->togglerContent = $value;
379
380 1
        return $new;
381
    }
382
383
    /**
384
     * The HTML attributes of the navbar toggler button.
385
     *
386
     * {@see Html::renderTagAttributes()} for details on how attributes are being rendered.
387
     *
388
     * @param array $value
389
     */
390 2
    public function togglerOptions(array $value): self
391
    {
392 2
        $new = clone $this;
393 2
        $new->togglerOptions = $value;
394
395 2
        return $new;
396
    }
397
398
    /**
399
     * This for a 100% width navbar.
400
     */
401 1
    public function withoutRenderInnerContainer(): self
402
    {
403 1
        $new = clone $this;
404 1
        $new->renderInnerContainer = false;
405
406 1
        return $new;
407
    }
408
409
    /**
410
     * The HTML attributes of the inner container.
411
     *
412
     * {@see Html::renderTagAttributes()} for details on how attributes are being rendered.
413
     *
414
     * @param array $value
415
     */
416 2
    public function innerContainerOptions(array $value): self
417
    {
418 2
        $new = clone $this;
419 2
        $new->innerContainerOptions = $value;
420
421 2
        return $new;
422
    }
423
424
    /**
425
     * The HTML attributes for the widget container tag. The following special options are recognized.
426
     *
427
     * {@see Html::renderTagAttributes()} for details on how attributes are being rendered.
428
     *
429
     * @param array $value
430
     */
431 3
    public function options(array $value): self
432
    {
433 3
        $new = clone $this;
434 3
        $new->options = $value;
435
436 3
        return $new;
437
    }
438
439 20
    private function renderBrand(): string
440
    {
441 20
        if (empty($this->brandImage) && empty($this->brandText)) {
442 11
            return '';
443
        }
444
445 9
        $content = '';
446 9
        $options = $this->brandOptions;
447 9
        $encode = ArrayHelper::remove($options, 'encode', $this->encodeTags);
448
449 9
        Html::addCssClass($options, ['widget' => 'navbar-brand']);
450
451 9
        if (!empty($this->brandImage)) {
452 3
            $encode = false;
453 3
            $content = Html::img($this->brandImage)->addAttributes($this->brandImageAttributes);
454
        }
455
456 9
        if (!empty($this->brandText)) {
457 7
            $content .= $this->brandText;
458
        }
459
        /** @var string|Stringable $content */
460 9
        if (empty($this->brandUrl)) {
461 1
            $brand = Html::span($content, $options);
462
        } else {
463 8
            $brand = Html::a($content, $this->brandUrl, $options);
464
        }
465
466 9
        return $brand
467 9
            ->encode($encode)
468 9
            ->render();
469
    }
470
471
    /**
472
     * Renders collapsible toggle button.
473
     *
474
     * @param string|null $targetId - ID of target element for current button
475
     *
476
     * @throws JsonException
477
     *
478
     * @return string the rendering toggle button.
479
     *
480
     * @link https://getbootstrap.com/docs/5.0/components/navbar/#toggler
481
     */
482 19
    private function renderToggleButton(?string $targetId): string
483
    {
484 19
        $options = $this->togglerOptions;
485 19
        $encode = ArrayHelper::remove($options, 'encode', $this->encodeTags);
486 19
        Html::addCssClass($options, ['widget' => 'navbar-toggler']);
487
488 19
        $defauts = [
489 19
            'type' => 'button',
490 19
            'data' => [
491 19
                'bs-toggle' => $this->offcanvas ? 'offcanvas' : 'collapse',
492 19
            ],
493 19
            'aria' => [
494 19
                'controls' => $targetId,
495 19
                'expanded' => 'false',
496 19
                'label' => $this->screenReaderToggleText,
497 19
            ],
498 19
        ];
499
500 19
        if ($targetId) {
501 18
            $defauts['data']['bs-target'] = '#' . $targetId;
502
        }
503
504 19
        return Html::button(
505 19
            $this->togglerContent,
506 19
            ArrayHelper::merge($defauts, $options)
507 19
        )
508 19
            ->encode($encode)
509 19
            ->render();
510
    }
511
}
512