Passed
Pull Request — master (#205)
by Aydin
02:04
created

CheckboxItem::getRows()   A

Complexity

Conditions 5
Paths 2

Size

Total Lines 30
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
eloc 19
c 0
b 0
f 0
nc 2
nop 2
dl 0
loc 30
rs 9.3222
1
<?php
2
3
namespace PhpSchool\CliMenu\MenuItem;
4
5
use PhpSchool\CliMenu\CliMenu;
6
use PhpSchool\CliMenu\MenuStyle;
7
use PhpSchool\CliMenu\Util\StringUtil;
8
use PhpSchool\CliMenu\Style\CheckboxStyle;
9
10
class CheckboxItem implements MenuItemInterface, ToggableItemInterface
11
{
12
    use ToggableTrait;
13
14
    /**
15
     * @var CheckboxStyle;
16
     */
17
    private $style;
18
19
    public function __construct(
20
        string $text,
21
        callable $selectAction,
22
        bool $showItemExtra = false,
23
        bool $disabled = false
24
    ) {
25
        $this->text          = $text;
26
        $this->selectAction  = $selectAction;
27
        $this->showItemExtra = $showItemExtra;
28
        $this->disabled      = $disabled;
29
30
        $this->style = new CheckboxStyle();
31
    }
32
33
    /**
34
     * The output text for the item
35
     */
36
    public function getRows(MenuStyle $style, bool $selected = false) : array
37
    {
38
        $marker = sprintf("%s", $this->style->getMarker($this->checked));
39
40
        $itemExtra = $this->style->getItemExtra();
41
42
        $length = $this->style->getDisplaysExtra()
43
            ? $style->getContentWidth() - (mb_strlen($itemExtra) + 2)
44
            : $style->getContentWidth();
45
46
        $rows = explode(
47
            "\n",
48
            StringUtil::wordwrap(
49
                sprintf('%s%s', $marker, $this->text),
50
                $length,
51
                sprintf("\n%s", str_repeat(' ', mb_strlen($marker)))
52
            )
53
        );
54
55
        return array_map(function ($row, $key) use ($style, $length, $itemExtra) {
56
            $text = $this->disabled ? $style->getDisabledItemText($row) : $row;
57
58
            if ($key === 0) {
59
                return $this->showItemExtra
60
                    ? sprintf('%s%s  %s', $text, str_repeat(' ', $length - mb_strlen($row)), $itemExtra)
61
                    : $text;
62
            }
63
64
            return $text;
65
        }, $rows, array_keys($rows));
66
    }
67
68
    /**
69
     * Execute the items callable if required
70
     */
71
    public function getSelectAction() : ?callable
72
    {
73
        return function (CliMenu $cliMenu) {
74
            $this->toggle();
75
            $cliMenu->redraw();
76
77
            return ($this->selectAction)($cliMenu);
78
        };
79
    }
80
81
    public function getStyle() : CheckboxStyle
82
    {
83
        return $this->style;
84
    }
85
86
    public function setStyle(CheckboxStyle $style) : self
87
    {
88
        $this->style = $style;
89
90
        return $this;
91
    }
92
}
93