forked from php-school/cli-menu
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNumber.php
More file actions
113 lines (83 loc) · 2.52 KB
/
Copy pathNumber.php
File metadata and controls
113 lines (83 loc) · 2.52 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
<?php
declare(strict_types=1);
namespace PhpSchool\CliMenu\Input;
use PhpSchool\CliMenu\MenuStyle;
use PhpSchool\Terminal\InputCharacter;
/**
* @author Aydin Hassan <[email protected]>
*/
class Number implements Input
{
private InputIO $inputIO;
private string $promptText = 'Enter a number:';
private string $validationFailedText = 'Not a valid number, try again';
private string $placeholderText = '';
private \Closure|null $validator = null;
private MenuStyle $style;
public function __construct(InputIO $inputIO, MenuStyle $style)
{
$this->inputIO = $inputIO;
$this->style = $style;
}
public function setPromptText(string $promptText): Input
{
$this->promptText = $promptText;
return $this;
}
public function getPromptText(): string
{
return $this->promptText;
}
public function setValidationFailedText(string $validationFailedText): Input
{
$this->validationFailedText = $validationFailedText;
return $this;
}
public function getValidationFailedText(): string
{
return $this->validationFailedText;
}
public function setPlaceholderText(string $placeholderText): Input
{
$this->placeholderText = $placeholderText;
return $this;
}
public function getPlaceholderText(): string
{
return $this->placeholderText;
}
public function setValidator(callable $validator): Input
{
if ($validator instanceof \Closure) {
$validator = $validator->bindTo($this);
}
$this->validator = $validator(...);
return $this;
}
public function ask(): InputResult
{
$this->inputIO->registerControlCallback(InputCharacter::UP, function (string $input) {
return $this->validate($input) ? (string) ((int) $input + 1) : $input;
});
$this->inputIO->registerControlCallback(InputCharacter::DOWN, function (string $input) {
return $this->validate($input) ? (string) ((int) $input - 1) : $input;
});
return $this->inputIO->collect($this);
}
public function validate(string $input): bool
{
if ($this->validator) {
$validator = $this->validator;
return $validator($input);
}
return (bool) preg_match('/^-?\d+$/', $input);
}
public function filter(string $value): string
{
return $value;
}
public function getStyle(): MenuStyle
{
return $this->style;
}
}