Completed
Push — master ( 499201...4a0bb5 )
by Aydin
26s queued 12s
created

CliMenuBuilder::setSelectedMarker()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 3
nc 1
nop 1
dl 0
loc 6
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace PhpSchool\CliMenu\Builder;
4
5
use PhpSchool\CliMenu\Action\ExitAction;
6
use PhpSchool\CliMenu\Action\GoBackAction;
7
use PhpSchool\CliMenu\Exception\InvalidShortcutException;
8
use PhpSchool\CliMenu\MenuItem\AsciiArtItem;
9
use PhpSchool\CliMenu\MenuItem\CheckboxItem;
10
use PhpSchool\CliMenu\MenuItem\LineBreakItem;
11
use PhpSchool\CliMenu\MenuItem\MenuItemInterface;
12
use PhpSchool\CliMenu\MenuItem\MenuMenuItem;
13
use PhpSchool\CliMenu\MenuItem\RadioItem;
14
use PhpSchool\CliMenu\MenuItem\SelectableItem;
15
use PhpSchool\CliMenu\CliMenu;
16
use PhpSchool\CliMenu\MenuItem\SplitItem;
17
use PhpSchool\CliMenu\MenuItem\StaticItem;
18
use PhpSchool\CliMenu\MenuStyle;
19
use PhpSchool\CliMenu\Style\CheckboxStyle;
20
use PhpSchool\CliMenu\Style\RadioStyle;
21
use PhpSchool\CliMenu\Style\SelectableStyle;
22
use PhpSchool\CliMenu\Terminal\TerminalFactory;
23
use PhpSchool\Terminal\Terminal;
24
25
/**
26
 * @author Michael Woodward <[email protected]>
27
 * @author Aydin Hassan <[email protected]>
28
 */
