Passed
Pull Request — master (#17)
by Mr.
02:30
created

Accordion::items()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 1
dl 0
loc 5
ccs 3
cts 3
cp 1
crap 1
rs 10
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 Yiisoft\Arrays\ArrayHelper;
9
use Yiisoft\Html\Html;
10
use Yiisoft\Widget\Exception\InvalidConfigException;
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 implode("\n", [
77 7
            Html::beginTag('div', $this->options),
78 7
            $this->renderItems(),
79 4
            Html::endTag('div'),
80 4
        ]) . "\n";
81
    }
82
83
    /**
84
     * Renders collapsible items as specified on {@see items}.
85
     *
86
     * @throws InvalidConfigException|JsonException
87
     *
88
     * @return string the rendering result
89
     */
90 7
    public function renderItems(): string
91
    {
92 7
        $items = [];
93 7
        $index = 0;
94 7
        $expanded = array_search(true, array_column(ArrayHelper::toArray($this->items), 'expand'));
95
96 7
        foreach ($this->items as $key => $item) {
97 7
            if (!is_array($item)) {
98 1
                $item = ['content' => $item];
99
            }
100
101 7
            if ($expanded === false && $index === 0) {
102 6
                $item['expand'] = true;
103
            }
104
105 7
            if (!array_key_exists('label', $item)) {
106 3
                if (is_int($key)) {
107 3
                    throw new InvalidConfigException("The 'label' option is required.");
108
                }
109
110
                $item['label'] = $key;
111
            }
112
113 4
            $header = ArrayHelper::remove($item, 'label');
114 4
            $options = ArrayHelper::getValue($item, 'options', []);
115
116 4
            Html::addCssClass($options, ['panel' => 'accordion-item']);
117
118 4
            $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

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

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