Completed
Pull Request — master (#52)
by Wilmer
01:36
created

Breadcrumbs   A

Complexity

Total Complexity 23

Size/Duplication

Total Lines 265
Duplicated Lines 0 %

Test Coverage

Coverage 98.18%

Importance

Changes 0
Metric Value
wmc 23
eloc 55
c 0
b 0
f 0
dl 0
loc 265
rs 10
ccs 54
cts 55
cp 0.9818

11 Methods

Rating   Name   Duplication   Size   Complexity  
A homeUrlLink() 0 5 1
A itemTemplate() 0 5 1
A options() 0 5 1
A renderItem() 0 18 4
A links() 0 9 2
B show() 0 28 9
A encodeLabels() 0 5 1
A __toString() 0 3 1
A homeLink() 0 5 1
A tag() 0 5 1
A activeItemTemplate() 0 5 1
1
<?php
2
3
namespace Yiisoft\Widget;
4
5
use Yiisoft\Html\Html;
6
use Yiisoft\Arrays\ArrayHelper;
7
use Yiisoft\Widget\Widget;
8
9
/**
10
 * Breadcrumbs displays a list of links indicating the position of the current page in the whole site hierarchy.
11
 *
12
 * For example, breadcrumbs like "Home / Sample Post / Edit" means the user is viewing an edit page for the
13
 * "Sample Post". He can click on "Sample Post" to view that page, or he can click on "Home" to return to the homepage.
14
 *
15
 * To use Breadcrumbs, you need to configure its {@see links} property, which specifies the links to be displayed. For
16
 * example,
17
 *
18
 * ```php
19
 * // $this is the view object currently being used
20
 * echo Breadcrumbs::widget()
21
 *     -> itemTemplate() => "<li><i>{link}</i></li>\n", // template for all links
22
 *     -> links() => [
23
 *         [
24
 *             'label' => 'Post Category',
25
 *             'url' => 'post-category/view?id=10',
26
 *             'template' => "<li><b>{link}</b></li>\n", // template for this link only
27
 *         ],
28
 *         ['label' => 'Sample Post', 'url' => 'post/edit?id=1',
29
 *         'Edit',
30
 *     ];
31
 * ```
32
 *
33
 * Because breadcrumbs usually appears in nearly every page of a website, you may consider placing it in a layout view.
34
 * You can use a view parameter (e.g. `$this->params['breadcrumbs']`) to configure the links in different views. In the
35
 * layout view, you assign this view parameter to the {@see links} property like the following:
36
 *
37
 * ```php
38
 * // $this is the view object currently being used
39
 * echo Breadcrumbs::widget()
40
 *     ->links() => isset($this->params['breadcrumbs']) ? $this->params['breadcrumbs'] : [];
41
 * ```
42
 */
43
class Breadcrumbs extends Widget
44
{
45
    /**
46
     * @var string the name of the breadcrumb container tag.
47
     */
48
    private $tag = 'ul';
49
50
    /**
51
     * @var array the HTML attributes for the breadcrumb container tag.
52
     *
53
     * {@see \Yiisoft\Html\Html::renderTagAttributes()} for details on how attributes are being rendered.
54
     */
55
    private $options = ['class' => 'breadcrumb'];
56
57
    /**
58
     * @var bool whether to HTML-encode the link labels.
59
     */
60
    private $encodeLabels = true;
61
62
    /**
63
     * @var bool the first hyperlink in the breadcrumbs (called home link). If this property is true, it will default
64
     *           to a link pointing to HomeUrl '\' with the label 'Home'. If this property is false, the home link will
65
     *           not be rendered.
66
     */
67
    private $homeLink = true;
68
69
    /**
70
     * @var string $homeUrlLink
71
     */
72
    private $homeUrlLink;
73
74
    /**
75
     * @var array list of links to appear in the breadcrumbs. If this property is empty, the widget will not render
76
     *            anything. Each array element represents a single link in the breadcrumbs with the following structure:
77
     *
78
     * ```php
79
     * [
80
     *     'label' => 'label of the link',  // required
81
     *     'url' => 'url of the link',      // optional, will be processed by Url::to()
82
     *     'template' => 'own template of the item', // optional, if not set $this->itemTemplate will be used
83
     * ]
84
     * ```
85
     *
86
     * If a link is active, you only need to specify its "label", and instead of writing `['label' => $label]`, you may
87
     * simply use `$label`.
88
     *
89
     * Additional array elements for each link will be treated as the HTML attributes for the hyperlink tag.
90
     * For example, the following link specification will generate a hyperlink with CSS class `external`:
91
     *
92
     * ```php
93
     * [
94
     *     'label' => 'demo',
95
     *     'url' => 'http://example.com',
96
     *     'class' => 'external',
97
     * ]
98
     * ```
99
     *
100
     * Each individual link can override global {@see encodeLabels} param like the following:
101
     *
102
     * ```php
103
     * [
104
     *     'label' => '<strong>Hello!</strong>',
105
     *     'encode' => false,
106
     * ]
107
     * ```
108
     */
109
    private $links = [];
110
111
    /**
112
     * @var string the template used to render each inactive item in the breadcrumbs. The token `{link}` will be
113
     *             replaced with the actual HTML link for each inactive item.
114
     */
115
    private $itemTemplate = "<li>{link}</li>\n";
116
117
    /**
118
     * @var string the template used to render each active item in the breadcrumbs. The token `{link}` will be replaced
119
     *             with the actual HTML link for each active item.
120
     */
121
    private $activeItemTemplate = "<li class=\"active\">{link}</li>\n";
122
123
    /**
124
     * Renders the widget.
125
     *
126
     * @return string the result of widget execution to be outputted.
127
     */
128 8
    public function show(): string
129
    {
130 8
        if (empty($this->links)) {
131 1
            return '';
132
        }
133
134 7
        $links = [];
135
136 7
        if ($this->homeLink === true) {
137 2
            $links[] = $this->renderItem([
138 2
                'label' => 'Home',
139
                'url'   => '/',
140 2
            ], $this->itemTemplate);
141 5
        } elseif (!empty($this->homeUrlLink)) {
142 1
            $links[] = $this->renderItem($this->homeUrlLink, $this->itemTemplate);
0 ignored issues
show
Bug introduced by
$this->homeUrlLink of type string is incompatible with the type array expected by parameter $link of Yiisoft\Widget\Breadcrumbs::renderItem(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

142
            $links[] = $this->renderItem(/** @scrutinizer ignore-type */ $this->homeUrlLink, $this->itemTemplate);
Loading history...
143
        }
144
145 7
        foreach ($this->links as $key => $link) {
146 7
            if (!is_array($link)) {
147 7
                $link = ['label' => $link];
148
            }
149
150 7
            if (!empty($link)) {
151 7
                $links[] = $this->renderItem($link, isset($link['url']) ? $this->itemTemplate : $this->activeItemTemplate);
152
            }
153
        }
154
155 7
        return Html::tag((!empty($this->tag)) ? $this->tag : false, implode('', $links), $this->options);
156
    }
157
158
    /**
159
     * Renders a single breadcrumb item.
160
     *
161
     * @param array  $link the link to be rendered. It must contain the "label" element. The "url" element is optional.
162
     * @param string $template the template to be used to rendered the link. The token "{link}" will be replaced by the
163
     *                         link.
164
     *
165
     * @throws \InvalidArgumentException if `$link` does not have "label" element.
166
     *
167
     * @return string the rendering result
168
     */
169 7
    protected function renderItem(array $link, string $template)
170
    {
171 7
        $encodeLabel = ArrayHelper::remove($link, 'encode', $this->encodeLabels);
172 7
        $label = $encodeLabel ? Html::encode($link['label']) : $link['label'];
173
174 7
        if (isset($link['template'])) {
175
            $template = $link['template'];
176
        }
177
178 7
        if (isset($link['url'])) {
179 2
            $options = $link;
180 2
            unset($options['template'], $options['label'], $options['url']);
181 2
            $link = Html::a($label, $link['url'], $options);
182
        } else {
183 7
            $link = $label;
184
        }
185
186 7
        return strtr($template, ['{link}' => $link]);
187
    }
188
189
    /**
190
     * {@see tag}
191
     *
192
     * @param string $value
193
     *
194
     * @return Widget
195
     */
196 3
    public function tag(string $value): Widget
197
    {
198 3
        $this->tag = $value;
199
200 3
        return $this;
201
    }
202
203
    /**
204
     * {@see options}
205
     *
206
     * @param array $value
207
     *
208
     * @return Widget
209
     */
210 4
    public function options(array $value): Widget
211
    {
212 4
        $this->options = $value;
213
214 4
        return $this;
215
    }
216
217
    /**
218
     * {@see encodeLabel}
219
     *
220
     * @param boolean $value
221
     *
222
     * @return Widget
223
     */
224 1
    public function encodeLabels(bool $value): Widget
225
    {
226 1
        $this->encodeLabels = $value;
227
228 1
        return $this;
229
    }
230
231
    /**
232
     * {@see homeLink}
233
     *
234
     * @param bool $value
235
     *
236
     * @return Widget
237
     */
238 7
    public function homeLink(bool $value): Widget
239
    {
240 7
        $this->homeLink = $value;
241
242 7
        return $this;
243
    }
244
245
    /**
246
     * {@see links}
247
     *
248
     * @param string $value
249
     *
250
     * @return Widget
251
     */
252 1
    public function homeUrlLink(array $value): Widget
253
    {
254 1
        $this->homeUrlLink = $value;
0 ignored issues
show
Documentation Bug introduced by
It seems like $value of type array is incompatible with the declared type string of property $homeUrlLink.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
255
256 1
        return $this;
257
    }
258
259
    /**
260
     * {@see links}
261
     *
262
     * @param array $value
263
     *
264
     * @return Widget
265
     */
266 8
    public function links(array $value): Widget
267
    {
268 8
        if (!array_key_exists('label', $value)) {
269 1
            throw new \InvalidArgumentException('The "label" element is required for each link.');
270
        }
271
272 7
        $this->links = $value;
273
274 7
        return $this;
275
    }
276
277
    /**
278
     * {@see itemTemplate}
279
     *
280
     * @param string $value
281
     *
282
     * @return Widget
283
     */
284 1
    public function itemTemplate(string $value): Widget
285
    {
286 1
        $this->itemTemplate = $value;
287
288 1
        return $this;
289
    }
290
291
    /**
292
     * {@see activeItemTemplate}
293
     *
294
     * @param string $value
295
     *
296
     * @return Widget
297
     */
298 3
    public function activeItemTemplate(string $value): Widget
299
    {
300 3
        $this->activeItemTemplate = $value;
301
302 3
        return $this;
303
    }
304
305 8
    public function __toString()
306
    {
307 8
        return $this->show();
308
    }
309
}
310