Passed
Push — master ( 2301b1...386ec7 )
by Alexander
14:22 queued 11:36
created

Carousel::render()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 19
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 3

Importance

Changes 0
Metric Value
cc 3
eloc 10
nc 4
nop 0
dl 0
loc 19
ccs 12
cts 12
cp 1
crap 3
rs 9.9332
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 count;
13
use function implode;
14
use function is_string;
15
16
/**
17
 * Carousel renders a carousel bootstrap javascript component.
18
 *
19
 * For example:
20
 *
21
 * ```php
22
 * echo Carousel::widget()
23
 *     ->items([
24
 *         // the item contains only the image
25
 *         '<img src="http://twitter.github.io/bootstrap/assets/img/bootstrap-mdo-sfmoma-01.jpg"/>',
26
 *         // equivalent to the above
27
 *         ['content' => '<img src="http://twitter.github.io/bootstrap/assets/img/bootstrap-mdo-sfmoma-02.jpg"/>'],
28
 *         // the item contains both the image and the caption
29
 *         [
30
 *             'content' => '<img src="http://twitter.github.io/bootstrap/assets/img/bootstrap-mdo-sfmoma-03.jpg"/>',
31
 *             'caption' => '<h4>This is title</h4><p>This is the caption text</p>',
32
 *             'captionOptions' => ['class' => ['d-none', 'd-md-block']],
33
 *             'options' => [...],
34
 *         ],
35
 *     ]);
36
 * ```
37
 */
