Passed
Push — master ( b856e3...01442b )
by Dmitrijs
02:12
created

Breadcrumbs::renderIcon()   A

Complexity

Conditions 5
Paths 4

Size

Total Lines 18
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 11
dl 0
loc 18
rs 9.6111
c 0
b 0
f 0
cc 5
nc 4
nop 1
1
<?php
2
/**
3
 * @link https://github.com/DMGPage/yii2-materialize
4
 * @copyright Copyright (c) 2018 Dmitrijs Reinmanis
5
 * @license https://github.com/DMGPage/yii2-materialize/blob/master/LICENSE
6
 */
7
8
namespace dmgpage\yii2materialize\widgets;
9
10
use yii\base\InvalidConfigException;
11
use yii\helpers\ArrayHelper;
12
use dmgpage\yii2materialize\helpers\Html;
13
use dmgpage\yii2materialize\assets\MaterializeExtraAsset;
14
15
/**
16
 * Breadcrumbs displays a list of links indicating the position of the current page in the whole site hierarchy.
17
 *
18
 * For example, breadcrumbs like "Home / Sample Post / Edit" means the user is viewing an edit page
19
 * for the "Sample Post". He can click on "Sample Post" to view that page, or he can click on "Home"
20
 * to return to the homepage.
21
 *
22
 * To use Breadcrumbs, you need to configure its [[links]] property, which specifies the links to be displayed. For example,
23
 *
24
 * ```php
25
 * echo Breadcrumbs::widget([
26
 *     'type' => BreadcrumbType::BASE,
27
 *     'homeLink' => [
28
 *         'label' => 'Home',
29
 *         'url' => '/',
30
 *         'icon' => 'home'
31
 *     ],
32
 *     'links' => [
33
 *         [
34
 *             'label' => 'Post Category',
35
 *             'url' => ['post-category/view', 'id' => 10],
36
 *             'target' => '_blank',
37
 *             'icon' => 'create'
38
 *         ],
39
 *         [
40
 *             'label' => 'Sample Post',
41
 *             'url' => ['post/edit', 'id' => 1],
42
 *             'icon' => 'reorder'
43
 *         ],
44
 *         'Edit',
45
 *     ],
46
 * ]);
47
 * ```
48
 *
49
 * Because breadcrumbs usually appears in nearly every page of a website, you may consider placing it in a layout view.
50
 * You can use a view parameter (e.g. `$this->params['breadcrumbs']`) to configure the links in different
51
 * views. In the layout view, you assign this view parameter to the [[links]] property like the following:
52
 *
53
 * ```php
54
 * // $this is the view object currently being used
55
 * echo Breadcrumbs::widget([
56
 *     'links' => isset($this->params['breadcrumbs']) ? $this->params['breadcrumbs'] : [],
57
 * ]);
58
 * ```
59
 */
