Test Failed
Pull Request — master (#35)
by Wilmer
02:28
created

ButtonDropdown::withDirection()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 3
c 0
b 0
f 0
nc 1
nop 1
dl 0
loc 6
ccs 3
cts 3
cp 1
crap 1
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Yii\Bootstrap5;
6
7
use Yiisoft\Arrays\ArrayHelper;
8
use Yiisoft\Factory\Exceptions\InvalidConfigException;
9
use Yiisoft\Html\Html;
10
11
/**
12
 * ButtonDropdown renders a group or split button dropdown bootstrap component.
13
 *
14
 * For example,
15
 *
16
 * ```php
17
 * // a button group using Dropdown widget
18
 * echo ButtonDropdown::widget()
19
 *     ->label('Action')
20
 *     ->dropdown'([
21
 *         'items' => [
22
 *             ['label' => 'DropdownA', 'url' => '/'],
23
 *             ['label' => 'DropdownB', 'url' => '#'],
24
 *         ],
25
 *     ]);
26
 * ```
27
 */
28
final class ButtonDropdown extends Widget
29
{
30
    /**
31
     * The css class part of dropdown
32
     */
33
    public const DIRECTION_DOWN = 'down';
34
35
    /**
36
     * The css class part of dropleft
37
     */
38
    public const DIRECTION_LEFT = 'left';
39
40
    /**
41
     * The css class part of dropright
42
     */
43
    public const DIRECTION_RIGHT = 'right';
44
45
    /**
46
     * The css class part of dropup
47
     */
48
    public const DIRECTION_UP = 'up';
49
50
    private string $label = 'Button';
51
    private array $options = [];
52
    private array $buttonOptions = [];
53
    private array $dropdown = [];
54
    private string $direction = self::DIRECTION_DOWN;
55
    private bool $split = false;
56
    private string $tagName = 'button';
57
    private bool $encodeLabels = true;
58
    private bool $encodeTags = false;
59
    private string $dropdownClass = Dropdown::class;
60
    private bool $renderContainer = true;
61 3
62
    public function run(): string
63
    {
64 3
        if (!isset($this->dropdown['items'])) {
65 3
            return '';
66
        }
67 3
68 3
        /** Set options id to button options id to ensure correct css selector in plugin initialisation */
69
        if (empty($this->options['id'])) {
70
            $id = $this->getId();
71 3
72
            $this->options['id'] = "{$id}-button-dropdown";
73 3
            $this->buttonOptions['id'] = "{$id}-button";
74
        }
75 3
76
        if ($this->encodeTags === false) {
77 3
            $this->options = array_merge($this->options, ['encode' => false]);
78 3
        }
79 3
80
        $html = $this->renderButton() . "\n" . $this->renderDropdown();
81
82 3
        if ($this->renderContainer) {
83
            /** @psalm-suppress InvalidArgument */
84 3
            Html::addCssClass($this->options, ['widget' => 'drop' . $this->direction, 'btn-group']);
85
86
            $options = $this->options;
87
            $tag = ArrayHelper::remove($options, 'tag', 'div');
88
            $html = Html::tag($tag, $html, $options);
89
        }
90
91
        return $html;
92
    }
93
94 3
    /**
95
     * The HTML attributes of the button.
96 3
     *
97
     * {@see Html::renderTagAttributes()} for details on how attributes are being rendered.
98 3
     *
99
     * @param array $value
100 3
     *
101 3
     * @return $this
102
     */
103
    public function withButtonOptions(array $value): self
104 3
    {
105 1
        $new = clone $this;
106
        $new->buttonOptions = $value;
107 1
108 1
        return $new;
109 1
    }
110
111 1
    /**
112
     * The drop-direction of the widget.
113 1
     *
114
     * Possible values are 'left', 'right', 'up', or 'down' (default)
115 1
     *
116 1
     * @param string $value
117 1
     *
118 1
     * @return $this
119 1
     */
120
    public function withDirection(string $value): self
121 2
    {
122
        $new = clone $this;
123 2
        $new->direction = $value;
124
125 2
        return $new;
126 2
    }
127 2
128 2
    /**
129
     * The configuration array for example:
130
     *
131 3
     * ```php
132
     *    [
133
     *        'items' => [
134
     *            ['label' => 'DropdownA', 'url' => '/'],
135
     *            ['label' => 'DropdownB', 'url' => '#'],
136 3
     *        ],
137 3
     *    ]
138 3
     * ```
139 3
     *
140 3
     * {@see Dropdown}
141 3
     *
142 3
     * @param array $value
143
     *
144
     * @return $this
145
     */
146
    public function withDropdown(array $value): self
147
    {
148
        $new = clone $this;
149
        $new->dropdown = $value;
150 3
151
        return $new;
152 3
    }
153
154 3
    /**
155 3
     * Name of a class to use for rendering dropdowns withing this widget. Defaults to {@see Dropdown}.
156 3
     *
157
     * @param string $value
158
     *
159
     * @return $this
160
     */
161
    public function withDropdownClass(string $value): self
162
    {
163
        $new = clone $this;
164
        $new->dropdownClass = $value;
165
166
        return $new;
167
    }
168
169
    /**
170
     * Whether the label should be HTML-encoded.
171
     *
172
     * @param bool $value
173
     *
174
     * @return $this
175
     */
176
    public function withoutEncodeLabels(bool $value = false): self
177
    {
178
        $new = clone $this;
179
        $new->encodeLabels = $value;
180
181
        return $new;
182
    }
183
184 3
    /**
185
     * The button label.
186 3
     *
187
     * @param string $value
188 3
     *
189
     * @return $this
190
     */
191
    public function withLabel(string $value): self
192
    {
193
        $new = clone $this;
194
        $new->label = $value;
195
196
        return $new;
197
    }
198
199
    /**
200
     * The HTML attributes for the container tag. The following special options are recognized.
201
     *
202
     * {@see Html::renderTagAttributes()} for details on how attributes are being rendered.
203
     *
204
     * @param array $value
205
     *
206
     * @return $this
207
     */
208
    public function withOptions(array $value): self
209 3
    {
210
        $new = clone $this;
211 3
        $new->options = $value;
212
213 3
        return $new;
214
    }
215
216
    /**
217
     * Whether to render the container using the {@see options} as HTML attributes. If set to `false`, the container
218
     * element enclosing the button and dropdown will NOT be rendered.
219
     *
220
     * @param bool $value
221
     *
222
     * @return $this
223
     */
224
    public function withoutRenderContainer(bool $value = false): self
225
    {
226
        $new = clone $this;
227
        $new->renderContainer = $value;
228
229
        return $new;
230
    }
231
232
    /**
233
     * Whether to display a group of split-styled button group.
234
     *
235
     * @param bool $value
236
     *
237
     * @return $this
238
     */
239
    public function withSplit(bool $value = true): self
240
    {
241
        $new = clone $this;
242
        $new->split = $value;
243
244
        return $new;
245
    }
246
247
    /**
248
     * The tag to use to render the button.
249
     *
250
     * @param string $value
251 3
     *
252
     * @return $this
253 3
     */
254
    public function withTagName(string $value): self
255 3
    {
256
        $new = clone $this;
257
        $new->tagName = $value;
258
259
        return $new;
260
    }
261
262
    /**
263
     * Allows you to enable or disable the encoding tags html.
264
     *
265
     * @param bool $value
266
     *
267 1
     * @return self
268
     */
269 1
    public function withEncodeTags(bool $value = true): self
270
    {
271 1
        $new = clone $this;
272
        $new->encodeTags = $value;
273
274
        return $new;
275
    }
276
277
    /**
278
     * Generates the button dropdown.
279
     *
280
     * @throws InvalidConfigException
281
     *
282
     * @return string the rendering result.
283
     */
284
    private function renderButton(): string
285
    {
286
        Html::addCssClass($this->buttonOptions, 'btn');
287
288
        $label = $this->label;
289
290
        if ($this->encodeLabels !== false) {
291
            $label = Html::encode($label);
292
        }
293
294
        if ($this->split) {
295
            $buttonOptions = $this->buttonOptions;
296 1
297
            $this->buttonOptions['data-bs-toggle'] = 'dropdown';
298 1
            $this->buttonOptions['aria-haspopup'] = 'true';
299
            $this->buttonOptions['aria-expanded'] = 'false';
300 1
301
            Html::addCssClass($this->buttonOptions, ['toggle' => 'dropdown-toggle dropdown-toggle-split']);
302
303
            unset($buttonOptions['id']);
304
305
            $splitButton = Button::widget()
306
                ->withLabel('<span class="sr-only">Toggle Dropdown</span>')
0 ignored issues
show
Bug introduced by
The method withLabel() does not exist on Yiisoft\Widget\Widget. It seems like you code against a sub-type of Yiisoft\Widget\Widget such as Yiisoft\Yii\Bootstrap5\Button or Yiisoft\Yii\Bootstrap5\ButtonDropdown. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

306
                ->/** @scrutinizer ignore-call */ withLabel('<span class="sr-only">Toggle Dropdown</span>')
Loading history...
307
                ->withoutEncodeLabels()
308
                ->withOptions($this->buttonOptions)
309
                ->render();
310
        } else {
311
            $buttonOptions = $this->buttonOptions;
312
313
            Html::addCssClass($buttonOptions, ['toggle' => 'dropdown-toggle']);
314
315
            $buttonOptions['data-bs-toggle'] = 'dropdown';
316
            $buttonOptions['aria-haspopup'] = 'true';
317
            $buttonOptions['aria-expanded'] = 'false';
318
            $splitButton = '';
319
        }
320
321
        if (!isset($buttonOptions['href']) && ($this->tagName === 'a')) {
322
            $buttonOptions['href'] = '#';
323
            $buttonOptions['role'] = 'button';
324
        }
325
326
        return Button::widget()
327
            ->withTagName($this->tagName)
0 ignored issues
show
Bug introduced by
The method withTagName() does not exist on Yiisoft\Widget\Widget. It seems like you code against a sub-type of Yiisoft\Widget\Widget such as Yiisoft\Yii\Bootstrap5\Button or Yiisoft\Yii\Bootstrap5\ButtonDropdown. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

327
            ->/** @scrutinizer ignore-call */ withTagName($this->tagName)
Loading history...
328
            ->withLabel($label)
329
            ->withOptions($buttonOptions)
330
            ->withoutEncodeLabels()
331
            ->render()
332
            . "\n" . $splitButton;
333
    }
334
335
    /**
336
     * Generates the dropdown menu.
337
     *
338
     * @return string the rendering result.
339
     */
340
    private function renderDropdown(): string
341
    {
342
        $dropdownClass = $this->dropdownClass;
343
344
        return $dropdownClass::widget()
345
            ->withItems($this->dropdown['items'])
346
            ->withoutEncodeLabels($this->encodeLabels)
347
            ->render();
348
    }
349
}
350