Passed
Push — master ( 39eeb7...47c735 )
by Alexander
04:24 queued 02:01
created

Carousel::options()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

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