38
final class Carousel extends Widget
39
{
40
    private array $controls = [
41
        '<span class="carousel-control-prev-icon" aria-hidden="true"></span><span class="visually-hidden">Previous</span>',
42
        '<span class="carousel-control-next-icon" aria-hidden="true"></span><span class="visually-hidden">Next</span>',
43
    ];
44
    private bool $encodeTags = false;
45
    private bool $showIndicators = true;
46
    private array $items = [];
47
    private bool $crossfade = false;
48
    private array $options = ['data-bs-ride' => 'carousel'];
49
50 8
    public function render(): string
51
    {
52 8
        if (!isset($this->options['id'])) {
53 8
            $this->options['id'] = "{$this->getId()}-carousel";
54
        }
55
56
        /** @psalm-suppress InvalidArgument */
57 8
        Html::addCssClass($this->options, ['widget' => 'carousel', 'slide']);
58
59 8
        if ($this->crossfade) {
60 1
            Html::addCssClass($this->options, ['crossfade' => 'carousel-fade']);
61
        }
62
63 8
        return Html::div(
64 8
            $this->renderIndicators() . $this->renderItems() . $this->renderControls(),
65 8
            $this->options
66 8
        )
67 8
            ->encode($this->encodeTags)
68 8
            ->render();
69
    }
70
71
    /**
72
     * The labels for the previous and the next control buttons.
73
     *
74
     * If null, it means the previous and the next control buttons should not be displayed.
75
     *
76
     * @param array $value
77
     */
78 2
    public function controls(array $value): self
79
    {
80 2
        $new = clone $this;
81 2
        $new->controls = $value;
82
83 2
        return $new;
84
    }
85
86
    /**
87
     * Animate slides with a fade transition instead of a slide. Defaults to `false`.
88
     */
89 1
    public function withCrossfade(): self
90
    {
91 1
        $new = clone $this;
92 1
        $new->crossfade = true;
93
94 1
        return $new;
95
    }
96
97
    /**
98
     * List of slides in the carousel. Each array element represents a single slide with the following structure:
99
     *
100
     * ```php
101
     * [
102
     *     // required, slide content (HTML), such as an image tag
103
     *     'content' => '<img src="http://twitter.github.io/bootstrap/assets/img/bootstrap-mdo-sfmoma-01.jpg"/>',
104
     *     // optional, the caption (HTML) of the slide
105
     *     'caption' => '<h4>This is title</h4><p>This is the caption text</p>',
106
     *     // optional the HTML attributes of the slide container
107
     *     'options' => [],
108
     * ]
109
     * ```
110
     *
111
     * @param array $value
112
     */
113 8
    public function items(array $value): self
114
    {
115 8
        $new = clone $this;
116 8
        $new->items = $value;
117
118 8
        return $new;
119
    }
120
121
    /**
122
     * The HTML attributes for the container tag. The following special options are recognized.
123
     *
124
     * {@see Html::renderTagAttributes()} for details on how attributes are being rendered.
125
     *
126
     * @param array $value
127
     */
128 1
    public function options(array $value): self
129
    {
130 1
        $new = clone $this;
131 1
        $new->options = $value;
132
133 1
        return $new;
134
    }
135
136
    /**
137
     * Whether carousel indicators (<ol> tag with anchors to items) should be displayed or not.
138
     */
139 1
    public function withoutShowIndicators(): self
140
    {
141 1
        $new = clone $this;
142 1
        $new->showIndicators = false;
143
144 1
        return $new;
145
    }
146
147
    /**
148
     * Renders carousel indicators.
149
     */
150 8
    private function renderIndicators(): string
151
    {
152 8
        if ($this->showIndicators === false) {
153 1
            return '';
154
        }
155
156 7
        $indicators = [];
157
158 7
        for ($i = 0, $count = count($this->items); $i < $count; $i++) {
159 7
            $options = ['data-bs-target' => '#' . $this->options['id'], 'data-bs-slide-to' => $i];
160 7
            if ($i === 0) {
161
                /** @psalm-suppress InvalidArgument */
162 7
                Html::addCssClass($options, ['active' => 'active']);
163
            }
164 7
            $indicators[] = Html::tag('li', '', $options);
165
        }
166
167 7
        $indicatorOptions = ['class' => ['carousel-indicators']];
168
169 7
        return Html::tag('ol', implode("\n", $indicators), $indicatorOptions)
170 7
            ->encode($this->encodeTags)
171 7
            ->render();
172
    }
173
174
    /**
175
     * Renders carousel items as specified on {@see items}.
176
     */
177 8
    private function renderItems(): string
178
    {
179 8
        $items = [];
180
181 8
        foreach ($this->items as $i => $iValue) {
182 8
            $items[] = $this->renderItem($iValue, $i);
183
        }
184
185 7
        $itemOptions = ['class' => 'carousel-inner'];
186
187 7
        return Html::div(implode("\n", $items), $itemOptions)
188 7
            ->encode($this->encodeTags)
189 7
            ->render();
190
    }
191
192
    /**
193
     * Renders a single carousel item
194
     *
195
     * @param array|string $item a single item from {@see items}
196
     * @param int $index the item index as the first item should be set to `active`
197
     *
198
     * @throws JsonException|RuntimeException if the item is invalid.
199
     *
200
     * @return string the rendering result.
201
     */
202 8
    private function renderItem(array|string $item, int $index): string
203
    {
204 8
        if (is_string($item)) {
0 ignored issues
show
introduced by
The condition is_string($item) is always false.
Loading history...
205 1
            $content = $item;
206 1
            $caption = null;
207 1
            $options = [];
208 7
        } elseif (isset($item['content'])) {
209 6
            $content = $item['content'];
210 6
            $caption = ArrayHelper::getValue($item, 'caption');
211
212 6
            if ($caption !== null) {
213 6
                $captionOptions = ArrayHelper::remove($item, 'captionOptions', []);
214 6
                Html::addCssClass($captionOptions, ['captionOptions' => 'carousel-caption']);
215
216 6
                $caption = Html::div($caption, $captionOptions)
217 6
                    ->encode($this->encodeTags)
218 6
                    ->render();
219
            }
220
221 6
            $options = ArrayHelper::getValue($item, 'options', []);
222
        } else {
223 1
            throw new RuntimeException('The "content" option is required.');
224
        }
225
226 7
        Html::addCssClass($options, ['widget' => 'carousel-item']);
227
228 7
        if ($index === 0) {
229 7
            Html::addCssClass($options, ['active' => 'active']);
230
        }
231
232 7
        return Html::div($content . "\n" . $caption, $options)
233 7
            ->encode($this->encodeTags)
234 7
            ->render();
235
    }
236
237
    /**
238
     * Renders previous and next control buttons.
239
     *
240
     * @throws JsonException|RuntimeException if {@see controls} is invalid.
241
     */
242 7
    private function renderControls(): string
243
    {
244 7
        $controlsOptions0 = [
245 7
            'class' => 'carousel-control-prev',
246 7
            'data-bs-slide' => 'prev',
247 7
            'role' => 'button',
248 7
        ];
249
250 7
        $controlsOptions1 = [
251 7
            'class' => 'carousel-control-next',
252 7
            'data-bs-slide' => 'next',
253 7
            'role' => 'button',
254 7
        ];
255
256 7
        if (isset($this->controls[0], $this->controls[1])) {
257 5
            return Html::a($this->controls[0], '#' . $this->options['id'], $controlsOptions0)->encode($this->encodeTags) . "\n" .
258 5
                Html::a($this->controls[1], '#' . $this->options['id'], $controlsOptions1)->encode($this->encodeTags);
259
        }
260
261 2
        if ($this->controls === []) {
262 1
            return '';
263
        }
264
265 1
        throw new RuntimeException(
266 1
            'The "controls" property must be either null or an array of two elements.'
267 1
        );
268
    }
269
}
270