Passed
Pull Request — master (#91)
by
unknown
03:06
created

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