Passed
Push — master ( e97433...d57a25 )
by Dmitrijs
02:20
created

Tabs   A

Complexity

Total Complexity 24

Size/Duplication

Total Lines 189
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 24
eloc 62
dl 0
loc 189
rs 10
c 0
b 0
f 0

5 Methods

Rating   Name   Duplication   Size   Complexity  
A init() 0 8 2
A run() 0 5 1
A renderItems() 0 25 6
A hasActiveTab() 0 9 4
B renderItem() 0 47 11
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\helpers\ArrayHelper;
11
use dmgpage\yii2materialize\helpers\Html;
12
use yii\base\InvalidConfigException;
13
14
/**
15
 * The tabs structure consists of an unordered list of tabs that have hashes corresponding to tab ids.
16
 * Then when you click on each tab, only the container with the corresponding tab id will become visible.
17
 *
18
 * You can use Tabs like this:
19
 *
20
 * ```php
21
 * echo Tabs::widget([
22
 *     'items' => [
23
 *         [
24
 *             'label' => 'Home',
25
 *             'content' => 'Home content...',
26
 *             'active' => true
27
 *         ],
28
 *         [
29
 *             'label' => 'Profile',
30
 *             'content' => 'Profile content...'
31
 *         ],
32
 *         [
33
 *             'label' => 'Messages',
34
 *             'content' => 'Messages content...',
35
 *             'disabled' => true
36
 *         ],
37
 *         [
38
 *             'label' => 'Google',
39
 *             'url' => 'http://www.google.lv'
40
 *         ],
41
 *         [
42
 *             'label' => 'Hidden',
43
 *             'content' => 'Hidden content...',
44
 *             'visible' => false
45
 *         ],
46
 *     ]
47
 * ]);
48
 * ```
49
 * @property bool $initializePlugin
50
 *
51
 * @see https://materializecss.com/tabs.html
52
 * @package widgets
53
 */
