Completed
Pull Request — master (#210)
by
unknown
02:16
created

CliMenuBuilder::propagateStyles()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 10
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 6
nc 4
nop 1
dl 0
loc 10
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\Terminal\TerminalFactory;
20
use PhpSchool\Terminal\Terminal;
21
22
/**
23
 * @author Michael Woodward <[email protected]>
24
 * @author Aydin Hassan <[email protected]>
25
 */
26
class CliMenuBuilder
27
{
28
    /**
29
     * @var CliMenu
30
     */
31
    private $menu;
32
33
    /**
34
     * @var string
35
     */
36
    private $goBackButtonText = 'Go Back';
37
38
    /**
39
     * @var string
40
     */
41
    private $exitButtonText = 'Exit';
42
43
    /**
44
     * @var MenuStyle
45
     */
46
    private $style;
47
48
    /**
49
     * @var Terminal
50
     */
51
    private $terminal;
52
53
    /**
54
     * @var bool
55
     */
56
    private $disableDefaultItems = false;
57
58
    /**
59
     * @var bool
60
     */
61
    private $disabled = false;
62
63
    /**
64
     * Whether or not to auto create keyboard shortcuts for items
65
     * when they contain square brackets. Eg: [M]y item
66
     *
67
     * @var bool
68
     */
69
    private $autoShortcuts = false;
70
71
    /**
72
     * Regex to auto match for shortcuts defaults to looking
73
     * for a single character encased in square brackets
74
     *
75
     * @var string
76
     */
77
    private $autoShortcutsRegex = '/\[(.)\]/';
78
79
    /**
80
     * @var bool
81
     */
82
    private $subMenu = false;
83
84
    public function __construct(Terminal $terminal = null)
85
    {
86
        $this->terminal = $terminal ?? TerminalFactory::fromSystem();
87
        $this->style    = new MenuStyle($this->terminal);
88
        $this->menu     = new CliMenu(null, [], $this->terminal, $this->style);
89
    }
90
    
91
    public static function newSubMenu(Terminal $terminal) : self
92
    {
93
        $instance = new self($terminal);
94
        $instance->subMenu = true;
95
        
96
        return $instance;
97
    }
98
99
    public function setTitle(string $title) : self
100
    {
101
        $this->menu->setTitle($title);
102
103
        return $this;
104
    }
105
106
    public function addMenuItem(MenuItemInterface $item) : self
107
    {
108
        $this->menu->addItem($item);
109
110
        $this->processItemShortcut($item);
111
112
        return $this;
113
    }
114
115
    public function addItem(
116
        string $text,
117
        callable $itemCallable,
118
        bool $showItemExtra = false,
119
        bool $disabled = false
120
    ) : self {
121
        $this->addMenuItem(new SelectableItem($text, $itemCallable, $showItemExtra, $disabled));
122
123
        return $this;
124
    }
125
126
    public function addItems(array $items) : self
127
    {
128
        foreach ($items as $item) {
129
            $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

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

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