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

Accordion::withItems()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 3
c 1
b 0
f 0
nc 1
nop 1
dl 0
loc 6
ccs 4
cts 4
cp 1
crap 1
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Yii\Bootstrap5;
6
7
use JsonException;
8
use RuntimeException;
9
use Yiisoft\Arrays\ArrayHelper;
10
use Yiisoft\Html\Html;
11
12
use function array_column;
13
use function array_key_exists;
14
use function array_merge;
15
use function array_search;
16
use function implode;
17
use function is_array;
18
use function is_int;
19
use function is_numeric;
20
use function is_object;
21
use function is_string;
22
23
/**
24
 * Accordion renders an accordion bootstrap javascript component.
25
 *
26
 * For example:
27
 *
28
 * ```php
29
 * echo Accordion::widget()
30
 *     ->witItems([
31
 *         [
32
 *             'label' => 'Collapsible Group Item #1',
33
 *             'content' => 'Anim pariatur cliche...',
34
 *             // open its content by default
35
 *             'contentOptions' => ['class' => 'show'],
36
 *         ],
37
 *         // another group item
38
 *         [
39
 *             'label' => 'Collapsible Group Item #2',
40
 *             'content' => 'Anim pariatur cliche...',
41
 *             'contentOptions' => [...],
42
 *             'options' => [...],
43
 *             'expand' => true,
44
 *         ],
45
 *         // if you want to swap out .accordion-body with .list-group, you may provide an array
46
 *         [
47
 *             'label' => 'Collapsible Group Item #3',
48
 *             'content' => [
49
 *                 'Anim pariatur cliche...',
50
 *                 'Anim pariatur cliche...',
51
 *             ],
52
 *             'contentOptions' => [...],
53
 *             'options' => [...],
54
 *         ],
55
 *     ]);
56
 * ```
57
 */
