Completed
Pull Request — master (#183)
by Aydin
03:49 queued 02:06
created

SplitItem::getText()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

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