60
class Breadcrumbs extends Widget
61
{
62
    /**
63
     * @var array the HTML attributes for the breadcrumb container tag.
64
     * @see \yii\helpers\Html::renderTagAttributes() for details on how attributes are being rendered.
65
     */
66
    public $options = [];
67
68
    /**
69
     * @var array the HTML attributes for the breadcrumb wrapper tag.
70
     * @see \yii\helpers\Html::renderTagAttributes() for details on how attributes are being rendered.
71
     */
72
    public $wrapperOptions = [];
73
74
    /**
75
     * @var array the HTML attributes for the breadcrumb column tag.
76
     * @see \yii\helpers\Html::renderTagAttributes() for details on how attributes are being rendered.
77
     */
78
    public $columnOptions = [];
79
80
    /**
81
     * @var string the type of breadcrumb to be rendered
82
     * @see \dmgpage\yii2materialize\helpers\BreadcrumbType
83
     */
84
    public $type;
85
86
    /**
87
     * @var bool whether to HTML-encode the link labels.
88
     */
89
    public $encodeLabels = true;
90
91
    /**
92
     * @var array the first hyperlink in the breadcrumbs (called home link).
93
     * Please refer to [[links]] on the format of the link.
94
     * If this property is not set, it will default to a link pointing to [[\yii\web\Application::homeUrl]]
95
     * with the label 'Home'. If this property contains `['render' => false]`, the home link will not be rendered.
96
     */
97
    public $homeLink;
98
99
    /**
100
     * @var array list of links to appear in the breadcrumbs. If this property is empty,
101
     * the widget will not render anything. Each array element represents a single link in the breadcrumbs
102
     * with the following structure:
103
     *
104
     * ```php
105
     * [
106
     *     'label' => 'label of the link',  // required
107
     *     'url' => 'url of the link',      // optional, will be processed by Url::to()
108
     *     'icon' => [                      // optional, will generate icon with given name and options
109
     *         'name' => 'home',
110
     *         'options' =>  ['class' => 'red']
111
     *     ]
112
     * ]
113
     * ```
114
     *
115
     * If a link is active, you only need to specify its "label", and instead of writing `['label' => $label]`,
116
     * you may simply use `$label`.
117
     */
118
    public $links = [];
119
120
    /**
121
     * Initialize the widget.
122
     */
123
    public function init()
124
    {
125
        parent::init();
126
127
        if (!isset($this->wrapperOptions['class'])) {
128
            Html::addCssClass($this->wrapperOptions, 'nav-wrapper');
129
        }
130
131
        if (!isset($this->columnOptions['class'])) {
132
            Html::addCssClass($this->columnOptions, 'col s12');
133
        }
134
    }
135
136
    /**
137
     * Renders the widget.
138
     */
139
    public function run()
140
    {
141
        $this->registerPlugin('breadcrumb');
142
143
        if (!empty($this->links)) {
144
            $links = [];
145
146
            if (empty($this->homeLink)) {
147
                $links[] = $this->renderItem(
148
                    [
149
                        'label' => \Yii::t('yii', 'Home'),
150
                        'url' => \Yii::$app->homeUrl
151
                    ]
152
                );
153
            } elseif (!isset($this->homeLink['render']) || $this->homeLink['render'] === true) {
154
                $links[] = $this->renderItem($this->homeLink);
155
            }
156
157
            foreach ($this->links as $link) {
158
                if (!is_array($link)) {
159
                    $link = ['label' => $link];
160
                }
161
162
                $links[] = $this->renderItem($link);
163
            }
164
165
            $column = Html::tag('div', implode('', $links), $this->columnOptions);
166
            $wraper = Html::tag('div', $column, $this->wrapperOptions);
167
168
            if (!empty($this->type)) {
169
                Html::addCssClass($this->options, $this->type);
170
                $view = $this->getView();
171
                MaterializeExtraAsset::register($view);
172
            }
173
174
            return Html::tag('nav', $wraper, $this->options);
175
        }
176
    }
177
178
    /**
179
     * Renders a single breadcrumb item.
180
     *
181
     * @param array $link the link to be rendered. It must contain the "label" element. The "url" and "icon" element is optional.
182
     * @return string the rendering result
183
     * @throws InvalidConfigException if `$link` does not have "label" element.
184
     */
185
    protected function renderItem($link)
186
    {
187
        $encodeLabel = ArrayHelper::remove($link, 'encode', $this->encodeLabels);
188
189
        if (array_key_exists('label', $link)) {
190
            $label = $encodeLabel ? Html::encode($link['label']) : $link['label'];
191
        } else {
192
            throw new InvalidConfigException('The "label" element is required for each link.');
193
        }
194
195
        // Add icon to label text
196
        if (isset($link['icon'])) {
197
            // Has issues on positioning: https://github.com/Dogfalo/materialize/issues/6224
198
            $label = $this->renderIcon($link['icon']) . $label;
199
        }
200
201
        $options = $link;
202
        unset($options['label'], $options['url'], $options['icon']);
203
204
        if (!isset($options['class'])) {
205
            Html::addCssClass($options, 'breadcrumb');
206
        }
207
208
        if (isset($link['url'])) {
209
            return Html::a($label, $link['url'], $options);
210
        } else {
211
            return Html::tag('span', $label, $options) ;
212
        }
213
    }
214
}
215
216