58
final class Accordion extends Widget
59
{
60
    private array $items = [];
61
    private bool $encodeLabels = true;
62
    private bool $encodeTags = false;
63
    private bool $autoCloseItems = true;
64
    private array $itemToggleOptions = [];
65
    private array $options = [];
66 7
67
    public function run(): string
68 7
    {
69 7
        if (!isset($this->options['id'])) {
70
            $this->options['id'] = "{$this->getId()}-accordion";
71
        }
72 7
73
        $this->registerPlugin('collapse', $this->options);
74
75 7
        /** @psalm-suppress InvalidArgument */
76
        Html::addCssClass($this->options, 'accordion');
77 7
78
        if ($this->encodeTags === false) {
79
            $this->options = array_merge($this->options, ['encode' => false]);
80
        }
81
82
        return Html::div($this->renderItems(), $this->options);
83
    }
84
85
    /**
86
     * Whether to close other items if an item is opened. Defaults to `true` which causes an accordion effect.
87 7
     *
88
     * Set this to `false` to allow keeping multiple items open at once.
89 7
     *
90 7
     * @param bool $value
91 7
     *
92
     * @return $this
93 7
     */
94 7
    public function withAutoCloseItems(bool $value): self
95 1
    {
96
        $new = clone $this;
97
        $new->autoCloseItems = $value;
98 7
99 6
        return $new;
100
    }
101
102 7
    /**
103 3
     * Whether the labels for header items should be HTML-encoded.
104 3
     *
105
     * @param bool $value
106
     *
107
     * @return $this
108
     */
109
    public function withEncodeLabels(bool $value): self
110 4
    {
111 4
        $new = clone $this;
112
        $new->encodeLabels = $value;
113 4
114
        return $new;
115 4
    }
116
117
    /**
118 4
     * List of groups in the collapse widget. Each array element represents a single group with the following structure:
119
     *
120
     * - label: string, required, the group header label.
121
     * - encode: bool, optional, whether this label should be HTML-encoded. This param will override global
122
     *   `$this->encodeLabels` param.
123
     * - content: array|string|object, required, the content (HTML) of the group
124
     * - options: array, optional, the HTML attributes of the group
125
     * - contentOptions: optional, the HTML attributes of the group's content
126
     *
127
     * You may also specify this property as key-value pairs, where the key refers to the `label` and the value refers
128
     * to `content`. If value is a string it is interpreted as label. If it is an array, it is interpreted as explained
129
     * above.
130
     *
131
     * For example:
132 4
     *
133
     * ```php
134 4
     * echo Accordion::widget([
135 4
     *     'withItems' => [
136 4
     *       'Introduction' => 'This is the first collapsible menu',
137 4
     *       'Second panel' => [
138 4
     *           'content' => 'This is the second collapsible menu',
139
     *       ],
140 4
     *       [
141
     *           'label' => 'Third panel',
142 4
     *           'content' => 'This is the third collapsible menu',
143 4
     *       ],
144
     *   ]
145
     * ])
146 4
     * ```
147 4
     *
148
     * @param array $value
149
     *
150 4
     * @return $this
151
     */
152 4
    public function withItems(array $value): self
153 4
    {
154
        $new = clone $this;
155
        $new->items = $value;
156 4
157 4
        return $new;
158 4
    }
159 4
160 4
    /**
161 4
     * The HTML options for the item toggle tag. Key 'tag' might be used here for the tag name specification.
162 4
     *
163 4
     * For example:
164
     *
165
     * ```php
166 4
     * [
167 1
     *     'tag' => 'div',
168 1
     *     'class' => 'custom-toggle',
169
     * ]
170 3
     * ```
171 3
     *
172 3
     * @param array $value
173
     *
174 3
     * @return $this
175
     */
176
    public function withItemToggleOptions(array $value): self
177 4
    {
178 4
        $new = clone $this;
179 1
        $new->itemToggleOptions = $value;
180 1
181 1
        return $new;
182
    }
183
184
    /**
185
     * The HTML attributes for the widget container tag. The following special options are recognized.
186 1
     *
187
     * {@see Html::renderTagAttributes()} for details on how attributes are being rendered.
188 4
     *
189
     * @param array $value
190
     *
191
     * @return $this
192
     */
193
    public function withOptions(array $value): self
194 4
    {
195
        $new = clone $this;
196 4
        $new->options = $value;
197 4
198
        return $new;
199
    }
200
201 4
    /**
202 4
     * Allows you to enable or disable the encoding tags html.
203
     *
204 4
     * @param bool $value
205
     *
206
     * @return self
207
     */
208
    public function withencodeTags(bool $value): self
209
    {
210
        $new = clone $this;
211
        $new->encodeTags = $value;
212
213
        return $new;
214
    }
215
216 1
    /**
217
     * Renders collapsible items as specified on {@see items}.
218 1
     *
219
     * @throws JsonException|RuntimeException
220 1
     *
221
     * @return string the rendering result
222
     */
223
    private function renderItems(): string
224
    {
225
        $items = [];
226
        $index = 0;
227
        $expanded = array_search(true, array_column($this->items, 'expand'), true);
228
229
        foreach ($this->items as $key => $item) {
230
            if (!is_array($item)) {
231
                $item = ['content' => $item];
232
            }
233
234
            if ($expanded === false && $index === 0) {
235
                $item['expand'] = true;
236
            }
237
238
            if (!array_key_exists('label', $item)) {
239
                throw new RuntimeException('The "label" option is required.');
240
            }
241
242
            $header = ArrayHelper::remove($item, 'label');
243
            $options = ArrayHelper::getValue($item, 'options', []);
244
245
            if ($this->encodeTags === false) {
246
                $options = array_merge($options, ['encode' => false]);
247
            }
248
249
            Html::addCssClass($options, ['panel' => 'accordion-item']);
250
251
            $items[] = Html::div($this->renderItem($header, $item, $index++), $options);
0 ignored issues
show
Bug introduced by
It seems like $header can also be of type null; however, parameter $header of Yiisoft\Yii\Bootstrap5\Accordion::renderItem() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

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

251
            $items[] = Html::div($this->renderItem(/** @scrutinizer ignore-type */ $header, $item, $index++), $options);
Loading history...
Bug introduced by
It seems like $item can also be of type object; however, parameter $item of Yiisoft\Yii\Bootstrap5\Accordion::renderItem() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

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

251
            $items[] = Html::div($this->renderItem($header, /** @scrutinizer ignore-type */ $item, $index++), $options);
Loading history...
252
        }
253
254
        return implode("\n", $items);
255
    }
256
257
    /**
258
     * Renders a single collapsible item group.
259
     *
260
     * @param string $header a label of the item group {@see items}
261
     * @param array $item a single item from {@see items}
262
     * @param int $index the item index as each item group content must have an id
263
     *
264
     * @throws JsonException|RuntimeException
265
     *
266
     * @return string the rendering result
267
     */
268
    private function renderItem(string $header, array $item, int $index): string
269
    {
270
        if (array_key_exists('content', $item)) {
271
            $id = $this->options['id'] . '-collapse' . $index;
272 7
            $expand = ArrayHelper::remove($item, 'expand', false);
273
            $options = ArrayHelper::getValue($item, 'contentOptions', []);
274 7
            $options['id'] = $id;
275
276 7
            Html::addCssClass($options, ['accordion-body', 'collapse']);
277
278
            if ($expand) {
279
                Html::addCssClass($options, 'show');
280
            }
281
282
            if (!isset($options['aria-label'], $options['aria-labelledby'])) {
283
                $options['aria-labelledby'] = $options['id'] . '-heading';
284
            }
285
286
            $encodeLabel = $item['encode'] ?? $this->encodeLabels;
287
288
            if ($encodeLabel) {
289
                $header = Html::encode($header);
290
            }
291
292
            $itemToggleOptions = array_merge([
293
                'tag' => 'button',
294
                'type' => 'button',
295 1
                'data-bs-toggle' => 'collapse',
296
                'data-bs-target' => '#' . $options['id'],
297 1
                'aria-expanded' => $expand ? 'true' : 'false',
298
            ], $this->itemToggleOptions);
299 1
300
            if ($this->encodeTags === false) {
301
                $itemToggleOptions = array_merge($itemToggleOptions, ['encode' => false]);
302
            }
303
304
            $itemToggleTag = ArrayHelper::remove($itemToggleOptions, 'tag', 'button');
305
306
            /** @psalm-suppress ConflictingReferenceConstraint */
307
            if ($itemToggleTag === 'a') {
308
                ArrayHelper::remove($itemToggleOptions, 'data-bs-target');
309
                $header = Html::a($header, '#' . $id, $itemToggleOptions) . "\n";
310
            } else {
311
                Html::addCssClass($itemToggleOptions, 'accordion-button');
312
                if (!$expand) {
313
                    Html::addCssClass($itemToggleOptions, 'collapsed');
314
                }
315
                $header = Html::button($header, $itemToggleOptions);
316
            }
317
318
            if (is_string($item['content']) || is_numeric($item['content']) || is_object($item['content'])) {
319
                $content = $item['content'];
320
            } elseif (is_array($item['content'])) {
321
                $ulOptions = ['class' => 'list-group'];
322
                $ulItemOptions = ['itemOptions' => ['class' => 'list-group-item']];
323
324
                if ($this->encodeTags === false) {
325
                    $ulOptions = array_merge($ulOptions, ['encode' => false]);
326
                    $ulItemOptions['itemOptions'] = array_merge($ulItemOptions['itemOptions'], ['encode' => false]);
327
                }
328
329
                $content = Html::ul($item['content'], array_merge($ulOptions, $ulItemOptions)) . "\n";
330
            } else {
331
                throw new RuntimeException('The "content" option should be a string, array or object.');
332
            }
333
        } else {
334
            throw new RuntimeException('The "content" option is required.');
335
        }
336
337
        $group = [];
338
339
        if ($this->autoCloseItems) {
340
            $options['data-bs-parent'] = '#' . $this->options['id'];
341
        }
342
343
        $groupOptions = ['class' => 'accordion-header', 'id' => $options['id'] . '-heading'];
344
345
        if ($this->encodeTags === false) {
346
            $options = array_merge($options, ['encode' => false]);
347
            $groupOptions = array_merge($groupOptions, ['encode' => false]);
348
        }
349
350
        $group[] = Html::tag('h2', $header, $groupOptions);
351
        $group[] = Html::div($content, $options);
352
353
        return implode("\n", $group);
354
    }
355
}
356