Passed
Pull Request — master (#22)
by Mr.
02:05
created

Accordion::renderItems()   B

Complexity

Conditions 7
Paths 13

Size

Total Lines 32
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 17
CRAP Score 7.0084

Importance

Changes 0
Metric Value
cc 7
eloc 17
nc 13
nop 0
dl 0
loc 32
ccs 17
cts 18
cp 0.9444
crap 7.0084
rs 8.8333
c 0
b 0
f 0
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
 *     ->items([
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
class Accordion extends Widget
59
{
60
    private array $items = [];
61
    private bool $encodeLabels = true;
62
    private bool $autoCloseItems = true;
63
    private array $itemToggleOptions = [];
64
    private array $options = [];
65
66 7
    protected function run(): string
67
    {
68 7
        if (!isset($this->options['id'])) {
69 7
            $this->options['id'] = "{$this->getId()}-accordion";
70
        }
71
72 7
        $this->registerPlugin('collapse', $this->options);
73
74 7
        Html::addCssClass($this->options, 'accordion');
75
76 7
        return Html::div($this->renderItems(), $this->options);
77
    }
78
79
    /**
80
     * Renders collapsible items as specified on {@see items}.
81
     *
82
     * @throws JsonException|RuntimeException
83
     *
84
     * @return string the rendering result
85
     */
86 7
    public function renderItems(): string
87
    {
88 7
        $items = [];
89 7
        $index = 0;
90 7
        $expanded = array_search(true, array_column($this->items, 'expand'), true);
91
92 7
        foreach ($this->items as $key => $item) {
93 7
            if (!is_array($item)) {
94 1
                $item = ['content' => $item];
95
            }
96
97 7
            if ($expanded === false && $index === 0) {
98 6
                $item['expand'] = true;
99
            }
100
101 7
            if (!array_key_exists('label', $item)) {
102 3
                if (is_int($key)) {
103 3
                    throw new RuntimeException('The "label" option is required.');
104
                }
105
106
                $item['label'] = $key;
107
            }
108
109 4
            $header = ArrayHelper::remove($item, 'label');
110 4
            $options = ArrayHelper::getValue($item, 'options', []);
111
112 4
            Html::addCssClass($options, ['panel' => 'accordion-item']);
113
114 4
            $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

114
            $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

114
            $items[] = Html::div($this->renderItem($header, /** @scrutinizer ignore-type */ $item, $index++), $options);
Loading history...
115
        }
116
117 4
        return implode("\n", $items);
118
    }
119
120
    /**
121
     * Renders a single collapsible item group.
122
     *
123
     * @param string $header a label of the item group {@see items}
124
     * @param array $item a single item from {@see items}
125
     * @param int $index the item index as each item group content must have an id
126
     *
127
     * @throws JsonException|RuntimeException
128
     *
129
     * @return string the rendering result
130
     */
131 4
    public function renderItem(string $header, array $item, int $index): string
132
    {
133 4
        if (array_key_exists('content', $item)) {
134 4
            $id = $this->options['id'] . '-collapse' . $index;
135 4
            $expand = ArrayHelper::remove($item, 'expand', false);
136 4
            $options = ArrayHelper::getValue($item, 'contentOptions', []);
137 4
            $options['id'] = $id;
138
139 4
            Html::addCssClass($options, ['accordion-body', 'collapse']);
140
141 4
            if ($expand) {
142 4
                Html::addCssClass($options, 'show');
143
            }
144
145 4
            if (!isset($options['aria-label'], $options['aria-labelledby'])) {
146 4
                $options['aria-labelledby'] = $options['id'] . '-heading';
147
            }
148
149 4
            $encodeLabel = $item['encode'] ?? $this->encodeLabels;
150
151 4
            if ($encodeLabel) {
152 4
                $header = Html::encode($header);
153
            }
154
155 4
            $itemToggleOptions = array_merge([
156 4
                'tag' => 'button',
157 4
                'type' => 'button',
158 4
                'data-toggle' => 'collapse',
159 4
                'data-target' => '#' . $options['id'],
160 4
                'aria-expanded' => $expand ? 'true' : 'false',
161 4
            ], $this->itemToggleOptions);
162 4
            $itemToggleTag = ArrayHelper::remove($itemToggleOptions, 'tag', 'button');
163
164
            /** @psalm-suppress ConflictingReferenceConstraint */
165 4
            if ($itemToggleTag === 'a') {
166 1
                ArrayHelper::remove($itemToggleOptions, 'data-target');
167 1
                $header = Html::a($header, '#' . $id, $itemToggleOptions) . "\n";
168
            } else {
169 3
                Html::addCssClass($itemToggleOptions, 'accordion-button');
170 3
                if (!$expand) {
171 3
                    Html::addCssClass($itemToggleOptions, 'collapsed');
172
                }
173 3
                $header = Html::button($header, $itemToggleOptions);
174
            }
175
176 4
            if (is_string($item['content']) || is_numeric($item['content']) || is_object($item['content'])) {
177 4
                $content = $item['content'];
178 1
            } elseif (is_array($item['content'])) {
179 1
                $content = Html::ul($item['content'], [
180 1
                    'class' => 'list-group',
181
                    'itemOptions' => [
182
                        'class' => 'list-group-item',
183
                    ],
184
                    'encode' => false,
185 1
                ]) . "\n";
186
            } else {
187 4
                throw new RuntimeException('The "content" option should be a string, array or object.');
188
            }
189
        } else {
190
            throw new RuntimeException('The "content" option is required.');
191
        }
192
193 4
        $group = [];
194
195 4
        if ($this->autoCloseItems) {
196 4
            $options['data-parent'] = '#' . $this->options['id'];
197
        }
198
199
200 4
        $group[] = Html::tag('h2', $header, ['class' => 'accordion-header', 'id' => $options['id'] . '-heading']);
201 4
        $group[] = Html::div($content, $options);
202
203 4
        return implode("\n", $group);
204
    }
205
206
    /**
207
     * Whether to close other items if an item is opened. Defaults to `true` which causes an accordion effect.
208
     *
209
     * Set this to `false` to allow keeping multiple items open at once.
210
     *
211
     * @param bool $value
212
     *
213
     * @return $this
214
     */
215 1
    public function autoCloseItems(bool $value): self
216
    {
217 1
        $this->autoCloseItems = $value;
218
219 1
        return $this;
220
    }
221
222
    /**
223
     * Whether the labels for header items should be HTML-encoded.
224
     *
225
     * @param bool $value
226
     *
227
     * @return $this
228
     */
229
    public function encodeLabels(bool $value): self
230
    {
231
        $this->encodeLabels = $value;
232
233
        return $this;
234
    }
235
236
    /**
237
     * List of groups in the collapse widget. Each array element represents a single group with the following structure:
238
     *
239
     * - label: string, required, the group header label.
240
     * - encode: bool, optional, whether this label should be HTML-encoded. This param will override global
241
     *   `$this->encodeLabels` param.
242
     * - content: array|string|object, required, the content (HTML) of the group
243
     * - options: array, optional, the HTML attributes of the group
244
     * - contentOptions: optional, the HTML attributes of the group's content
245
     *
246
     * You may also specify this property as key-value pairs, where the key refers to the `label` and the value refers
247
     * to `content`. If value is a string it is interpreted as label. If it is an array, it is interpreted as explained
248
     * above.
249
     *
250
     * For example:
251
     *
252
     * ```php
253
     * echo Accordion::widget([
254
     *     'items' => [
255
     *       'Introduction' => 'This is the first collapsible menu',
256
     *       'Second panel' => [
257
     *           'content' => 'This is the second collapsible menu',
258
     *       ],
259
     *       [
260
     *           'label' => 'Third panel',
261
     *           'content' => 'This is the third collapsible menu',
262
     *       ],
263
     *   ]
264
     * ])
265
     * ```
266
     *
267
     * @param array $value
268
     *
269
     * @return $this
270
     */
271 7
    public function items(array $value): self
272
    {
273 7
        $this->items = $value;
274
275 7
        return $this;
276
    }
277
278
    /**
279
     * The HTML options for the item toggle tag. Key 'tag' might be used here for the tag name specification.
280
     *
281
     * For example:
282
     *
283
     * ```php
284
     * [
285
     *     'tag' => 'div',
286
     *     'class' => 'custom-toggle',
287
     * ]
288
     * ```
289
     *
290
     * @param array $value
291
     *
292
     * @return $this
293
     */
294 1
    public function itemToggleOptions(array $value): self
295
    {
296 1
        $this->itemToggleOptions = $value;
297
298 1
        return $this;
299
    }
300
301
    /**
302
     * The HTML attributes for the widget container tag. The following special options are recognized.
303
     *
304
     * {@see \Yiisoft\Html\Html::renderTagAttributes()} for details on how attributes are being rendered.
305
     *
306
     * @param array $value
307
     *
308
     * @return $this
309
     */
310
    public function options(array $value): self
311
    {
312
        $this->options = $value;
313
314
        return $this;
315
    }
316
}
317