Passed
Pull Request — master (#189)
by
unknown
01:54
created

SplitItem::getSelectAction()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
c 1
b 0
f 0
nc 1
nop 0
dl 0
loc 3
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 (is_a($item, CheckableItem::class)) {
134
                    /** @var CheckableItem $item */
135
                    $markerType = $item->getChecked()
136
                        ? $style->getCheckedMarker()
137
                        : $style->getUncheckedMarker();
138
                } else {
139
                    $markerType = $style->getMarker($isSelected);
140
                }
141
142
                $marker = $item->canSelect()
143
                    ? sprintf('%s', $markerType)
144
                    : '';
145
146
                $itemExtra = '';
147
                if ($style->getDisplaysExtra()) {
148
                    $itemExtra = $item->showsItemExtra()
149
                        ? sprintf('  %s', $style->getItemExtra())
150
                        : sprintf('  %s', str_repeat(' ', mb_strlen($style->getItemExtra())));
151
                }
152
153
                return $this->buildCell(
154
                    explode(
155
                        "\n",
156
                        StringUtil::wordwrap(
157
                            sprintf('%s%s', $marker, $item->getText()),
158
                            $length,
159
                            sprintf("\n%s", str_repeat(' ', mb_strlen($marker)))
160
                        )
161
                    ),
162
                    $length,
163
                    $style,
164
                    $isSelected,
165
                    $itemExtra
166
                );
167
            }, array_keys($this->items), $this->items),
168
            $style,
169
            $missingLength,
170
            $length
171
        );
172
    }
173
174
    private function buildRows(array $cells, MenuStyle $style, int $missingLength, int $length) : array
175
    {
176
        $extraPadLength = $style->getDisplaysExtra() ? 2 + mb_strlen($style->getItemExtra()) : 0;
177
        
178
        return array_map(
179
            function ($i) use ($cells, $length, $missingLength, $extraPadLength) {
180
                return $this->buildRow($cells, $i, $length, $missingLength, $extraPadLength);
181
            },
182
            range(0, max(array_map('count', $cells)) - 1)
183
        );
184
    }
185
186
    private function buildRow(array $cells, int $index, int $length, int $missingLength, int $extraPadLength) : string
187
    {
188
        return sprintf(
189
            '%s%s',
190
            implode(
191
                '',
192
                array_map(
193
                    function ($cell) use ($index, $length, $extraPadLength) {
194
                        return $cell[$index] ?? str_repeat(' ', $length + $this->gutter + $extraPadLength);
195
                    },
196
                    $cells
197
                )
198
            ),
199
            str_repeat(' ', $missingLength)
200
        );
201
    }
202
203
    private function buildCell(
204
        array $content,
205
        int $length,
206
        MenuStyle $style,
207
        bool $isSelected,
208
        string $itemExtra
209
    ) : array {
210
        return array_map(function ($row, $index) use ($length, $style, $isSelected, $itemExtra) {
211
            $invertedColoursSetCode = $isSelected
212
                ? $style->getInvertedColoursSetCode()
213
                : '';
214
            $invertedColoursUnsetCode = $isSelected
215
                ? $style->getInvertedColoursUnsetCode()
216
                : '';
217
218
            return sprintf(
219
                '%s%s%s%s%s%s',
220
                $invertedColoursSetCode,
221
                $row,
222
                str_repeat(' ', $length - mb_strlen($row)),
223
                $index === 0 ? $itemExtra : str_repeat(' ', mb_strlen($itemExtra)),
224
                $invertedColoursUnsetCode,
225
                str_repeat(' ', $this->gutter)
226
            );
227
        }, $content, array_keys($content));
228
    }
229
230
    /**
231
     * Is there an item with this index and can it be
232
     * selected?
233
     */
234
    public function canSelectIndex(int $index) : bool
235
    {
236
        return isset($this->items[$index]) && $this->items[$index]->canSelect();
237
    }
238
239
    /**
240
     * Set the item index which should be selected. If the item does
241
     * not exist then throw an exception.
242
     */
243
    public function setSelectedItemIndex(int $index) : void
244
    {
245
        if (!isset($this->items[$index])) {
246
            throw new \InvalidArgumentException(sprintf('Index: "%s" does not exist', $index));
247
        }
248
        
249
        $this->selectedItemIndex = $index;
250
    }
251
252
    /**
253
     * Get the currently select item index.
254
     * May be null in case of no selectable item.
255
     */
256
    public function getSelectedItemIndex() : ?int
257
    {
258
        return $this->selectedItemIndex;
259
    }
260
261
    /**
262
     * Get the currently selected item - if no items are selectable
263
     * then throw an exception.
264
     */
265
    public function getSelectedItem() : MenuItemInterface
266
    {
267
        if (null === $this->selectedItemIndex) {
268
            throw new \RuntimeException('No item is selected');
269
        }
270
        
271
        return $this->items[$this->selectedItemIndex];
272
    }
273
274
    public function getItems() : array
275
    {
276
        return $this->items;
277
    }
278
279
    /**
280
     * Can the item be selected
281
     * In this case, it indicates if at least 1 item inside the SplitItem can be selected
282
     */
283
    public function canSelect() : bool
284
    {
285
        return $this->canBeSelected;
286
    }
287
288
    /**
289
     * Execute the items callable if required
290
     */
291
    public function getSelectAction() : ?callable
292
    {
293
        return null;
294
    }
295
296
    /**
297
     * Whether or not the menu item is showing the menustyle extra value
298
     */
299
    public function showsItemExtra() : bool
300
    {
301
        return false;
302
    }
303
304
    /**
305
     * Enable showing item extra
306
     */
307
    public function showItemExtra() : void
308
    {
309
        //noop
310
    }
311
312
    /**
313
     * Disable showing item extra
314
     */
315
    public function hideItemExtra() : void
316
    {
317
        //noop
318
    }
319
320
    /**
321
     * Nothing to return with SplitItem
322
     */
323
    public function getText() : string
324
    {
325
        throw new \BadMethodCallException(sprintf('Not supported on: %s', __CLASS__));
326
    }
327
}
328