Completed
Pull Request — master (#203)
by
unknown
01:50
created

RadioItem::showItemExtra()   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
nc 1
nop 0
dl 0
loc 3
rs 10
c 1
b 0
f 0
1
<?php
2
3
namespace PhpSchool\CliMenu\MenuItem;
4
5
use PhpSchool\CliMenu\CliMenu;
6
use PhpSchool\CliMenu\Style;
7
8
class RadioItem implements MenuItemInterface, ToggableItemInterface, RadioInterface
9
{
10
    use ToggableTrait;
11
12
    public function __construct(
13
        string $text,
14
        callable $selectAction,
15
        bool $showItemExtra = false,
16
        bool $disabled = false
17
    ) {
18
        $this->text          = $text;
19
        $this->selectAction  = $selectAction;
20
        $this->showItemExtra = $showItemExtra;
21
        $this->disabled      = $disabled;
22
    }
23
24
    public function getStyle() : Style\ItemStyleInterface
25
    {
26
        if (!$this->style) {
27
            $this->style = new Style\RadioStyle();
28
        }
29
30
        return $this->style;
31
    }
32
33
    /**
34
     * @param Style\RadioStyle|Style\ItemStyleInterface $style
35
     * @return $this
36
     */
37
    public function setStyle(Style\ItemStyleInterface $style) : self
38
    {
39
        $this->style = $style;
40
41
        return $this;
42
    }
43
44
    /**
45
     * Execute the items callable if required
46
     */
47
    public function getSelectAction() : ?callable
48
    {
49
        return function (CliMenu $cliMenu) {
50
            $parentItem = $cliMenu->getItemByIndex($cliMenu->getSelectedItemIndex());
51
52
            $siblings = $parentItem instanceof SplitItem
53
                ? $parentItem->getItems()
54
                : $cliMenu->getItems();
55
56
            $filtered = array_filter(
57
                $siblings,
58
                function (MenuItemInterface $item) {
59
                    return $item instanceof self;
60
                }
61
            );
62
63
            array_walk(
64
                $filtered,
65
                function (RadioItem $checkableItem) {
66
                    $checkableItem->setUnchecked();
67
                }
68
            );
69
70
            $this->setChecked();
71
            $cliMenu->redraw();
72
73
            return ($this->selectAction)($cliMenu);
74
        };
75
    }
76
}
77