Passed
Pull Request — master (#35)
by Wilmer
03:14 queued 52s
created

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

242
            $items[] = Html::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

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