Passed
Pull Request — master (#90)
by
unknown
13:09
created

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