Passed
Pull Request — master (#203)
by
unknown
01:56
created

RadioItem::setStyle()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
c 0
b 0
f 0
nc 1
nop 1
dl 0
loc 5
rs 10
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
        $this->style = new Style\RadioStyle();
24
    }
25
26
    public function getStyle() : Style\ItemStyleInterface
27
    {
28
        return $this->style;
29
    }
30
31
    /**
32
     * @param Style\RadioStyle|Style\ItemStyleInterface $style
33
     * @return $this
34
     */
35
    public function setStyle(Style\ItemStyleInterface $style) : self
36
    {
37
        $this->style = $style;
38
39
        return $this;
40
    }
41
42
    /**
43
     * Execute the items callable if required
44
     */
45
    public function getSelectAction() : ?callable
46
    {
47
        return function (CliMenu $cliMenu) {
48
            $parentItem = $cliMenu->getItemByIndex($cliMenu->getSelectedItemIndex());
49
50
            $siblings = $parentItem instanceof SplitItem
51
                ? $parentItem->getItems()
52
                : $cliMenu->getItems();
53
54
            $filtered = array_filter(
55
                $siblings,
56
                function (MenuItemInterface $item) {
57
                    return $item instanceof self;
58
                }
59
            );
60
61
            array_walk(
62
                $filtered,
63
                function (RadioItem $checkableItem) {
64
                    $checkableItem->setUnchecked();
65
                }
66
            );
67
68
            $this->setChecked();
69
            $cliMenu->redraw();
70
71
            return ($this->selectAction)($cliMenu);
72
        };
73
    }
74
}
75