54
class Tabs extends Widget
55
{
56
    /**
57
     * @var array list of tabs in the tabs widget. Each array element represents a single
58
     * tab with the following structure:
59
     *
60
     * - label: string, required, the tab header label.
61
     * - encode: boolean, optional, whether this label should be HTML-encoded. This param will override
62
     *   global `$this->encodeLabels` param.
63
     * - headerOptions: array, optional, the HTML attributes of the tab header.
64
     * - linkOptions: array, optional, the HTML attributes of the tab header link tags.
65
     * - content: string, optional, the content (HTML) of the tab pane.
66
     * - url: string, optional, an external URL. When this is specified, clicking on this tab will bring
67
     *   the browser to this URL
68
     * - options: array, optional, the HTML attributes of the tab pane container.
69
     * - active: boolean, optional, whether this item tab header and pane should be active. If no item is marked as
70
     *   'active' explicitly - the first one will be activated.
71
     * - visible: boolean, optional, whether the item tab header and pane should be visible or not. Defaults to true.
72
     * - disabled: boolean, optional, whether the item tab header and pane should be disabled or not. Defaults to false.
73
     */
74
    public $items = [];
75
76
    /**
77
     * @var array list of HTML attributes for the header container tags. This will be overwritten
78
     * by the "headerOptions" set in individual [[items]].
79
     * @see \yii\helpers\Html::renderTagAttributes() for details on how attributes are being rendered.
80
     */
81
    public $headerOptions = [];
82
83
    /**
84
     * @var array list of HTML attributes for the tab header link tags. This will be overwritten
85
     * by the "linkOptions" set in individual [[items]].
86
     * @see \yii\helpers\Html::renderTagAttributes() for details on how attributes are being rendered.
87
     */
88
    public $linkOptions = [];
89
90
    /**
91
     * @var array list of HTML attributes for the item container tags. This will be overwritten
92
     * by the "options" set in individual [[items]]. The following special options are recognized:
93
     *
94
     * - tag: string, defaults to "div", the tag name of the item container tags.
95
     *
96
     * @see \yii\helpers\Html::renderTagAttributes() for details on how attributes are being rendered.
97
     */
98
    public $itemOptions = [];
99
100
    /**
101
     * @var boolean whether to render the `tab-content` container and its content. You may set this property
102
     * to be false so that you can manually render `tab-content` yourself in case your tab contents are complex.
103
     */
104
    public $renderTabContent = true;
105
106
    /**
107
     * @var boolean whether the labels for header items should be HTML-encoded.
108
     */
109
    public $encodeLabels = true;
110
111
    /**
112
     * @var boolean whether the tab width for header items should be fixed.
113
     */
114
    public $fixedWidth = false;
115
116
    /**
117
     * Initializes the widget.
118
     */
119
    public function init()
120
    {
121
        parent::init();
122
        
123
        Html::addCssClass($this->options, ['widget' => 'tabs']);
124
125
        if ($this->fixedWidth) {
126
            Html::addCssClass($this->options, ['width' => 'tabs-fixed-width']);
127
        }
128
    }
129
130
    /**
131
     * Renders the widget.
132
     */
133
    public function run()
134
    {
135
        $this->initializePlugin = true;
136
        $this->registerPlugin('tabs');
137
        return $this->renderItems();
138
    }
139
140
    /**
141
     * Renders tab items as specified on [[items]].
142
     *
143
     * @return string the rendering result.
144
     * @throws InvalidConfigException.
145
     */
146
    protected function renderItems()
147
    {
148
        $headers = [];
149
        $panes = [];
150
151
        if (!$this->hasActiveTab() && !empty($this->items)) {
152
            $this->items[0]['active'] = true;
153
        }
154
155
        foreach ($this->items as $index => $item) {
156
            list($header, $content) = $this->renderItem($index, $item);
157
158
            $headers[] = $header;
159
160
            if (!empty($content)) {
161
                $panes[] = $content;
162
            }
163
        }
164
165
        $html = Html::tag('ul', implode("\n", $headers), $this->options);
166
        $html .= $this->renderTabContent
167
            ? "\n" . Html::tag('div', implode("\n", $panes), ['class' => 'tab-content'])
168
            : '';
169
170
        return $html;
171
    }
172
173
    /**
174
     * Renders single tab item as specified on [[items]].
175
     *
176
     * @param int $index tab serial number
177
     * @param array $item single tab element
178
     * @return array returns array containing tab header and content [header, content]
179
     * @throws InvalidConfigException.
180
     */
181
    protected function renderItem($index, $item)
182
    {
183
        if (!array_key_exists('label', $item)) {
184
            throw new InvalidConfigException("The 'label' option is required.");
185
        } elseif (ArrayHelper::remove($item, 'visible', true)) {
186
            $encodeLabel = isset($item['encode']) ? $item['encode'] : $this->encodeLabels;
187
            $label = $encodeLabel ? Html::encode($item['label']) : $item['label'];
188
            $headerOptions = array_merge($this->headerOptions, ArrayHelper::getValue($item, 'headerOptions', []));
189
            $linkOptions = array_merge($this->linkOptions, ArrayHelper::getValue($item, 'linkOptions', []));
190
            $options = array_merge($this->itemOptions, ArrayHelper::getValue($item, 'options', []));
191
            $options['id'] = ArrayHelper::getValue($options, 'id', $this->options['id'] . '-tab' . $index);
192
193
            Html::addCssClass($options, 'col s12');
194
195
            // Add active tab and content
196
            if (ArrayHelper::remove($item, 'active')) {
197
                Html::addCssClass($options, 'active');
198
                Html::addCssClass($headerOptions, ['active', 'tab']);
199
            } else {
200
                Html::addCssClass($headerOptions, 'tab');
201
            }
202
203
            // Add disabled tab and content
204
            if (ArrayHelper::remove($item, 'disabled')) {
205
                Html::addCssClass($headerOptions, 'disabled');
206
            }
207
208
            // Add tab header
209
            if (isset($item['url'])) {
210
                $linkOptions['target'] = isset($linkOptions['target']) ? $linkOptions['target'] : '_self';
211
                $header = Html::a($label, $item['url'], $linkOptions);
212
            } else {
213
                $header = Html::a($label, '#' . $options['id'], $linkOptions);
214
            }
215
216
            // Add tab content
217
            if ($this->renderTabContent) {
218
                $tag = ArrayHelper::remove($options, 'tag', 'div');
219
                $content = Html::tag($tag, isset($item['content']) ? $item['content'] : '', $options);
220
            } else {
221
                $content = null;
222
            }
223
224
            $header = Html::tag('li', $header, $headerOptions);
225
        }
226
227
        return [$header, $content];
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $header does not seem to be defined for all execution paths leading up to this point.
Loading history...
Comprehensibility Best Practice introduced by
The variable $content does not seem to be defined for all execution paths leading up to this point.
Loading history...
228
    }
229
230
    /**
231
     * Searches for active tab value in [[items]]
232
     * @return boolean if there's active tab defined
233
     */
234
    protected function hasActiveTab()
235
    {
236
        foreach ($this->items as $item) {
237
            if (isset($item['active']) && $item['active'] === true) {
238
                return true;
239
            }
240
        }
241
242
        return false;
243
    }
244
}
245