29
class CliMenuBuilder
30
{
31
    /**
32
     * @var CliMenu
33
     */
34
    private $menu;
35
36
    /**
37
     * @var string
38
     */
39
    private $goBackButtonText = 'Go Back';
40
41
    /**
42
     * @var string
43
     */
44
    private $exitButtonText = 'Exit';
45
46
    /**
47
     * @var MenuStyle
48
     */
49
    private $style;
50
51
    /**
52
     * @var Terminal
53
     */
54
    private $terminal;
55
56
    /**
57
     * @var bool
58
     */
59
    private $disableDefaultItems = false;
60
61
    /**
62
     * @var bool
63
     */
64
    private $disabled = false;
65
66
    /**
67
     * Whether or not to auto create keyboard shortcuts for items
68
     * when they contain square brackets. Eg: [M]y item
69
     *
70
     * @var bool
71
     */
72
    private $autoShortcuts = false;
73
74
    /**
75
     * Regex to auto match for shortcuts defaults to looking
76
     * for a single character encased in square brackets
77
     *
78
     * @var string
79
     */
80
    private $autoShortcutsRegex = '/\[(.)\]/';
81
82
    /**
83
     * @var bool
84
     */
85
    private $subMenu = false;
86
87
    public function __construct(Terminal $terminal = null)
88
    {
89
        $this->terminal = $terminal ?? TerminalFactory::fromSystem();
90
        $this->style    = new MenuStyle($this->terminal);
91
        $this->menu     = new CliMenu(null, [], $this->terminal, $this->style);
92
    }
93
94
    public static function newSubMenu(Terminal $terminal) : self
95
    {
96
        $instance = new self($terminal);
97
        $instance->subMenu = true;
98
99
        return $instance;
100
    }
101
102
    public function setTitle(string $title) : self
103
    {
104
        $this->menu->setTitle($title);
105
106
        return $this;
107
    }
108
109
    public function addMenuItem(MenuItemInterface $item) : self
110
    {
111
        $this->menu->addItem($item);
112
113
        $this->processItemShortcut($item);
114
115
        return $this;
116
    }
117
118
    public function addItem(
119
        string $text,
120
        callable $itemCallable,
121
        bool $showItemExtra = false,
122
        bool $disabled = false
123
    ) : self {
124
        $this->addMenuItem(new SelectableItem($text, $itemCallable, $showItemExtra, $disabled));
125
126
        return $this;
127
    }
128
129
    public function addItems(array $items) : self
130
    {
131
        foreach ($items as $item) {
132
            $this->addItem(...$item);
0 ignored issues
show
Bug introduced by
The call to PhpSchool\CliMenu\Builde...iMenuBuilder::addItem() has too few arguments starting with itemCallable. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

132
            $this->/** @scrutinizer ignore-call */ 
133
                   addItem(...$item);

This check compares calls to functions or methods with their respective definitions. If the call has less arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
133
        }
134
135
        return $this;
136
    }
137
138
    public function addCheckboxItem(
139
        string $text,
140
        callable $itemCallable,
141
        bool $showItemExtra = false,
142
        bool $disabled = false
143
    ) : self {
144
        $this->addMenuItem(new CheckboxItem($text, $itemCallable, $showItemExtra, $disabled));
145
146
        return $this;
147
    }
148
149
    public function addRadioItem(
150
        string $text,
151
        callable $itemCallable,
152
        bool $showItemExtra = false,
153
        bool $disabled = false
154
    ) : self {
155
        $this->addMenuItem(new RadioItem($text, $itemCallable, $showItemExtra, $disabled));
156
157
        return $this;
158
    }
159
160
    public function addStaticItem(string $text) : self
161
    {
162
        $this->addMenuItem(new StaticItem($text));
163
164
        return $this;
165
    }
166
167
    public function addLineBreak(string $breakChar = ' ', int $lines = 1) : self
168
    {
169
        $this->addMenuItem(new LineBreakItem($breakChar, $lines));
170
171
        return $this;
172
    }
173
174
    public function addAsciiArt(string $art, string $position = AsciiArtItem::POSITION_CENTER, string $alt = '') : self
175
    {
176
        $this->addMenuItem(new AsciiArtItem($art, $position, $alt));
177
178
        return $this;
179
    }
180
181
    public function addSubMenu(string $text, \Closure $callback) : self
182
    {
183
        $builder = self::newSubMenu($this->terminal);
184
185
        if ($this->autoShortcuts) {
186
            $builder->enableAutoShortcuts($this->autoShortcutsRegex);
187
        }
188
189
        $callback($builder);
190
191
        $menu = $builder->build();
192
        $menu->setParent($this->menu);
193
194
        $this->menu->addItem($item = new MenuMenuItem(
195
            $text,
196
            $menu,
197
            $builder->isMenuDisabled()
198
        ));
199
200
        $this->processItemShortcut($item);
201
202
        return $this;
203
    }
204
205
    public function addSubMenuFromBuilder(string $text, CliMenuBuilder $builder) : self
206
    {
207
        $menu = $builder->build();
208
        $menu->setParent($this->menu);
209
210
        $this->menu->addItem($item = new MenuMenuItem(
211
            $text,
212
            $menu,
213
            $builder->isMenuDisabled()
214
        ));
215
216
        $this->processItemShortcut($item);
217
218
        return $this;
219
    }
220
221
    public function enableAutoShortcuts(string $regex = null) : self
222
    {
223
        $this->autoShortcuts = true;
224
225
        if (null !== $regex) {
226
            $this->autoShortcutsRegex = $regex;
227
        }
228
229
        return $this;
230
    }
231
232
    private function extractShortcut(string $title) : ?string
233
    {
234
        preg_match($this->autoShortcutsRegex, $title, $match);
235
236
        if (!isset($match[1])) {
237
            return null;
238
        }
239
240
        if (mb_strlen($match[1]) > 1) {
241
            throw InvalidShortcutException::fromShortcut($match[1]);
242
        }
243
244
        return isset($match[1]) ? strtolower($match[1]) : null;
245
    }
246
247
    private function processItemShortcut(MenuItemInterface $item) : void
248
    {
249
        $this->processIndividualShortcut($item, function (CliMenu $menu) use ($item) {
250
            $menu->executeAsSelected($item);
251
        });
252
    }
253
254
    private function processSplitItemShortcuts(SplitItem $splitItem) : void
255
    {
256
        foreach ($splitItem->getItems() as $item) {
257
            $this->processIndividualShortcut($item, function (CliMenu $menu) use ($splitItem, $item) {
258
                $current = $splitItem->getSelectedItemIndex();
259
260
                $splitItem->setSelectedItemIndex(
261
                    array_search($item, $splitItem->getItems(), true)
0 ignored issues
show
Bug introduced by
It seems like array_search($item, $splitItem->getItems(), true) can also be of type false and string; however, parameter $index of PhpSchool\CliMenu\MenuIt...:setSelectedItemIndex() does only seem to accept integer, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

261
                    /** @scrutinizer ignore-type */ array_search($item, $splitItem->getItems(), true)
Loading history...
262
                );
263
264
                $menu->executeAsSelected($splitItem);
265
266
                if ($current !== null) {
267
                    $splitItem->setSelectedItemIndex($current);
268
                }
269
            });
270
        }
271
    }
272
273
    private function processIndividualShortcut(MenuItemInterface $item, callable $callback) : void
274
    {
275
        if (!$this->autoShortcuts) {
276
            return;
277
        }
278
279
        if ($shortcut = $this->extractShortcut($item->getText())) {
280
            $this->menu->addCustomControlMapping(
281
                $shortcut,
282
                $callback
283
            );
284
        }
285
    }
286
287
    public function addSplitItem(\Closure $callback) : self
288
    {
289
        $builder = new SplitItemBuilder($this->menu);
290
291
        if ($this->autoShortcuts) {
292
            $builder->enableAutoShortcuts($this->autoShortcutsRegex);
293
        }
294
295
        $callback($builder);
296
297
        $this->menu->addItem($splitItem = $builder->build());
298
299
        $this->processSplitItemShortcuts($splitItem);
300
301
        return $this;
302
    }
303
304
    /**
305
     * Disable a submenu
306
     *
307
     * @throws \InvalidArgumentException
308
     */
309
    public function disableMenu() : self
310
    {
311
        if (!$this->subMenu) {
312
            throw new \InvalidArgumentException(
313
                'You can\'t disable the root menu'
314
            );
315
        }
316
317
        $this->disabled = true;
318
319
        return $this;
320
    }
321
322
    public function isMenuDisabled() : bool
323
    {
324
        return $this->disabled;
325
    }
326
327
    public function setGoBackButtonText(string $goBackButtonTest) : self
328
    {
329
        $this->goBackButtonText = $goBackButtonTest;
330
331
        return $this;
332
    }
333
334
    public function setExitButtonText(string $exitButtonText) : self
335
    {
336
        $this->exitButtonText = $exitButtonText;
337
338
        return $this;
339
    }
340
341
    public function setBackgroundColour(string $colour, string $fallback = null) : self
342
    {
343
        $this->style->setBg($colour, $fallback);
344
345
        return $this;
346
    }
347
348
    public function setForegroundColour(string $colour, string $fallback = null) : self
349
    {
350
        $this->style->setFg($colour, $fallback);
351
352
        return $this;
353
    }
354
355
    public function setWidth(int $width) : self
356
    {
357
        $this->style->setWidth($width);
358
359
        return $this;
360
    }
361
362
    public function setPadding(int $topBottom, int $leftRight = null) : self
363
    {
364
        $this->style->setPadding($topBottom, $leftRight);
365
366
        return $this;
367
    }
368
369
    public function setPaddingTopBottom(int $topBottom) : self
370
    {
371
        $this->style->setPaddingTopBottom($topBottom);
372
373
        return $this;
374
    }
375
376
    public function setPaddingLeftRight(int $leftRight) : self
377
    {
378
        $this->style->setPaddingLeftRight($leftRight);
379
380
        return $this;
381
    }
382
383
    public function setMarginAuto() : self
384
    {
385
        $this->style->setMarginAuto();
386
387
        return $this;
388
    }
389
390
    public function setMargin(int $margin) : self
391
    {
392
        $this->style->setMargin($margin);
393
394
        return $this;
395
    }
396
397
    public function setItemExtra(string $extra) : self
398
    {
399
        $this->style->setItemExtra($extra);
400
        $this->menu->getSelectableStyle()->setItemExtra($extra);
401
402
        // if we customise item extra, it means we most likely want to display it
403
        $this->displayExtra();
404
405
        return $this;
406
    }
407
408
    public function setTitleSeparator(string $separator) : self
409
    {
410
        $this->style->setTitleSeparator($separator);
411
412
        return $this;
413
    }
414
415
    public function setBorder(int $top, $right = null, $bottom = null, $left = null, string $colour = null) : self
416
    {
417
        $this->style->setBorder($top, $right, $bottom, $left, $colour);
418
419
        return $this;
420
    }
421
422
    public function setBorderTopWidth(int $width) : self
423
    {
424
        $this->style->setBorderTopWidth($width);
425
426
        return $this;
427
    }
428
429
    public function setBorderRightWidth(int $width) : self
430
    {
431
        $this->style->setBorderRightWidth($width);
432
433
        return $this;
434
    }
435
436
    public function setBorderBottomWidth(int $width) : self
437
    {
438
        $this->style->setBorderBottomWidth($width);
439
440
        return $this;
441
    }
442
443
    public function setBorderLeftWidth(int $width) : self
444
    {
445
        $this->style->setBorderLeftWidth($width);
446
447
        return $this;
448
    }
449
450
    public function setBorderColour(string $colour, $fallback = null) : self
451
    {
452
        $this->style->setBorderColour($colour, $fallback);
453
454
        return $this;
455
    }
456
457
    public function getStyle() : MenuStyle
458
    {
459
        return $this->style;
460
    }
461
462
    public function getTerminal() : Terminal
463
    {
464
        return $this->terminal;
465
    }
466
467
    private function getDefaultItems() : array
468
    {
469
        $actions = [];
470
        if ($this->subMenu) {
471
            $actions[] = new SelectableItem($this->goBackButtonText, new GoBackAction);
472
        }
473
474
        $actions[] = new SelectableItem($this->exitButtonText, new ExitAction);
475
        return $actions;
476
    }
477
478
    public function disableDefaultItems() : self
479
    {
480
        $this->disableDefaultItems = true;
481
482
        return $this;
483
    }
484
485
    public function displayExtra() : self
486
    {
487
        $this->style->setDisplaysExtra(true);
488
        $this->menu->getSelectableStyle()->setDisplaysExtra(true);
489
490
        return $this;
491
    }
492
493
    private function itemsHaveExtra(array $items) : bool
494
    {
495
        return !empty(array_filter($items, function (MenuItemInterface $item) {
496
            return $item->showsItemExtra();
497
        }));
498
    }
499
500
    public function build() : CliMenu
501
    {
502
        if (!$this->disableDefaultItems) {
503
            $this->menu->addItems($this->getDefaultItems());
504
        }
505
506
        if (!$this->style->getDisplaysExtra()) {
507
            $this->style->setDisplaysExtra($this->itemsHaveExtra($this->menu->getItems()));
508
        }
509
510
        if (!$this->subMenu) {
511
            $this->propagateStyles($this->menu);
512
        }
513
514
        return $this->menu;
515
    }
516
517
    public function getCheckboxStyle() : CheckboxStyle
518
    {
519
        return $this->menu->getCheckboxStyle();
520
    }
521
522
    public function setCheckboxStyle(CheckboxStyle $style) : self
523
    {
524
        $this->menu->setCheckboxStyle($style);
525
526
        return $this;
527
    }
528
529
    public function modifyCheckboxStyle(callable $itemCallable) : self
530
    {
531
        $itemCallable($this->menu->getCheckboxStyle());
532
533
        return $this;
534
    }
535
536
    public function getRadioStyle() : RadioStyle
537
    {
538
        return $this->menu->getRadioStyle();
539
    }
540
541
    public function setRadioStyle(RadioStyle $style) : self
542
    {
543
        $this->menu->setRadioStyle($style);
544
545
        return $this;
546
    }
547
548
    public function modifyRadioStyle(callable $itemCallable) : self
549
    {
550
        $itemCallable($this->menu->getRadioStyle());
551
552
        return $this;
553
    }
554
555
    public function getSelectableStyle() : SelectableStyle
556
    {
557
        return $this->menu->getSelectableStyle();
558
    }
559
560
    public function setSelectableStyle(SelectableStyle $style) : self
561
    {
562
        $this->menu->setSelectableStyle($style);
563
564
        return $this;
565
    }
566
567
    public function modifySelectableStyle(callable $itemCallable) : self
568
    {
569
        $itemCallable($this->menu->getSelectableStyle());
570
571
        return $this;
572
    }
573
574
    /**
575
     * Pass styles from current menu to sub-menu
576
     * only if sub-menu style has not be customized
577
     */
578
    private function propagateStyles(CliMenu $menu, array $items = [])
579
    {
580
        $currentItems = !empty($items) ? $items : $menu->getItems();
581
582
        foreach ($currentItems as $item) {
583
            if ($item instanceof CheckboxItem
584
                && !$item->getStyle()->hasChangedFromDefaults()
585
            ) {
586
                $item->setStyle(clone $menu->getCheckboxStyle());
587
            }
588
589
            if ($item instanceof RadioItem
590
                && !$item->getStyle()->hasChangedFromDefaults()
591
            ) {
592
                $item->setStyle(clone $menu->getRadioStyle());
593
            }
594
595
            if (($item instanceof MenuMenuItem
596
                    || $item instanceof SelectableItem
597
                    || $item instanceof StaticItem
598
                )
599
                && !$item->getStyle()->hasChangedFromDefaults()
600
            ) {
601
                $item->setStyle(clone $menu->getSelectableStyle());
602
            }
603
604
            // Apply current style to children, if they are not customized
605
            if ($item instanceof MenuMenuItem) {
606
                $subMenu = $item->getSubMenu();
607
608
                if (!$subMenu->getStyle()->hasChangedFromDefaults()) {
609
                    $subMenu->setStyle(clone $menu->getStyle());
610
                }
611
612
                if (!$subMenu->getCheckboxStyle()->hasChangedFromDefaults()) {
613
                    $subMenu->setCheckboxStyle(clone $menu->getCheckboxStyle());
614
                }
615
616
                if (!$subMenu->getRadioStyle()->hasChangedFromDefaults()) {
617
                    $subMenu->setRadioStyle(clone $menu->getRadioStyle());
618
                }
619
620
                if (!$subMenu->getSelectableStyle()->hasChangedFromDefaults()) {
621
                    $subMenu->setSelectableStyle(clone $menu->getSelectableStyle());
622
                }
623
624
                $this->propagateStyles($subMenu);
625
            }
626
627
            // Apply styles to SplitItem children using current $menu
628
            if ($item instanceof SplitItem) {
629
                $this->propagateStyles($menu, $item->getItems());
630
            }
631
        }
632
    }
633
}
634