Test Failed
Pull Request — master (#127)
by
unknown
13:20
created

Accordion::toggleOptions()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 1
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 3
c 0
b 0
f 0
nc 1
nop 1
dl 0
loc 6
rs 10
ccs 1
cts 1
cp 1
crap 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Yii\Bootstrap5;
6
7
use JsonException;
8
use RuntimeException;
9
use Stringable;
10
use Yiisoft\Arrays\ArrayHelper;
11
use Yiisoft\Html\Html;
12
use function array_key_exists;
13
use function implode;
14
use function is_array;
15
use function is_numeric;
16
use function is_string;
17
18
/**
19
 * Accordion renders an accordion bootstrap JavaScript component.
20
 *
21
 * For example:
22
 *
23
 * ```php
24
 * echo Accordion::widget()
25
 *     ->items([
26
 *         [
27
 *             'label' => 'Accordion Item #1',
28
 *             'content' => [
29
 *                 'This is the first items accordion body. It is shown by default, until the collapse plugin ' .
30
 *                 'the appropriate classes that we use to style each element. These classes control the ' .
31
 *                 'overall appearance, as well as the showing and hiding via CSS transitions. You can  ' .
32
 *                 'modify any of this with custom CSS or overriding our default variables. Its also worth ' .
33
 *                 'noting that just about any HTML can go within the .accordion-body, though the transition ' .
34
 *                 'does limit overflow.',
35
 *             ],
36
 *         ],
37
 *         [
38
 *             'label' => 'Accordion Item #2',
39
 *             'content' => '<strong>This is the second items accordion body.</strong> It is hidden by default, ' .
40
 *                 'until the collapse plugin adds the appropriate classes that we use to style each element. ' .
41
 *                 'These classes control the overall appearance, as well as the showing and hiding via CSS ' .
42
 *                 'transitions. You can modify any of this with custom CSS or overriding our default ' .
43
 *                 'variables. Its also worth noting that just about any HTML can go within the ' .
44
 *                 '<code>.accordion-body</code>, though the transition does limit overflow.',
45
 *             'contentOptions' => [
46
 *                 'class' => 'testContentOptions',
47
 *             ],
48
 *             'options' => [
49
 *                 'class' => 'testClass',
50
 *                 'id' => 'testId',
51
 *             ],
52
 *         ],
53
 *         [
54
 *             'label' => '<b>Accordion Item #3</b>',
55
 *             'content' => [
56
 *                 '<b>test content1</b>',
57
 *                 '<strong>This is the third items accordion body.</strong> It is hidden by default, until the ' .
58
 *                 'collapse plugin adds the appropriate classes that we use to style each element. These ' .
59
 *                 'classes control the overall appearance, as well as the showing and hiding via CSS ' .
60
 *                 'transitions. You can modify any of this with custom CSS or overriding our default ' .
61
 *                 'variables. Its also worth noting that just about any HTML can go within the ' .
62
 *                 '<code>.accordion-body</code>, though the transition does limit overflow.',
63
 *             ],
64
 *             'contentOptions' => [
65
 *                 'class' => 'testContentOptions2',
66
 *             ],
67
 *             'options' => [
68
 *                 'class' => 'testClass2',
69
 *                 'id' => 'testId2',
70
 *             ],
71
 *             'encode' => false,
72
 *         ],
73
 *     ]);
74
 * ```
75
 *
76
 * @link https://getbootstrap.com/docs/5.0/components/accordion/
77
 */
78
final class Accordion extends Widget
79
{
80
    private array $items = [];
81
    private array $expands = [];
82
    private ?bool $defaultExpand = null;
83
    private bool $encodeLabels = true;
84
    private bool $encodeTags = false;
85
    private bool $autoCloseItems = true;
86
    private array $headerOptions = [];
87
    private array $toggleOptions = [];
88
    private array $contentOptions = [];
89
    private array $bodyOptions = [];
90
    private array $options = [];
91
    private bool $flush = false;
92
93 13
    public function getId(?string $suffix = '-accordion'): ?string
94
    {
95 13
        return $this->options['id'] ?? parent::getId($suffix);
96
    }
97
98 9
    /**
99
     * @return string
100 9
     * @throws JsonException
101
     */
102
    public function render(): string
103 9
    {
104
        $options = $this->options;
105 9
        $options['id'] = $this->getId();
106
        Html::addCssClass($options, ['widget' => 'accordion']);
107
108 13
        if ($this->flush) {
109
            Html::addCssClass($options, ['flush' => 'accordion-flush']);
110 13
        }
111
112 13
        if ($this->theme) {
113 1
            $options['data-bs-theme'] = $this->theme;
114
        }
115
116 13
        return Html::div($this->renderItems(), $options)
117 13
            ->encode($this->encodeTags)
118
            ->render();
119
    }
120 13
121 13
    /**
122 13
     * Whether to close other items if an item is opened. Defaults to `true` which causes an accordion effect.
123
     *
124
     * Set this to `false` to allow keeping multiple items open at once.
125
     */
126
    public function allowMultipleOpenedItems(): self
127
    {
128
        $new = clone $this;
129
        $new->autoCloseItems = false;
130 1
131
        return $new;
132 1
    }
133 1
134
    /**
135 1
     * When tags Labels HTML should not be encoded.
136
     */
137
    public function withoutEncodeLabels(): self
138
    {
139
        $new = clone $this;
140
        $new->encodeLabels = false;
141 1
142
        return $new;
143 1
    }
144 1
145
    /**
146 1
     * List of groups in the collapse widget. Each array element represents a single group with the following structure:
147
     *
148
     * - label: string, required, the group header label.
149
     * - encode: bool, optional, whether this label should be HTML-encoded. This param will override global
150
     *   `$this->encodeLabels` param.
151
     * - content: array|string|object, required, the content (HTML) of the group
152
     * - options: array, optional, the HTML attributes of the group
153
     * - contentOptions: optional, the HTML attributes of the group's content
154
     *
155
     * You may also specify this property as key-value pairs, where the key refers to the `label` and the value refers
156
     * to `content`. If value is a string it is interpreted as label. If it is an array, it is interpreted as explained
157
     * above.
158
     *
159
     * For example:
160
     *
161
     * ```php
162
     * echo Accordion::widget()
163
     *     ->items(
164
     *         [
165
     *             [
166
     *                 'Introduction' => 'This is the first collapsible menu',
167
     *                 'Second panel' => [
168
     *                     'content' => 'This is the second collapsible menu',
169
     *                 ],
170
     *             ],
171
     *             [
172
     *                 'label' => 'Third panel',
173
     *                 'content' => 'This is the third collapsible menu',
174
     *             ],
175
     *         ],
176
     *     );
177
     * ```
178
     */
179
    public function items(array $value): self
180
    {
181
        $new = clone $this;
182
        $new->items = $value;
183 13
        $new->expands = array_map(fn ($item) => isset($item['expand']) ? (bool) $item['expand'] : $this->defaultExpand, $new->items);
184
185 13
        return $new;
186 13
    }
187 13
188
    /**
189 13
     * Set expand property for items without it
190
     */
191
    public function defaultExpand(?bool $default): self
192
    {
193
        if ($default === $this->defaultExpand) {
194
            return $this;
195 1
        }
196
197 1
        $new = clone $this;
198
        $new->defaultExpand = $default;
199
        $new->expands = array_map(fn ($item) => isset($item['expand']) ? (bool) $item['expand'] : $new->defaultExpand, $new->items);
200
201 1
        return $new;
202 1
    }
203 1
204
    /**
205 1
     * Options for each header if not present in item
206
     */
207
    public function headerOptions(array $options): self
208
    {
209
        $new = clone $this;
210
        $new->headerOptions = $options;
211
212
        return $new;
213
    }
214
215
    /**
216
     * The HTML options for the item toggle tag. Key 'tag' might be used here for the tag name specification.
217
     *
218
     * For example:
219
     *
220
     * ```php
221
     * [
222
     *     'tag' => 'div',
223
     *     'class' => 'custom-toggle',
224
     * ]
225
     * ```
226
     */
227
    public function toggleOptions(array $options): self
228
    {
229
        $new = clone $this;
230
        $new->toggleOptions = $options;
231 1
232
        return $new;
233 1
    }
234 1
235
    /**
236 1
     * Content options for items if not present in current
237
     */
238
    public function contentOptions(array $options): self
239
    {
240
        $new = clone $this;
241
        $new->contentOptions = $options;
242
243
        return $new;
244
    }
245
246
    /**
247
     * The HTML attributes for the widget container tag. The following special options are recognized.
248
     *
249
     * {@see Html::renderTagAttributes()} for details on how attributes are being rendered.
250
     */
251
    public function options(array $value): self
252
    {
253
        $new = clone $this;
254
        $new->options = $value;
255 1
256
        return $new;
257 1
    }
258 1
259
    public function bodyOptions(array $options): self
260 1
    {
261
        $new = clone $this;
262
        $new->bodyOptions = $options;
263
264
        return $new;
265
    }
266
267
    /**
268
     * Remove the default background-color, some borders, and some rounded corners to render accordions
269 1
     * edge-to-edge with their parent container.
270
     *
271 1
     * @link https://getbootstrap.com/docs/5.0/components/accordion/#flush
272 1
     */
273
    public function flush(): self
274 1
    {
275
        $new = clone $this;
276
        $new->flush = true;
277
278
        return $new;
279
    }
280
281
    /**
282
     * Renders collapsible items as specified on {@see items}.
283
     *
284 13
     * @throws JsonException|RuntimeException
285
     *
286 13
     * @return string the rendering result
287 13
     */
288 13
    private function renderItems(): string
289 13
    {
290
        $items = [];
291 13
        $index = 0;
292 13
        $expanded = in_array(true, $this->expands, true);
293 1
        $allClose = !$expanded && count($this->items) === count(array_filter($this->expands, static fn ($expand) => $expand === false));
294
295
        foreach ($this->items as $item) {
296 13
            if (!is_array($item)) {
297 11
                $item = ['content' => $item];
298
            }
299
300 13
            if ($allClose === false && $expanded === false && $index === 0) {
301 3
                $item['expand'] = true;
302
            }
303
304 10
            if (!array_key_exists('label', $item)) {
305 10
                throw new RuntimeException('The "label" option is required.');
306
            }
307 8
308
            $options = ArrayHelper::getValue($item, 'options', []);
309 8
            $item = $this->renderItem($item);
310 8
311 8
            Html::addCssClass($options, ['panel' => 'accordion-item']);
312
313
            $items[] = Html::div($item, $options)
314 8
                ->encode(false)
315
                ->render();
316
317
            $index++;
318
        }
319
320
        return implode('', $items);
321
    }
322
323
    /**
324
     * Renders a single collapsible item group.
325
     *
326
     * @param array $item a single item from {@see items}
327 10
     * @param int $index the item index as each item group content must have an id
328
     *
329 10
     * @throws JsonException|RuntimeException
330 1
     *
331
     * @return string the rendering result
332
     */
333 9
    private function renderItem(array $item): string
334 9
    {
335
        if (!array_key_exists('content', $item)) {
336 8
            throw new RuntimeException('The "content" option is required.');
337
        }
338
339
        $collapse = $this->renderCollapse($item);
340
        $header = $this->renderHeader($collapse, ArrayHelper::getValue($item, 'headerOptions'));
341
342 9
        return $header . $collapse->render();
343
    }
344 9
345 9
    /**
346 9
     * Render collapse header
347 9
     */
348
    private function renderHeader(Collapse $collapse, ?array $headerOptions): string
349 9
    {
350
        $options = $headerOptions ?? $this->headerOptions;
351 9
        $tag = ArrayHelper::remove($options, 'tag', 'h2');
352 9
353 9
        Html::addCssClass($options, ['widget' => 'accordion-header']);
354
355
        return Html::tag($tag, $collapse->renderToggle(), $options)
356
            ->encode(false)
357
            ->render();
358
    }
359 9
360
    /**
361 9
     * Render collapse item
362 9
     */
363 9
    private function renderCollapse(array $item): Collapse
364
    {
365 9
        $expand = $item['expand'] ?? false;
366 9
        $options = $item['contentOptions'] ?? $this->contentOptions;
367 9
        $toggleOptions = $item['toggleOptions'] ?? $this->toggleOptions;
368 9
        $bodyOptions = $item['bodyOptions'] ?? $this->bodyOptions;
369 9
370 9
        $toggleOptions['encode'] = $toggleOptions['encode'] ?? $this->encodeLabels;
371 9
        $bodyOptions['encode'] = $bodyOptions['encode'] ?? $this->encodeTags;
372 9
373 9
        Html::addCssClass($options, ['accordion-collapse']);
374 9
        Html::addCssClass($toggleOptions, ['accordion-button']);
375
        Html::addCssClass($bodyOptions, ['widget' => 'accordion-body']);
376 9
377
        if (!$expand) {
378 9
            Html::addCssClass($toggleOptions, ['collapsed']);
379 8
        }
380
381
        if ($this->autoCloseItems) {
382 9
            $options['data-bs-parent'] = '#' . $this->getId();
383 1
        }
384
385 8
        return Collapse::widget()
386
            ->withToggleLabel($item['label'])
0 ignored issues
show
Bug introduced by
The method withToggleLabel() does not exist on Yiisoft\Widget\Widget. It seems like you code against a sub-type of Yiisoft\Widget\Widget such as Yiisoft\Yii\Bootstrap5\AbstractToggleWidget. ( Ignorable by Annotation )

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

386
            ->/** @scrutinizer ignore-call */ withToggleLabel($item['label'])
Loading history...
387 8
            ->withToggleOptions($toggleOptions)
388 8
            ->withOptions($options)
389
            ->withContent($this->renderBody($item))
390
            ->withBodyOptions($bodyOptions)
391
            ->withCollapsed($expand)
392 9
            ->withToggle(false);
393 9
    }
394 9
395
    /**
396
     * Render collapse body
397
     */
398
    private function renderBody(array $item): string
399
    {
400 9
        $items = '';
401
402 9
        if ($this->isStringableObject($item['content'])) {
403 9
            $content = [$item['content']];
404 9
        } else {
405 9
            $content = (array) $item['content'];
406 8
        }
407
408 8
        foreach ($content as $value) {
409
            if (!is_string($value) && !is_numeric($value) && !$this->isStringableObject($value)) {
410 8
                throw new RuntimeException('The "content" option should be a string, array or object.');
411 7
            }
412
413
            $items .= $value;
414 8
        }
415 8
416
        return $items;
417
    }
418 8
419 8
    private function isStringableObject(mixed $value): bool
420
    {
421
        return $value instanceof Stringable;
422 8
    }
423
}
424