Passed
Pull Request — master (#37)
by Evgeniy
02:34
created

Breadcrumbs::withoutEncodeLabels()   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 0
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\Widgets;
6
7
use InvalidArgumentException;
8
use JsonException;
9
use Yiisoft\Arrays\ArrayHelper;
10
use Yiisoft\Html\Html;
11
use Yiisoft\Widget\Widget;
12
13
use function array_key_exists;
14
use function implode;
15
use function is_array;
16
use function strtr;
17
18
/**
19
 * Breadcrumbs displays a list of links indicating the position of the current page in the whole site hierarchy.
20
 *
21
 * For example, breadcrumbs like "Home / Sample Post / Edit" means the user is viewing an edit page for the
22
 * "Sample Post". He can click on "Sample Post" to view that page, or he can click on "Home" to return to the homepage.
23
 *
24
 * To use Breadcrumbs, you need to configure its {@see Breadcrumbs::items()} method,
25
 * which specifies the links to be displayed. For example:
26
 *
27
 * ```php
28
 * // $this is the view object currently being used
29
 * echo Breadcrumbs::widget()
30
 *     -> itemTemplate() => "<li><i>{link}</i></li>\n", // template for all links
31
 *     -> links() => [
32
 *         [
33
 *             'label' => 'Post Category',
34
 *             'url' => 'post-category/view?id=10',
35
 *             'template' => "<li><b>{link}</b></li>\n", // template for this link only
36
 *         ],
37
 *         ['label' => 'Sample Post', 'url' => 'post/edit?id=1',
38
 *         'Edit',
39
 *     ];
40
 * ```
41
 *
42
 * Because breadcrumbs usually appears in nearly every page of a website, you may consider placing it in a layout view.
43
 * You can use a view common parameter (e.g. `$this->getCommonParameter('breadcrumbs')`) to configure the links in
44
 * different views. In the layout view, you assign this view parameter to the {@see Breadcrumbs::items()} method
45
 * like the following:
46
 *
47
 * ```php
48
 * // $this is the view object currently being used
49
 * echo Breadcrumbs::widget()
50
 *     ->links($this->hasCommonParameter('breadcrumbs') ? $this->getCommonParameter('breadcrumbs') : []);
51
 * ```
52
 */
53
final class Breadcrumbs extends Widget
54
{
55
    private string $tag = 'ul';
56
    private array $options = ['class' => 'breadcrumb'];
57
    private array $homeItem = ['label' => 'Home', 'url' => '/'];
58
    private array $items = [];
59
    private string $itemTemplate = "<li>{link}</li>\n";
60
    private string $activeItemTemplate = "<li class=\"active\">{link}</li>\n";
61
    private bool $encodeLabels = true;
62
63
    /**
64
     * Returns a new instance with the specified tag.
65
     *
66
     * @param string $value The tag name.
67
     *
68
     * @return self
69
     */
70 4
    public function tag(string $value): self
71
    {
72 4
        $new = clone $this;
73 4
        $new->tag = $value;
74 4
        return $new;
75
    }
76
77
    /**
78
     * Disables encoding for labels and returns a new instance.
79
     *
80
     * @return self Whether the labels for menu items should be HTML-encoded.
81
     */
82 2
    public function withoutEncodeLabels(): self
83
    {
84 2
        $new = clone $this;
85 2
        $new->encodeLabels = false;
86 2
        return $new;
87
    }
88
89
    /**
90
     * Returns a new instance with the specified first item in the breadcrumbs (called home link).
91
     *
92
     * If an empty array is specified, the home item will not be rendered.
93
     *
94
     * @param array $value Please refer to {@see items()} on the format.
95
     *
96
     * @return self
97
     */
98 7
    public function homeItem(array $value): self
99
    {
100 7
        $new = clone $this;
101 7
        $new->homeItem = $value;
102 7
        return $new;
103
    }
104
105
    /**
106
     * Returns a new instance with the specified list of items.
107
     *
108
     * @param array $value List of items to appear in the breadcrumbs. If this property is empty, the widget will not
109
     * render anything. Each array element represents a single link in the breadcrumbs with the following structure:
110
     *
111
     * ```php
112
     * [
113
     *     'label' => 'label of the link',  // required
114
     *     'url' => 'url of the link',      // optional
115
     *     'template' => 'own template of the item', // optional, if not set $this->itemTemplate will be used
116
     * ]
117
     * ```
118
     *
119
     * If a link is active, you only need to specify its "label", and instead of writing `['label' => $label]`, you may
120
     * simply use `$label`.
121
     *
122
     * Additional array elements for each link will be treated as the HTML attributes for the hyperlink tag.
123
     * For example, the following link specification will generate a hyperlink with CSS class `external`:
124
     *
125
     * ```php
126
     * [
127
     *     'label' => 'demo',
128
     *     'url' => 'http://example.com',
129
     *     'class' => 'external',
130
     * ]
131
     * ```
132
     *
133
     * Each individual link can override global {@see encodeLabels} param like the following:
134
     *
135
     * ```php
136
     * [
137
     *     'label' => '<strong>Hello!</strong>',
138
     *     'encode' => false,
139
     * ]
140
     * ```
141
     *
142
     * @return self
143
     */
144 9
    public function items(array $value): self
145
    {
146 9
        $new = clone $this;
147 9
        $new->items = $value;
148 9
        return $new;
149
    }
150
151
    /**
152
     * @param array $value The HTML attributes for the menu's container tag. The following special options are
153
     * recognized:
154
     *
155
     * - tag: string, defaults to "ul", the tag name of the item container tags. Set to false to disable container tag.
156
     *   See also {@see \Yiisoft\Html\Html::tag()}.
157
     *
158
     * {@see \Yiisoft\Html\Html::renderTagAttributes()} for details on how attributes are being rendered.
159
     *
160
     * @return self
161
     */
162 5
    public function options(array $value): self
163
    {
164 5
        $new = clone $this;
165 5
        $new->options = $value;
166 5
        return $new;
167
    }
168
169
    /**
170
     * Returns a new instance with the specified item template.
171
     *
172
     * @param string $value The template used to render each inactive item in the breadcrumbs.
173
     * The token `{link}` will be replaced with the actual HTML link for each inactive item.
174
     *
175
     * @return self
176
     */
177 2
    public function itemTemplate(string $value): self
178
    {
179 2
        $new = clone $this;
180 2
        $new->itemTemplate = $value;
181 2
        return $new;
182
    }
183
184
    /**
185
     * Returns a new instance with the specified active item template.
186
     *
187
     * @param string $value The template used to render each active item in the breadcrumbs.
188
     * The token `{link}` will be replaced with the actual HTML link for each active item.
189
     *
190
     * @return self
191
     */
192 4
    public function activeItemTemplate(string $value): self
193
    {
194 4
        $new = clone $this;
195 4
        $new->activeItemTemplate = $value;
196 4
        return $new;
197
    }
198
199
    /**
200
     * Renders the widget.
201
     *
202
     * @throws JsonException
203
     *
204
     * @return string The result of widget execution to be outputted.
205
     */
206 9
    protected function run(): string
207
    {
208 9
        if (empty($this->items)) {
209 1
            return '';
210
        }
211
212 8
        $items = [];
213
214 8
        if (!empty($this->homeItem)) {
215 3
            $items[] = $this->renderItem($this->homeItem, $this->itemTemplate);
216
        }
217
218 8
        foreach ($this->items as $item) {
219 8
            if (!is_array($item)) {
220 7
                $item = ['label' => $item];
221
            }
222
223 8
            if (!empty($item)) {
224 8
                $items[] = $this->renderItem(
225 8
                    $item,
226 8
                    isset($item['url']) ? $this->itemTemplate : $this->activeItemTemplate
227
                );
228
            }
229
        }
230
231 7
        $body = implode('', $items);
232
233 7
        return empty($this->tag)
234 2
            ? $body
235 7
            : Html::tag($this->tag, $body, $this->options)->encode(false)->render()
236
            ;
237
    }
238
239
    /**
240
     * Renders a single breadcrumb item.
241
     *
242
     * @param array $item The item to be rendered. It must contain the "label" element. The "url" element is optional.
243
     * @param string $template the template to be used to rendered the link. The token "{link}" will be replaced by the
244
     * link.
245
     *
246
     * @throws InvalidArgumentException|JsonException if `$item` does not have "label" element.
247
     *
248
     * @return string The rendering result.
249
     */
250 8
    private function renderItem(array $item, string $template): string
251
    {
252 8
        if (!array_key_exists('label', $item)) {
253 1
            throw new InvalidArgumentException('The "label" element is required for each link.');
254
        }
255
256 7
        $encodeLabel = ArrayHelper::remove($item, 'encode', $this->encodeLabels);
257 7
        $label = $encodeLabel ? Html::encode($item['label']) : $item['label'];
258
259 7
        if (isset($item['template'])) {
260
            $template = $item['template'];
261
        }
262
263 7
        if (isset($item['url'])) {
264 2
            $options = $item;
265 2
            unset($options['template'], $options['label'], $options['url']);
266 2
            $item = Html::a($label, $item['url'], $options);
267
        } else {
268 7
            $item = $label;
269
        }
270
271 7
        return strtr($template, ['{link}' => $item]);
272
    }
273
}
274