Completed
Pull Request — master (#203)
by
unknown
01:54
created

SplitItem::setGutter()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 1
eloc 2
c 1
b 0
f 1
nc 1
nop 1
dl 0
loc 4
rs 10
1
<?php
2
3
namespace PhpSchool\CliMenu\MenuItem;
4
5
use Assert\Assertion;
6
use PhpSchool\CliMenu\MenuStyle;
7
use PhpSchool\CliMenu\Util\StringUtil;
8
9
/**
10
 * @author Michael Woodward <[email protected]>
11
 */
12
class SplitItem implements MenuItemInterface
13
{
14
    /**
15
     * @var array
16
     */
17
    private $items = [];
18
19
    /**
20
     * @var int|null
21
     */
22
    private $selectedItemIndex;
23
24
    /**
25
     * @var bool
26
     */
27
    private $canBeSelected = true;
28
29
    /**
30
     * @var int
31
     */
32
    private $gutter = 2;
33
34
    /**
35
     * @var array
36
     */
37
    private static $blacklistedItems = [
38
        \PhpSchool\CliMenu\MenuItem\AsciiArtItem::class,
39
        \PhpSchool\CliMenu\MenuItem\LineBreakItem::class,
40
        \PhpSchool\CliMenu\MenuItem\SplitItem::class,
41
    ];
42
43
    public function __construct(array $items = [])
44
    {
45
        $this->addItems($items);
46
        $this->setDefaultSelectedItem();
47
    }
48
49
    public function setGutter(int $gutter) : void
50
    {
51
        Assertion::greaterOrEqualThan($gutter, 0);
52
        $this->gutter = $gutter;
53
    }
54
55
    public function getGutter() : int
56
    {
57
        return $this->gutter;
58
    }
59
60
    public function addItem(MenuItemInterface $item) : self
61
    {
62
        foreach (self::$blacklistedItems as $bl) {
63
            if ($item instanceof $bl) {
64
                throw new \InvalidArgumentException("Cannot add a $bl to a SplitItem");
65
            }
66
        }
67
        $this->items[] = $item;
68
        $this->setDefaultSelectedItem();
69
        return $this;
70
    }
71
72
    public function addItems(array $items) : self
73
    {
74
        foreach ($items as $item) {
75
            $this->addItem($item);
76
        }
77
            
78
        return $this;
79
    }
80
81
    public function setItems(array $items) : self
82
    {
83
        $this->items = [];
84
        $this->addItems($items);
85
        return $this;
86
    }
87
88
    /**
89
     * Select default item
90
     */
91
    private function setDefaultSelectedItem() : void
92
    {
93
        foreach ($this->items as $index => $item) {
94
            if ($item->canSelect()) {
95
                $this->canBeSelected = true;
96
                $this->selectedItemIndex = $index;
97
                return;
98
            }
99
        }
100
101
        $this->canBeSelected = false;
102
        $this->selectedItemIndex = null;
103
    }
104
105
    /**
106
     * The output text for the item
107
     */
108
    public function getRows(MenuStyle $style, bool $selected = false) : array
109
    {
110
        $numberOfItems = count($this->items);
111
112
        if ($numberOfItems === 0) {
113
            throw new \RuntimeException(sprintf('There should be at least one item added to: %s', __CLASS__));
114
        }
115
        
116
        if (!$selected) {
117
            $this->setDefaultSelectedItem();
118
        }
119
120
        $length = $style->getDisplaysExtra()
121
            ? floor($style->getContentWidth() / $numberOfItems) - (mb_strlen($style->getItemExtra()) + 2)
122
            : floor($style->getContentWidth() / $numberOfItems);
123
        
124
        $length -= $this->gutter;
125
        $length = (int) $length;
126
        
127
        $missingLength = $style->getContentWidth() % $numberOfItems;
128
        
129
        return $this->buildRows(
130
            array_map(function ($index, $item) use ($selected, $length, $style) {
131
                $isSelected = $selected && $index === $this->selectedItemIndex;
132
133
                if ($item instanceof ItemStyleInterface) {
134
                    $itemStyle = $item->getStyle();
135
136
                    $getMarkerType = $item instanceof ToggableItemInterface
137
                        ? $item->getChecked()
138
                        : $isSelected;
139
140
                    $markerType        = $itemStyle->getMarker($getMarkerType);
141
                    $displaysExtraType = $itemStyle->getDisplaysExtra();
142
                    $itemExtraType     = $itemStyle->getItemExtra();
143
                } else {
144
                    $markerType        = $style->getMarker($isSelected);
145
                    $displaysExtraType = $style->getDisplaysExtra();
146
                    $itemExtraType     = $style->getItemExtra();
147
                }
148
149
                $marker = $item->canSelect()
150
                    ? sprintf('%s', $markerType)
151
                    : '';
152
153
                $itemExtra = '';
154
                if ($displaysExtraType) {
155
                    $itemExtra = $item->showsItemExtra()
156
                        ? sprintf('  %s', $itemExtraType)
157
                        : sprintf('  %s', str_repeat(' ', mb_strlen($itemExtraType)));
158
                }
159
160
                return $this->buildCell(
161
                    explode(
162
                        "\n",
163
                        StringUtil::wordwrap(
164
                            sprintf('%s%s', $marker, $item->getText()),
165
                            $length,
166
                            sprintf("\n%s", str_repeat(' ', mb_strlen($marker)))
167
                        )
168
                    ),
169
                    $length,
170
                    $style,
171
                    $isSelected,
172
                    $itemExtra
173
                );
174
            }, array_keys($this->items), $this->items),
175
            $style,
176
            $missingLength,
177
            $length
178
        );
179
    }
180
181
    private function buildRows(array $cells, MenuStyle $style, int $missingLength, int $length) : array
182
    {
183
        $extraPadLength = $style->getDisplaysExtra() ? 2 + mb_strlen($style->getItemExtra()) : 0;
184
        
185
        return array_map(
186
            function ($i) use ($cells, $length, $missingLength, $extraPadLength) {
187
                return $this->buildRow($cells, $i, $length, $missingLength, $extraPadLength);
188
            },
189
            range(0, max(array_map('count', $cells)) - 1)
190
        );
191
    }
192
193
    private function buildRow(array $cells, int $index, int $length, int $missingLength, int $extraPadLength) : string
194
    {
195
        return sprintf(
196
            '%s%s',
197
            implode(
198
                '',
199
                array_map(
200
                    function ($cell) use ($index, $length, $extraPadLength) {
201
                        return $cell[$index] ?? str_repeat(' ', $length + $this->gutter + $extraPadLength);
202
                    },
203
                    $cells
204
                )
205
            ),
206
            str_repeat(' ', $missingLength)
207
        );
208
    }
209
210
    private function buildCell(
211
        array $content,
212
        int $length,
213
        MenuStyle $style,
214
        bool $isSelected,
215
        string $itemExtra
216
    ) : array {
217
        return array_map(function ($row, $index) use ($length, $style, $isSelected, $itemExtra) {
218
            $invertedColoursSetCode = $isSelected
219
                ? $style->getInvertedColoursSetCode()
220
                : '';
221
            $invertedColoursUnsetCode = $isSelected
222
                ? $style->getInvertedColoursUnsetCode()
223
                : '';
224
225
            return sprintf(
226
                '%s%s%s%s%s%s',
227
                $invertedColoursSetCode,
228
                $row,
229
                str_repeat(' ', $length - mb_strlen($row)),
230
                $index === 0 ? $itemExtra : str_repeat(' ', mb_strlen($itemExtra)),
231
                $invertedColoursUnsetCode,
232
                str_repeat(' ', $this->gutter)
233
            );
234
        }, $content, array_keys($content));
235
    }
236
237
    /**
238
     * Is there an item with this index and can it be
239
     * selected?
240
     */
241
    public function canSelectIndex(int $index) : bool
242
    {
243
        return isset($this->items[$index]) && $this->items[$index]->canSelect();
244
    }
245
246
    /**
247
     * Set the item index which should be selected. If the item does
248
     * not exist then throw an exception.
249
     */
250
    public function setSelectedItemIndex(int $index) : void
251
    {
252
        if (!isset($this->items[$index])) {
253
            throw new \InvalidArgumentException(sprintf('Index: "%s" does not exist', $index));
254
        }
255
        
256
        $this->selectedItemIndex = $index;
257
    }
258
259
    /**
260
     * Get the currently select item index.
261
     * May be null in case of no selectable item.
262
     */
263
    public function getSelectedItemIndex() : ?int
264
    {
265
        return $this->selectedItemIndex;
266
    }
267
268
    /**
269
     * Get the currently selected item - if no items are selectable
270
     * then throw an exception.
271
     */
272
    public function getSelectedItem() : MenuItemInterface
273
    {
274
        if (null === $this->selectedItemIndex) {
275
            throw new \RuntimeException('No item is selected');
276
        }
277
        
278
        return $this->items[$this->selectedItemIndex];
279
    }
280
281
    public function getItems() : array
282
    {
283
        return $this->items;
284
    }
285
286
    /**
287
     * Can the item be selected
288
     * In this case, it indicates if at least 1 item inside the SplitItem can be selected
289
     */
290
    public function canSelect() : bool
291
    {
292
        return $this->canBeSelected;
293
    }
294
295
    /**
296
     * Execute the items callable if required
297
     */
298
    public function getSelectAction() : ?callable
299
    {
300
        return null;
301
    }
302
303
    /**
304
     * Whether or not the menu item is showing the menustyle extra value
305
     */
306
    public function showsItemExtra() : bool
307
    {
308
        return false;
309
    }
310
311
    /**
312
     * Enable showing item extra
313
     */
314
    public function showItemExtra() : void
315
    {
316
        //noop
317
    }
318
319
    /**
320
     * Disable showing item extra
321
     */
322
    public function hideItemExtra() : void
323
    {
324
        //noop
325
    }
326
327
    /**
328
     * Nothing to return with SplitItem
329
     */
330
    public function getText() : string
331
    {
332
        throw new \BadMethodCallException(sprintf('Not supported on: %s', __CLASS__));
333
    }
334
}
335