Passed
Pull Request — master (#230)
by Aydin
01:56
created

SplitItem::calculateItemExtra()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 5
nc 1
nop 0
dl 0
loc 8
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace PhpSchool\CliMenu\MenuItem;
4
5
use Assert\Assertion;
6
use PhpSchool\CliMenu\MenuStyle;
7
use PhpSchool\CliMenu\Style\DefaultStyle;
8
use PhpSchool\CliMenu\Style\ItemStyle;
9
use PhpSchool\CliMenu\Style\Selectable;
10
use PhpSchool\CliMenu\Util\StringUtil;
11
use function PhpSchool\CliMenu\Util\mapWithKeys;
12
use function PhpSchool\CliMenu\Util\max;
13
14
/**
15
 * @author Michael Woodward <[email protected]>
16
 */
17
class SplitItem implements MenuItemInterface
18
{
19
    /**
20
     * @var array
21
     */
22
    private $items = [];
23
24
    /**
25
     * @var int|null
26
     */
27
    private $selectedItemIndex;
28
29
    /**
30
     * @var bool
31
     */
32
    private $canBeSelected = true;
33
34
    /**
35
     * @var int
36
     */
37
    private $gutter = 2;
38
39
    /**
40
     * @var DefaultStyle
41
     */
42
    private $style;
43
44
    /**
45
     * @var array
46
     */
47
    private static $blacklistedItems = [
48
        \PhpSchool\CliMenu\MenuItem\AsciiArtItem::class,
49
        \PhpSchool\CliMenu\MenuItem\LineBreakItem::class,
50
        \PhpSchool\CliMenu\MenuItem\SplitItem::class,
51
    ];
52
53
    public function __construct(array $items = [])
54
    {
55
        $this->addItems($items);
56
        $this->setDefaultSelectedItem();
57
58
        $this->style = new DefaultStyle();
59
    }
60
61
    public function getGutter() : int
62
    {
63
        return $this->gutter;
64
    }
65
66
    public function setGutter(int $gutter) : void
67
    {
68
        Assertion::greaterOrEqualThan($gutter, 0);
69
        $this->gutter = $gutter;
70
    }
71
72
    public function addItem(MenuItemInterface $item) : self
73
    {
74
        foreach (self::$blacklistedItems as $bl) {
75
            if ($item instanceof $bl) {
76
                throw new \InvalidArgumentException("Cannot add a $bl to a SplitItem");
77
            }
78
        }
79
        $this->items[] = $item;
80
        $this->setDefaultSelectedItem();
81
        return $this;
82
    }
83
84
    public function addItems(array $items) : self
85
    {
86
        foreach ($items as $item) {
87
            $this->addItem($item);
88
        }
89
            
90
        return $this;
91
    }
92
93
    public function setItems(array $items) : self
94
    {
95
        $this->items = [];
96
        $this->addItems($items);
97
        return $this;
98
    }
99
100
    /**
101
     * Select default item
102
     */
103
    private function setDefaultSelectedItem() : void
104
    {
105
        foreach ($this->items as $index => $item) {
106
            if ($item->canSelect()) {
107
                $this->canBeSelected = true;
108
                $this->selectedItemIndex = $index;
109
                return;
110
            }
111
        }
112
113
        $this->canBeSelected = false;
114
        $this->selectedItemIndex = null;
115
    }
116
117
    /**
118
     * The output text for the item
119
     */
120
    public function getRows(MenuStyle $style, bool $selected = false) : array
121
    {
122
        $numberOfItems = count($this->items);
123
124
        if ($numberOfItems === 0) {
125
            throw new \RuntimeException(sprintf('There should be at least one item added to: %s', __CLASS__));
126
        }
127
        
128
        if (!$selected) {
129
            $this->setDefaultSelectedItem();
130
        }
131
132
        $largestItemExtra = $this->calculateItemExtra();
133
134
        $length = $largestItemExtra > 0
135
            ? floor($style->getContentWidth() / $numberOfItems) - ($largestItemExtra + 2)
136
            : floor($style->getContentWidth() / $numberOfItems);
137
138
        $length -= $this->gutter;
139
        $length = (int) $length;
140
141
        $missingLength = $style->getContentWidth() % $numberOfItems;
142
        
143
        return $this->buildRows(
144
            mapWithKeys($this->items, function (int $index, MenuItemInterface $item) use ($selected, $length, $style) {
145
                $isSelected = $selected && $index === $this->selectedItemIndex;
146
147
                $marker = '';
148
                if ($item->canSelect()) {
149
                    $marker = $item->getStyle()->getMarker($item, $isSelected);
150
                }
151
152
                $itemExtra = '';
153
                if ($item->getStyle()->getDisplaysExtra()) {
154
                    $itemExtraVal = $item->getStyle()->getItemExtra();
155
                    $itemExtra = $item->showsItemExtra()
156
                        ? sprintf('  %s', $itemExtraVal)
157
                        : sprintf('  %s', str_repeat(' ', mb_strlen($itemExtraVal)));
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
            }),
175
            $missingLength,
176
            $length,
177
            $largestItemExtra
178
        );
179
    }
180
181
    private function buildRows(array $cells, int $missingLength, int $length, int $largestItemExtra) : array
182
    {
183
        $extraPadLength = $largestItemExtra > 0 ? 2 + $largestItemExtra : 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
    /**
336
     * Finds largest itemExtra value in items
337
     */
338
    private function calculateItemExtra() : int
339
    {
340
        return max(array_map(
341
            function (MenuItemInterface $item) {
342
                return mb_strlen($item->getStyle()->getItemExtra());
343
            },
344
            array_filter($this->items, function (MenuItemInterface $item) {
345
                return $item->getStyle()->getDisplaysExtra();
346
            })
347
        ));
348
    }
349
350
    /**
351
     * @return DefaultStyle
352
     */
353
    public function getStyle(): ItemStyle
354
    {
355
        return $this->style;
356
    }
357
358
    public function setStyle(DefaultStyle $style): void
359
    {
360
        $this->style = $style;
361
    }
362
}
363