|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace TheAentMachine\Prompt; |
|
4
|
|
|
|
|
5
|
|
|
use Symfony\Component\Console\Question\Question; |
|
6
|
|
|
use TheAentMachine\Prompt\Helper\ValidatorHelper; |
|
7
|
|
|
|
|
8
|
|
|
final class Confirm extends AbstractInput |
|
9
|
|
|
{ |
|
10
|
|
|
/** @var null|bool */ |
|
11
|
|
|
private $default; |
|
12
|
|
|
|
|
13
|
|
|
/** |
|
14
|
|
|
* @param null|bool $default |
|
15
|
|
|
* @return self |
|
16
|
|
|
*/ |
|
17
|
|
|
public function setDefault(?bool $default): self |
|
18
|
|
|
{ |
|
19
|
|
|
$this->default = $default; |
|
20
|
|
|
return $this; |
|
21
|
|
|
} |
|
22
|
|
|
|
|
23
|
|
|
/** |
|
24
|
|
|
* @return Question |
|
25
|
|
|
*/ |
|
26
|
|
|
protected function build(): Question |
|
27
|
|
|
{ |
|
28
|
|
|
$question = parent::build(); |
|
29
|
|
|
$message = $question->getQuestion(); |
|
30
|
|
|
$validator = $question->getValidator(); |
|
31
|
|
|
if (!empty($this->default)) { |
|
32
|
|
|
$message .= $this->default === true ? ' [Y/n]: ' : ' [y/]: '; |
|
33
|
|
|
$question = new Question($message, $this->default === true ? 'yes' : 'no'); |
|
34
|
|
|
} else { |
|
35
|
|
|
$message .= ' [y/n]: '; |
|
36
|
|
|
$question = new Question($message); |
|
37
|
|
|
} |
|
38
|
|
|
$question->setValidator(ValidatorHelper::merge($validator, $this->boolValidator())); |
|
39
|
|
|
return $question; |
|
40
|
|
|
} |
|
41
|
|
|
|
|
42
|
|
|
/** |
|
43
|
|
|
* @return callable|null |
|
44
|
|
|
*/ |
|
45
|
|
|
private function boolValidator(): ?callable |
|
46
|
|
|
{ |
|
47
|
|
|
return function (?string $response) { |
|
48
|
|
|
$response = $response ?? ''; |
|
49
|
|
|
$response = \strtolower(trim($response)); |
|
50
|
|
|
if (!\in_array($response, ['y', 'n', 'yes', 'no'], true)) { |
|
51
|
|
|
throw new \InvalidArgumentException('Hey, answer must be "y" or "n"!'); |
|
52
|
|
|
} |
|
53
|
|
|
$response = \in_array($response, ['y', 'yes'], true) ? '1' : ''; |
|
54
|
|
|
return $response; |
|
55
|
|
|
}; |
|
56
|
|
|
} |
|
57
|
|
|
|
|
58
|
|
|
/** |
|
59
|
|
|
* @return bool |
|
60
|
|
|
*/ |
|
61
|
|
|
public function run(): bool |
|
62
|
|
|
{ |
|
63
|
|
|
$question = $this->build(); |
|
64
|
|
|
do { |
|
65
|
|
|
$response = $this->questionHelper->ask($this->input, $this->output, $question); |
|
66
|
|
|
} while (!empty($this->helpText) && $response === '?'); |
|
67
|
|
|
return !empty($response); |
|
68
|
|
|
} |
|
69
|
|
|
} |
|
70
|
|
|
|