1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace PhpSchool\CliMenu\MenuItem; |
4
|
|
|
|
5
|
|
|
use PhpSchool\CliMenu\MenuStyle; |
6
|
|
|
use PhpSchool\CliMenu\Style; |
7
|
|
|
use PhpSchool\CliMenu\Util\StringUtil; |
8
|
|
|
|
9
|
|
|
/** |
10
|
|
|
* @author Michael Woodward <[email protected]> |
11
|
|
|
*/ |
12
|
|
|
trait SelectableTrait |
13
|
|
|
{ |
14
|
|
|
private $text = ''; |
15
|
|
|
|
16
|
|
|
private $showItemExtra = false; |
17
|
|
|
|
18
|
|
|
private $disabled = false; |
19
|
|
|
|
20
|
|
|
/** |
21
|
|
|
* @var Style\ItemStyleInterface; |
22
|
|
|
*/ |
23
|
|
|
private $style; |
24
|
|
|
|
25
|
|
|
public function getStyle() : Style\ItemStyleInterface |
26
|
|
|
{ |
27
|
|
|
return $this->style; |
28
|
|
|
} |
29
|
|
|
|
30
|
|
|
/** |
31
|
|
|
* @param Style\ItemStyleInterface|Style\SelectableStyle $style |
32
|
|
|
* @return $this |
33
|
|
|
*/ |
34
|
|
|
public function setStyle(Style\ItemStyleInterface $style) : self |
35
|
|
|
{ |
36
|
|
|
$this->style = $style; |
37
|
|
|
|
38
|
|
|
return $this; |
39
|
|
|
} |
40
|
|
|
|
41
|
|
|
/** |
42
|
|
|
* The output text for the item |
43
|
|
|
*/ |
44
|
|
|
public function getRows(MenuStyle $style, bool $selected = false) : array |
45
|
|
|
{ |
46
|
|
|
$marker = sprintf("%s", $this->style->getMarker($selected)); |
47
|
|
|
|
48
|
|
|
$length = $this->style->getDisplaysExtra() |
49
|
|
|
? $style->getContentWidth() - (mb_strlen($this->style->getItemExtra()) + 2) |
50
|
|
|
: $style->getContentWidth(); |
51
|
|
|
|
52
|
|
|
$rows = explode( |
53
|
|
|
"\n", |
54
|
|
|
StringUtil::wordwrap( |
55
|
|
|
sprintf('%s%s', $marker, $this->text), |
56
|
|
|
$length, |
57
|
|
|
sprintf("\n%s", str_repeat(' ', mb_strlen($marker))) |
58
|
|
|
) |
59
|
|
|
); |
60
|
|
|
|
61
|
|
|
return array_map(function ($row, $key) use ($style, $length) { |
62
|
|
|
$text = $this->disabled ? $style->getDisabledItemText($row) : $row; |
63
|
|
|
|
64
|
|
|
if ($key === 0) { |
65
|
|
|
return $this->showItemExtra |
66
|
|
|
? sprintf('%s%s %s', $text, str_repeat(' ', $length - mb_strlen($row)), $this->style->getItemExtra()) |
67
|
|
|
: $text; |
68
|
|
|
} |
69
|
|
|
|
70
|
|
|
return $text; |
71
|
|
|
}, $rows, array_keys($rows)); |
72
|
|
|
} |
73
|
|
|
|
74
|
|
|
/** |
75
|
|
|
* Can the item be selected |
76
|
|
|
*/ |
77
|
|
|
public function canSelect() : bool |
78
|
|
|
{ |
79
|
|
|
return !$this->disabled; |
80
|
|
|
} |
81
|
|
|
|
82
|
|
|
public function showsItemExtra() : bool |
83
|
|
|
{ |
84
|
|
|
return $this->showItemExtra; |
85
|
|
|
} |
86
|
|
|
|
87
|
|
|
/** |
88
|
|
|
* Enable showing item extra |
89
|
|
|
*/ |
90
|
|
|
public function showItemExtra() : void |
91
|
|
|
{ |
92
|
|
|
$this->showItemExtra = true; |
93
|
|
|
} |
94
|
|
|
|
95
|
|
|
/** |
96
|
|
|
* Disable showing item extra |
97
|
|
|
*/ |
98
|
|
|
public function hideItemExtra() : void |
99
|
|
|
{ |
100
|
|
|
$this->showItemExtra = false; |
101
|
|
|
} |
102
|
|
|
} |
103
|
|
|
|