Completed
Push — master ( b9347c...09052b )
by Dmitrijs
02:21
created

Tabs::renderItems()   F

Complexity

Conditions 15
Paths 394

Size

Total Lines 59
Code Lines 36

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 36
dl 0
loc 59
rs 2.6583
c 0
b 0
f 0
cc 15
nc 394
nop 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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
 * @see https://materializecss.com/tabs.html
50
 * @package widgets
51
 */
52
class Tabs extends Widget
53
{
54
    /**
55
     * @var array list of tabs in the tabs widget. Each array element represents a single
56
     * tab with the following structure:
57
     *
58
     * - label: string, required, the tab header label.
59
     * - encode: boolean, optional, whether this label should be HTML-encoded. This param will override
60
     *   global `$this->encodeLabels` param.
61
     * - headerOptions: array, optional, the HTML attributes of the tab header.
62
     * - linkOptions: array, optional, the HTML attributes of the tab header link tags.
63
     * - content: string, optional, the content (HTML) of the tab pane.
64
     * - url: string, optional, an external URL. When this is specified, clicking on this tab will bring
65
     *   the browser to this URL
66
     * - options: array, optional, the HTML attributes of the tab pane container.
67
     * - active: boolean, optional, whether this item tab header and pane should be active. If no item is marked as
68
     *   'active' explicitly - the first one will be activated.
69
     * - visible: boolean, optional, whether the item tab header and pane should be visible or not. Defaults to true.
70
     * - disabled: boolean, optional, whether the item tab header and pane should be disabled or not. Defaults to false.
71
     */
72
    public $items = [];
73
74
    /**
75
     * @var array list of HTML attributes for the header container tags. This will be overwritten
76
     * by the "headerOptions" set in individual [[items]].
77
     * @see \yii\helpers\Html::renderTagAttributes() for details on how attributes are being rendered.
78
     */
79
    public $headerOptions = [];
80
81
    /**
82
     * @var array list of HTML attributes for the tab header link tags. This will be overwritten
83
     * by the "linkOptions" set in individual [[items]].
84
     * @see \yii\helpers\Html::renderTagAttributes() for details on how attributes are being rendered.
85
     */
86
    public $linkOptions = [];
87
88
    /**
89
     * @var array list of HTML attributes for the item container tags. This will be overwritten
90
     * by the "options" set in individual [[items]]. The following special options are recognized:
91
     *
92
     * - tag: string, defaults to "div", the tag name of the item container tags.
93
     *
94
     * @see \yii\helpers\Html::renderTagAttributes() for details on how attributes are being rendered.
95
     */
96
    public $itemOptions = [];
97
98
    /**
99
     * @var boolean whether to render the `tab-content` container and its content. You may set this property
100
     * to be false so that you can manually render `tab-content` yourself in case your tab contents are complex.
101
     */
102
    public $renderTabContent = true;
103
104
    /**
105
     * @var boolean whether the labels for header items should be HTML-encoded.
106
     */
107
    public $encodeLabels = true;
108
109
    /**
110
     * @var boolean whether the tab width for header items should be fixed.
111
     */
112
    public $fixedWidth = false;
113
114
    /**
115
     * Initializes the widget.
116
     */
117
    public function init()
118
    {
119
        parent::init();
120
        
121
        Html::addCssClass($this->options, ['widget' => 'tabs']);
122
123
        if ($this->fixedWidth) {
124
            Html::addCssClass($this->options, ['width' => 'tabs-fixed-width']);
125
        }
126
    }
127
128
    /**
129
     * Renders the widget.
130
     */
131
    public function run()
132
    {
133
        $this->initializePlugin = true;
0 ignored issues
show
Bug Best Practice introduced by
The property initializePlugin does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
134
        $this->registerPlugin('tabs');
135
        return $this->renderItems();
136
    }
137
138
    /**
139
     * Renders tab items as specified on [[items]].
140
     *
141
     * @return string the rendering result.
142
     * @throws InvalidConfigException.
143
     */
144
    protected function renderItems()
145
    {
146
        $headers = [];
147
        $panes = [];
148
149
        if (!$this->hasActiveTab() && !empty($this->items)) {
150
            $this->items[0]['active'] = true;
151
        }
152
153
        foreach ($this->items as $index => $item) {
154
            if (!array_key_exists('label', $item)) {
155
                throw new InvalidConfigException("The 'label' option is required.");
156
            } elseif (ArrayHelper::remove($item, 'visible', true)) {
157
                $encodeLabel = isset($item['encode']) ? $item['encode'] : $this->encodeLabels;
158
                $label = $encodeLabel ? Html::encode($item['label']) : $item['label'];
159
                $headerOptions = array_merge($this->headerOptions, ArrayHelper::getValue($item, 'headerOptions', []));
160
                $linkOptions = array_merge($this->linkOptions, ArrayHelper::getValue($item, 'linkOptions', []));
161
                $options = array_merge($this->itemOptions, ArrayHelper::getValue($item, 'options', []));
162
                $options['id'] = ArrayHelper::getValue($options, 'id', $this->options['id'] . '-tab' . $index);
163
164
                Html::addCssClass($options, 'col s12');
165
166
                // Add active tab and content
167
                if (ArrayHelper::remove($item, 'active')) {
168
                    Html::addCssClass($options, 'active');
169
                    Html::addCssClass($headerOptions, ['active', 'tab']);
170
                } else {
171
                    Html::addCssClass($headerOptions, 'tab');
172
                }
173
174
                // Add disabled tab and content
175
                if (ArrayHelper::remove($item, 'disabled')) {
176
                    Html::addCssClass($headerOptions, 'disabled');
177
                }
178
179
                // Add tab header
180
                if (isset($item['url'])) {
181
                    $linkOptions['target'] = isset($linkOptions['target']) ? $linkOptions['target'] : '_self';
182
                    $header = Html::a($label, $item['url'], $linkOptions);
183
                } else {
184
                    $header = Html::a($label, '#' . $options['id'], $linkOptions);
185
                }
186
187
                // Add tab content
188
                if ($this->renderTabContent) {
189
                    $tag = ArrayHelper::remove($options, 'tag', 'div');
190
                    $panes[] = Html::tag($tag, isset($item['content']) ? $item['content'] : '', $options);
191
                }
192
193
                $headers[] = Html::tag('li', $header, $headerOptions);
194
            }
195
        }
196
197
        $html = Html::tag('ul', implode("\n", $headers), $this->options);
198
        $html .= $this->renderTabContent
199
            ? "\n" . Html::tag('div', implode("\n", $panes), ['class' => 'tab-content'])
200
            : '';
201
202
        return $html;
203
    }
204
205
    /**
206
     * Searches for active tab value in [[items]]
207
     * @return boolean if there's active tab defined
208
     */
209
    protected function hasActiveTab()
210
    {
211
        foreach ($this->items as $item) {
212
            if (isset($item['active']) && $item['active'] === true) {
213
                return true;
214
            }
215
        }
216
217
        return false;
218
    }
219
}
220