Completed
Push — master ( e7e924...ba64aa )
by Dmitrijs
03:19
created

Breadcrumbs::init()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 4
dl 0
loc 8
rs 10
c 0
b 0
f 0
cc 3
nc 4
nop 0
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;
11
use yii\base\InvalidConfigException;
12
use yii\base\Widget;
0 ignored issues
show
Bug introduced by
This use statement conflicts with another class in this namespace, dmgpage\yii2materialize\widgets\Widget. Consider defining an alias.

Let?s assume that you have a directory layout like this:

.
|-- OtherDir
|   |-- Bar.php
|   `-- Foo.php
`-- SomeDir
    `-- Foo.php

and let?s assume the following content of Bar.php:

// Bar.php
namespace OtherDir;

use SomeDir\Foo; // This now conflicts the class OtherDir\Foo

If both files OtherDir/Foo.php and SomeDir/Foo.php are loaded in the same runtime, you will see a PHP error such as the following:

PHP Fatal error:  Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php

However, as OtherDir/Foo.php does not necessarily have to be loaded and the error is only triggered if it is loaded before OtherDir/Bar.php, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias:

// Bar.php
namespace OtherDir;

use SomeDir\Foo as SomeDirFoo; // There is no conflict anymore.
Loading history...
13
use yii\helpers\ArrayHelper;
14
use yii\helpers\Html;
15
16
/**
17
 * Breadcrumbs displays a list of links indicating the position of the current page in the whole site hierarchy.
18
 *
19
 * For example, breadcrumbs like "Home / Sample Post / Edit" means the user is viewing an edit page
20
 * for the "Sample Post". He can click on "Sample Post" to view that page, or he can click on "Home"
21
 * to return to the homepage.
22
 *
23
 * To use Breadcrumbs, you need to configure its [[links]] property, which specifies the links to be displayed. For example,
24
 *
25
 * ```php
26
 * echo Breadcrumbs::widget([
27
 *     'links' => [
28
 *         [
29
 *             'label' => 'Post Category',
30
 *             'url' => ['post-category/view', 'id' => 10]
31
 *         ],
32
 *         ['label' => 'Sample Post', 'url' => ['post/edit', 'id' => 1]],
33
 *         'Edit',
34
 *     ],
35
 * ]);
36
 * ```
37
 *
38
 * Because breadcrumbs usually appears in nearly every page of a website, you may consider placing it in a layout view.
39
 * You can use a view parameter (e.g. `$this->params['breadcrumbs']`) to configure the links in different
40
 * views. In the layout view, you assign this view parameter to the [[links]] property like the following:
41
 *
42
 * ```php
43
 * // $this is the view object currently being used
44
 * echo Breadcrumbs::widget([
45
 *     'links' => isset($this->params['breadcrumbs']) ? $this->params['breadcrumbs'] : [],
46
 * ]);
47
 * ```
48
 */
49
class Breadcrumbs extends Widget
50
{
51
    /**
52
     * @var array the HTML attributes for the breadcrumb container tag.
53
     * @see \yii\helpers\Html::renderTagAttributes() for details on how attributes are being rendered.
54
     */
55
    public $options = [];
56
57
    /**
58
     * @var array the HTML attributes for the breadcrumb wrapper tag.
59
     * @see \yii\helpers\Html::renderTagAttributes() for details on how attributes are being rendered.
60
     */
61
    public $wrapperOptions = [];
62
63
    /**
64
     * @var array the HTML attributes for the breadcrumb column tag.
65
     * @see \yii\helpers\Html::renderTagAttributes() for details on how attributes are being rendered.
66
     */
67
    public $columnOptions = [];
68
69
    /**
70
     * @var bool whether to HTML-encode the link labels.
71
     */
72
    public $encodeLabels = true;
73
74
    /**
75
     * @var array the first hyperlink in the breadcrumbs (called home link).
76
     * Please refer to [[links]] on the format of the link.
77
     * If this property is not set, it will default to a link pointing to [[\yii\web\Application::homeUrl]]
78
     * with the label 'Home'. If this property contains `['render' => false]`, the home link will not be rendered.
79
     */
80
    public $homeLink;
81
82
    /**
83
     * @var array list of links to appear in the breadcrumbs. If this property is empty,
84
     * the widget will not render anything. Each array element represents a single link in the breadcrumbs
85
     * with the following structure:
86
     *
87
     * ```php
88
     * [
89
     *     'label' => 'label of the link',  // required
90
     *     'url' => 'url of the link'      // optional, will be processed by Url::to()
91
     * ]
92
     * ```
93
     *
94
     * If a link is active, you only need to specify its "label", and instead of writing `['label' => $label]`,
95
     * you may simply use `$label`.
96
     */
97
    public $links = [];
98
99
    /**
100
     * Initialize the widget.
101
     */
102
    public function init()
103
    {
104
        if (!isset($this->wrapperOptions['class'])) {
105
            Html::addCssClass($this->wrapperOptions, 'nav-wrapper');
106
        }
107
108
        if (!isset($this->columnOptions['class'])) {
109
            Html::addCssClass($this->columnOptions, 'col s12');
110
        }
111
    }
112
113
    /**
114
     * Renders the widget.
115
     */
116
    public function run()
117
    {
118
        if (!empty($this->links)) {
119
            $links = [];
120
121
            if (empty($this->homeLink)) {
122
                $links[] = $this->renderItem(
123
                    [
124
                        'label' => Yii::t('yii', 'Home'),
125
                        'url' => Yii::$app->homeUrl
126
                    ]
127
                );
128
            } elseif (!isset($this->homeLink['render']) || $this->homeLink['render'] === true) {
129
                $links[] = $this->renderItem($this->homeLink);
130
            }
131
132
            foreach ($this->links as $link) {
133
                if (!is_array($link)) {
134
                    $link = ['label' => $link];
135
                }
136
137
                $links[] = $this->renderItem($link);
138
            }
139
140
            $column = Html::tag('div', implode('', $links), $this->columnOptions);
141
            $wraper = Html::tag('div', $column, $this->wrapperOptions);
142
            return Html::tag('nav', $wraper, $this->options);
143
        }
144
    }
145
146
    /**
147
     * Renders a single breadcrumb item.
148
     *
149
     * @param array $link the link to be rendered. It must contain the "label" element. The "url" element is optional.
150
     * @return string the rendering result
151
     * @throws InvalidConfigException if `$link` does not have "label" element.
152
     */
153
    protected function renderItem($link)
154
    {
155
        $encodeLabel = ArrayHelper::remove($link, 'encode', $this->encodeLabels);
156
157
        if (array_key_exists('label', $link)) {
158
            $label = $encodeLabel ? Html::encode($link['label']) : $link['label'];
159
        } else {
160
            throw new InvalidConfigException('The "label" element is required for each link.');
161
        }
162
163
        $options = $link;
164
        unset($options['label'], $options['url']);
165
166
        if (!isset($options['class'])) {
167
            Html::addCssClass($options, 'breadcrumb');
168
        }
169
170
        if (isset($link['url'])) {
171
            return Html::a($label, $link['url'], $options);
172
        } else {
173
            return Html::tag('span', $label, $options) ;
174
        }
175
    }
176
}
177