Passed
Pull Request — master (#15)
by Mr.
02:38
created

Accordion::renderItems()   A

Complexity

Conditions 5
Paths 7

Size

Total Lines 27
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 14
CRAP Score 5.0073

Importance

Changes 0
Metric Value
cc 5
eloc 14
nc 7
nop 0
dl 0
loc 27
ccs 14
cts 15
cp 0.9333
crap 5.0073
rs 9.4888
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Yii\Bootstrap5;
6
7
use function array_key_exists;
8
use function array_merge;
9
use function implode;
10
use function is_array;
11
12
use function is_int;
13
use function is_numeric;
14
use function is_object;
15
use function is_string;
16
use JsonException;
17
use Yiisoft\Arrays\ArrayHelper;
18
use Yiisoft\Html\Html;
19
use Yiisoft\Widget\Exception\InvalidConfigException;
20
21
/**
22
 * Accordion renders an accordion bootstrap javascript component.
23
 *
24
 * For example:
25
 *
26
 * ```php
27
 * echo Accordion::widget()
28
 *     ->items([
29
 *         [
30
 *             'label' => 'Collapsible Group Item #1',
31
 *             'content' => 'Anim pariatur cliche...',
32
 *             // open its content by default
33
 *             'contentOptions' => ['class' => 'show'],
34
 *         ],
35
 *         // another group item
36
 *         [
37
 *             'label' => 'Collapsible Group Item #2',
38
 *             'content' => 'Anim pariatur cliche...',
39
 *             'contentOptions' => [...],
40
 *             'options' => [...],
41
 *         ],
42
 *         // if you want to swap out .accordion-body with .list-group, you may provide an array
43
 *         [
44
 *             'label' => 'Collapsible Group Item #3',
45
 *             'content' => [
46
 *                 'Anim pariatur cliche...',
47
 *                 'Anim pariatur cliche...',
48
 *             ],
49
 *             'contentOptions' => [...],
50
 *             'options' => [...],
51
 *         ],
52
 *     ]);
53
 * ```
54
 */
55
class Accordion extends Widget
56
{
57
    private array $items = [];
58
    private bool $encodeLabels = true;
59
    private bool $autoCloseItems = true;
60
    private array $itemToggleOptions = [];
61
    private array $options = [];
62
63 6
    protected function run(): string
64
    {
65 6
        if (!isset($this->options['id'])) {
66 6
            $this->options['id'] = "{$this->getId()}-accordion";
67
        }
68
69 6
        $this->registerPlugin('collapse', $this->options);
70
71 6
        Html::addCssClass($this->options, 'accordion');
72
73 6
        return implode("\n", [
74 6
            Html::beginTag('div', $this->options),
75 6
            $this->renderItems(),
76 3
            Html::endTag('div'),
77 3
        ]) . "\n";
78
    }
79
80
    /**
81
     * Renders collapsible items as specified on {@see items}.
82
     *
83
     * @throws InvalidConfigException|JsonException
84
     *
85
     * @return string the rendering result
86
     */
87 6
    public function renderItems(): string
88
    {
89 6
        $items = [];
90 6
        $index = 0;
91
92 6
        foreach ($this->items as $key => $item) {
93 6
            if (!is_array($item)) {
94 1
                $item = ['content' => $item];
95
            }
96
97 6
            if (!array_key_exists('label', $item)) {
98 3
                if (is_int($key)) {
99 3
                    throw new InvalidConfigException("The 'label' option is required.");
100
                }
101
102
                $item['label'] = $key;
103
            }
104
105 3
            $header = ArrayHelper::remove($item, 'label');
106 3
            $options = ArrayHelper::getValue($item, 'options', []);
107
108 3
            Html::addCssClass($options, ['panel' => 'accordion-item']);
109
110 3
            $items[] = Html::tag('div', $this->renderItem($header, $item, $index++), $options);
0 ignored issues
show
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

110
            $items[] = Html::tag('div', $this->renderItem($header, /** @scrutinizer ignore-type */ $item, $index++), $options);
Loading history...
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

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