Passed
Pull Request — master (#41)
by Evgeniy
04:43 queued 02:11
created

Breadcrumbs::items()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 3
c 0
b 0
f 0
nc 1
nop 1
dl 0
loc 5
ccs 4
cts 4
cp 1
crap 1
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Yii\Bulma;
6
7
use InvalidArgumentException;
8
use JsonException;
9
use Yiisoft\Arrays\ArrayHelper;
10
use Yiisoft\Html\Html;
11
12
use function array_key_exists;
13
use function array_merge;
14
use function implode;
15
use function is_array;
16
use function strtr;
17
18
/**
19
 * The Bulma breadcrumb is a simple navigation component.
20
 *
21
 * ```php
22
 * echo Breadcrumbs::widget()->items([
23
 *     ['label' => 'Info'],
24
 *     ['label' => 'Contacts'],
25
 * ]);
26
 * ```
27
 *
28
 * @link https://bulma.io/documentation/components/breadcrumb/
29
 */
30
final class Breadcrumbs extends Widget
31
{
32
    private bool $encodeLabels = true;
33
    private array $homeItem = ['label' => 'Home', 'url' => '/'];
34
    private string $itemTemplate = "<li>{icon}{link}</li>\n";
35
    private string $activeItemTemplate = "<li class=\"is-active\"><a aria-current=\"page\">{icon}{label}</a></li>\n";
36
    private array $items = [];
37
    private array $options = [];
38
    private array $itemsOptions = [];
39
40 13
    protected function run(): string
41
    {
42 13
        if (empty($this->items)) {
43 1
            return '';
44
        }
45
46 12
        $this->buildOptions();
47
48
        return
49 12
            Html::openTag('nav', $this->options) . "\n" .
50 12
                Html::openTag('ul', $this->itemsOptions) . "\n" .
51 12
                    implode('', $this->renderItems()) .
52 11
                Html::closeTag('ul') . "\n" .
53 11
            Html::closeTag('nav');
54
    }
55
56
    /**
57
     * Disables encoding for labels.
58
     *
59
     * @return self
60
     */
61 1
    public function withoutEncodeLabels(): self
62
    {
63 1
        $new = clone $this;
64 1
        $new->encodeLabels = false;
65 1
        return $new;
66
    }
67
68
    /**
69
     * The first item in the breadcrumbs (called home link).
70
     *
71
     * If an empty array is specified, the home item will not be rendered.
72
     *
73
     * Please refer to {@see $items} on the format.
74
     *
75
     * @param array $value
76
     *
77
     * @return self
78
     */
79 8
    public function homeItem(array $value): self
80
    {
81 8
        $new = clone $this;
82 8
        $new->homeItem = $value;
83 8
        return $new;
84
    }
85
86
    /**
87
     * The template used to render each inactive item in the breadcrumbs. The token `{link}` will be replaced with the
88
     * actual HTML link for each inactive item.
89
     *
90
     * @param string $value
91
     *
92
     * @return self
93
     */
94 2
    public function itemTemplate(string $value): self
95
    {
96 2
        $new = clone $this;
97 2
        $new->itemTemplate = $value;
98 2
        return $new;
99
    }
100
101
    /**
102
     * The template used to render each active item in the breadcrumbs. The token `{link}` will be replaced with the
103
     * actual HTML link for each active item.
104
     *
105
     * @param string $value
106
     *
107
     * @return self
108
     */
109 2
    public function activeItemTemplate(string $value): self
110
    {
111 2
        $new = clone $this;
112 2
        $new->activeItemTemplate = $value;
113 2
        return $new;
114
    }
115
116
    /**
117
     * List of items to appear in the breadcrumb. If this property is empty, the widget will not render anything. Each
118
     * array element represents a single link in the breadcrumb with the following structure:
119
     *
120
     * ```php
121
     * [
122
     *     'label' => 'label of the link',  // required
123
     *     'url' => 'url of the link',      // optional, will be processed by Url::to()
124
     *     'template' => 'own template of the item', // optional, if not set $this->itemTemplate will be used
125
     * ]
126
     * ```
127
     *
128
     * @param array $value
129
     *
130
     * @return self
131
     */
132 14
    public function items(array $value): self
133
    {
134 14
        $new = clone $this;
135 14
        $new->items = $value;
136 14
        return $new;
137
    }
138
139
    /**
140
     * The HTML attributes for the widget container nav tag.
141
     *
142
     * @param array $value
143
     *
144
     * @return self
145
     *
146
     * {@see Html::renderTagAttributes()} for details on how attributes are being rendered.
147
     */
148 3
    public function options(array $value): self
149
    {
150 3
        $new = clone $this;
151 3
        $new->options = $value;
152 3
        return $new;
153
    }
154
155
    /**
156
     * The HTML attributes for the items widget.
157
     *
158
     * @param array $value
159
     *
160
     * @return self
161
     *
162
     * {@see Html::renderTagAttributes()} for details on how attributes are being rendered.
163
     */
164 2
    public function itemsOptions(array $value): self
165
    {
166 2
        $new = clone $this;
167 2
        $new->itemsOptions = $value;
168 2
        return $new;
169
    }
170
171 12
    private function buildOptions(): void
172
    {
173 12
        if (!isset($this->options['id'])) {
174 12
            $this->options['id'] = "{$this->getId()}-breadcrumbs";
175
        }
176
177 12
        $this->options = $this->addOptions(
178 12
            array_merge(
179 12
                $this->options,
180 12
                ['aria-label' => 'breadcrumbs']
181
            ),
182 12
            'breadcrumb'
183
        );
184 12
    }
185
186 12
    private function renderIcon(string $icon, array $iconOptions): string
187
    {
188 12
        $html = '';
189
190 12
        if ($icon !== '') {
191 1
            $html = Html::openTag('span', $iconOptions) .
192 1
                Html::tag('i', '', ['class' => $icon]) .
193 1
                Html::closeTag('span');
194
        }
195
196 12
        return $html;
197
    }
198
199
    /**
200
     * Renders a single breadcrumb item.
201
     *
202
     * @param array $item The item to be rendered. It must contain the "label" element. The "url" element is optional.
203
     * @param string $template The template to be used to rendered the link. The token "{link}" will be replaced by the
204
     * link.
205
     *
206
     * @throws InvalidArgumentException|JsonException If `$item` does not have "label" element.
207
     *
208
     * @return string The rendering result.
209
     */
210 12
    private function renderItem(array $item, string $template): string
211
    {
212 12
        $encodeLabel = ArrayHelper::remove($item, 'encode', $this->encodeLabels);
213
214 12
        $icon = '';
215 12
        $iconOptions = [];
216
217 12
        if (isset($item['icon'])) {
218 1
            $icon = $item['icon'];
219
        }
220
221 12
        if (isset($item['iconOptions']) && is_array($item['iconOptions'])) {
222 1
            $iconOptions = $this->addOptions($iconOptions, 'icon');
223
        }
224
225 12
        unset($item['icon'], $item['iconOptions']);
226
227 12
        if (array_key_exists('label', $item)) {
228 12
            $label = $encodeLabel ? Html::encode($item['label']) : $item['label'];
229
        } else {
230 1
            throw new InvalidArgumentException('The "label" element is required for each link.');
231
        }
232
233 12
        if (isset($item['template'])) {
234 1
            $template = $item['template'];
235
        }
236
237 12
        if (isset($item['url'])) {
238 12
            $options = $item;
239 12
            unset($options['template'], $options['label'], $options['url'], $options['icon']);
240 12
            $link = Html::a($label, $item['url'], $options)->encode(false)->render();
241
        } else {
242 2
            $link = $label;
243
        }
244
245 12
        return strtr(
246 12
            $template,
247 12
            ['{label}' => $label, '{link}' => $link, '{icon}' => $this->renderIcon($icon, $iconOptions)],
248
        );
249
    }
250
251 12
    private function renderItems(): array
252
    {
253 12
        $items = [];
254
255 12
        if (!empty($this->homeItem)) {
256 11
            $items[] = $this->renderItem($this->homeItem, $this->itemTemplate);
257
        }
258
259 12
        foreach ($this->items as $item) {
260 12
            if (!is_array($item)) {
261 1
                $item = ['label' => $item];
262
            }
263
264 12
            $items[] = $this->renderItem($item, isset($item['url']) ? $this->itemTemplate : $this->activeItemTemplate);
265
        }
266
267 11
        return $items;
268
    }
269
}
270