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

Breadcrumbs::render()   B

Complexity

Conditions 7
Paths 13

Size

Total Lines 36
Code Lines 20

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 22
CRAP Score 7

Importance

Changes 0
Metric Value
cc 7
eloc 20
nc 13
nop 0
dl 0
loc 36
ccs 22
cts 22
cp 1
crap 7
rs 8.6666
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 array_key_exists;
13
use function implode;
14
use function is_array;
15
use function strtr;
16
17
/**
18
 * Button renders a bootstrap button.
19
 *
20
 * For example,
21
 *
22
 * ```php
23
 * echo Breadcrumbs::widget()
24
 *     ->links(['label' => !empty($this->params['breadcrumbs']) ? $this->params['breadcrumbs'] : []]);
25
 * ```
26
 */
27
final class Breadcrumbs extends Widget
28
{
29
    /** @psalm-var non-empty-string */
30
    private string $tag = 'ol';
31
    private bool $encodeLabels = true;
32
    private bool $encodeTags = false;
33
    private array $homeLink = ['label' => 'Home', 'url' => '/'];
34
    private array $links = [];
35
    private string $itemTemplate = "<li class=\"breadcrumb-item\">{link}</li>\n";
36
    private string $activeItemTemplate = "<li class=\"breadcrumb-item active\" aria-current=\"page\">{link}</li>\n";
37
    private array $navOptions = ['aria-label' => 'breadcrumb'];
38
    private array $options = [];
39
40 10
    public function render(): string
41
    {
42 10
        if (empty($this->links)) {
43 1
            return '';
44
        }
45
46 9
        if (!isset($this->options['id'])) {
47 9
            $this->options['id'] = "{$this->getId()}-breadcrumb";
48
        }
49
50
        /** @psalm-suppress InvalidArgument */
51 9
        Html::addCssClass($this->options, ['widget' => 'breadcrumb']);
52
53 9
        $links = [];
54
55 9
        if ($this->homeLink !== []) {
56 8
            $links[] = $this->renderItem($this->homeLink, $this->itemTemplate);
57
        }
58
59 9
        foreach ($this->links as $link) {
60 9
            if (!is_array($link)) {
61 2
                $link = ['label' => $link];
62
            }
63
64 9
            $links[] = $this->renderItem($link, isset($link['url']) ? $this->itemTemplate : $this->activeItemTemplate);
65
        }
66
67 8
        return Html::tag(
68 8
            'nav',
69 8
            Html::tag($this->tag, implode('', $links), $this->options)
70 8
                ->encode($this->encodeTags)
71 8
                ->render(),
72 8
            $this->navOptions
73 8
        )
74 8
            ->encode($this->encodeTags)
75 8
            ->render();
76
    }
77
78
    /**
79
     * The template used to render each active item in the breadcrumbs. The token `{link}` will be replaced with the
80
     * actual HTML link for each active item.
81
     */
82 1
    public function activeItemTemplate(string $value): self
83
    {
84 1
        $new = clone $this;
85 1
        $new->activeItemTemplate = $value;
86
87 1
        return $new;
88
    }
89
90
    /**
91
     * When tags Labels HTML should not be encoded.
92
     */
93 1
    public function withoutEncodeLabels(): self
94
    {
95 1
        $new = clone $this;
96 1
        $new->encodeLabels = false;
97
98 1
        return $new;
99
    }
100
101
    /**
102
     * The first hyperlink in the breadcrumbs (called home link).
103
     *
104
     * Please refer to {@see links} on the format of the link.
105
     *
106
     * If this property is not set, it will default to a link pointing with the label 'Home'. If this property is false,
107
     * the home link will not be rendered.
108
     *
109
     * @param array $value
110
     */
111 2
    public function homeLink(array $value): self
112
    {
113 2
        $new = clone $this;
114 2
        $new->homeLink = $value;
115
116 2
        return $new;
117
    }
118
119
    /**
120
     * The template used to render each inactive item in the breadcrumbs. The token `{link}` will be replaced with the
121
     * actual HTML link for each inactive item.
122
     */
123 1
    public function itemTemplate(string $value): self
124
    {
125 1
        $new = clone $this;
126 1
        $new->itemTemplate = $value;
127
128 1
        return $new;
129
    }
130
131
    /**
132
     * List of links to appear in the breadcrumbs. If this property is empty, the widget will not render anything. Each
133
     * array element represents a single link in the breadcrumbs with the following structure:
134
     *
135
     * ```php
136
     * [
137
     *     'label' => 'label of the link',  // required
138
     *     'url' => 'url of the link',      // optional, will be processed by Url::to()
139
     *     'template' => 'own template of the item', // optional, if not set $this->itemTemplate will be used
140
     * ]
141
     * ```
142
     *
143
     * @param array $value
144
     */
145 10
    public function links(array $value): self
146
    {
147 10
        $new = clone $this;
148 10
        $new->links = $value;
149
150 10
        return $new;
151
    }
152
153
    /**
154
     * The HTML attributes for the widgets nav container tag.
155
     *
156
     * {@see Html::renderTagAttributes()} for details on how attributes are being rendered.
157
     *
158
     * @param array $value
159
     */
160 1
    public function navOptions(array $value): self
161
    {
162 1
        $new = clone $this;
163 1
        $new->navOptions = $value;
164
165 1
        return $new;
166
    }
167
168
    /**
169
     * The HTML attributes for the widget container tag. The following special options are recognized.
170
     *
171
     * {@see Html::renderTagAttributes()} for details on how attributes are being rendered.
172
     *
173
     * @param array $value
174
     */
175 1
    public function options(array $value): self
176
    {
177 1
        $new = clone $this;
178 1
        $new->options = $value;
179
180 1
        return $new;
181
    }
182
183
    /**
184
     * The name of the breadcrumb container tag.
185
     *
186
     * @psalm-param non-empty-string $value
187
     */
188 1
    public function tag(string $value): self
189
    {
190 1
        $new = clone $this;
191 1
        $new->tag = $value;
192
193 1
        return $new;
194
    }
195
196
    /**
197
     * Renders a single breadcrumb item.
198
     *
199
     * @param array $link the link to be rendered. It must contain the "label" element. The "url" element is optional.
200
     * @param string $template the template to be used to rendered the link. The token "{link}" will be replaced by the
201
     * link.
202
     *
203
     * @throws JsonException|RuntimeException if `$link` does not have "label" element.
204
     *
205
     * @return string the rendering result
206
     */
207 9
    private function renderItem(array $link, string $template): string
208
    {
209 9
        $encodeLabel = ArrayHelper::remove($link, 'encode', $this->encodeLabels);
210
211 9
        if (array_key_exists('label', $link)) {
212 9
            $label = $encodeLabel ? Html::encode($link['label']) : $link['label'];
213
        } else {
214 1
            throw new RuntimeException('The "label" element is required for each link.');
215
        }
216
217 9
        if (isset($link['template'])) {
218 2
            $template = $link['template'];
219
        }
220
221 9
        if (isset($link['url'])) {
222 9
            $options = $link;
223 9
            unset($options['template'], $options['label'], $options['url']);
224 9
            $linkHtml = Html::a($label, $link['url'], $options)->encode($this->encodeTags);
225
        } else {
226 8
            $linkHtml = $label;
227
        }
228
229 9
        return strtr($template, ['{link}' => $linkHtml]);
230
    }
231
}
232