Skip to content

Commit 40f0c13

Browse files
authored
Merge pull request #177 from vesper8/master
adds ability to set custom validator on Text and Number inputs
2 parents 83fbce5 + 96b37dc commit 40f0c13

File tree

2 files changed

+44
-0
lines changed

2 files changed

+44
-0
lines changed

src/Input/Number.php

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,11 @@ class Number implements Input
3030
*/
3131
private $placeholderText = '';
3232

33+
/**
34+
* @var null|callable
35+
*/
36+
private $validator;
37+
3338
/**
3439
* @var MenuStyle
3540
*/
@@ -77,6 +82,13 @@ public function getPlaceholderText() : string
7782
return $this->placeholderText;
7883
}
7984

85+
public function setValidator(callable $validator) : Input
86+
{
87+
$this->validator = $validator;
88+
89+
return $this;
90+
}
91+
8092
public function ask() : InputResult
8193
{
8294
$this->inputIO->registerControlCallback(InputCharacter::UP, function (string $input) {
@@ -92,6 +104,16 @@ public function ask() : InputResult
92104

93105
public function validate(string $input) : bool
94106
{
107+
if ($this->validator) {
108+
$validator = $this->validator;
109+
110+
if ($validator instanceof \Closure) {
111+
$validator = $validator->bindTo($this);
112+
}
113+
114+
return $validator($input);
115+
}
116+
95117
return (bool) preg_match('/^-?\d+$/', $input);
96118
}
97119

src/Input/Text.php

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,11 @@ class Text implements Input
2929
*/
3030
private $placeholderText = '';
3131

32+
/**
33+
* @var null|callable
34+
*/
35+
private $validator;
36+
3237
/**
3338
* @var MenuStyle
3439
*/
@@ -76,13 +81,30 @@ public function getPlaceholderText() : string
7681
return $this->placeholderText;
7782
}
7883

84+
public function setValidator(callable $validator) : Input
85+
{
86+
$this->validator = $validator;
87+
88+
return $this;
89+
}
90+
7991
public function ask() : InputResult
8092
{
8193
return $this->inputIO->collect($this);
8294
}
8395

8496
public function validate(string $input) : bool
8597
{
98+
if ($this->validator) {
99+
$validator = $this->validator;
100+
101+
if ($validator instanceof \Closure) {
102+
$validator = $validator->bindTo($this);
103+
}
104+
105+
return $validator($input);
106+
}
107+
86108
return !empty($input);
87109
}
88110

0 commit comments

Comments
 (0)