1
|
|
|
<?php |
2
|
|
|
namespace keeko\tools\helpers; |
3
|
|
|
|
4
|
|
|
use Symfony\Component\Console\Question\Question; |
5
|
|
|
use Symfony\Component\Console\Question\ConfirmationQuestion; |
6
|
|
|
|
7
|
|
|
/** |
8
|
|
|
* Helper for questions |
9
|
|
|
* |
10
|
|
|
* Original: https://github.com/composer/composer/blob/master/src/Composer/Command/Helper/DialogHelper.php |
11
|
|
|
*/ |
12
|
|
|
trait QuestionHelperTrait { |
13
|
|
|
|
14
|
|
|
/** |
15
|
|
|
* Build text for asking a question. For example: |
16
|
|
|
* |
17
|
|
|
* "Do you want to continue [yes]:" |
18
|
|
|
* |
19
|
|
|
* @param string $question The question you want to ask |
20
|
|
|
* @param mixed $default Default value to add to message, if false no default will be shown |
21
|
|
|
* @param string $sep Separation char for between message and user input |
22
|
|
|
* |
23
|
|
|
* @return string |
24
|
|
|
*/ |
25
|
|
|
protected function getQuestion($question, $default = null, $sep = ':') { |
26
|
|
|
return !empty($default) ? |
27
|
|
|
sprintf('<info>%s</info> [<comment>%s</comment>]%s ', $question, $default, $sep) : |
28
|
|
|
sprintf('<info>%s</info>%s ', $question, $sep); |
29
|
|
|
} |
30
|
|
|
|
31
|
|
|
/** |
32
|
|
|
* @return HelperSet |
33
|
|
|
*/ |
34
|
|
|
abstract protected function getHelperSet(); |
35
|
|
|
|
36
|
|
|
private $dialog; |
37
|
|
|
|
38
|
|
|
/** |
39
|
|
|
* |
40
|
|
|
* @param Question $question |
41
|
|
|
* @return string the answer |
42
|
|
|
*/ |
43
|
|
|
private function ask(Question $question) { |
44
|
|
|
if ($this->dialog === null) { |
45
|
|
|
$this->dialog = $this->getHelperSet()->get('question'); |
46
|
|
|
} |
47
|
|
|
$input = $this->getHelperSet()->get('io')->getInput(); |
48
|
|
|
$output = $this->getHelperSet()->get('io')->getOutput(); |
49
|
|
|
return $this->dialog->ask($input, $output, $question); |
50
|
|
|
} |
51
|
|
|
|
52
|
|
|
/** |
53
|
|
|
* Asks a question |
54
|
|
|
* |
55
|
|
|
* @param Question $question |
56
|
|
|
* @return string the answer |
57
|
|
|
*/ |
58
|
|
|
protected function askQuestion(Question $question) { |
59
|
|
|
$default = $question->getDefault(); |
60
|
|
|
$q = $this->getQuestion($question->getQuestion(), $default); |
61
|
|
|
$q = new Question($q, $default); |
62
|
|
|
$q->setAutocompleterValues($question->getAutocompleterValues()); |
63
|
|
|
return $this->ask($q); |
64
|
|
|
} |
65
|
|
|
|
66
|
|
|
/** |
67
|
|
|
* Asks a confirmation question |
68
|
|
|
* |
69
|
|
|
* @param ConfirmationQuestion $question |
70
|
|
|
* @return string the answer |
71
|
|
|
*/ |
72
|
|
|
protected function askConfirmation(ConfirmationQuestion $question) { |
73
|
|
|
$default = 'y/n'; |
74
|
|
|
$q = $this->getQuestion($question->getQuestion(), $default); |
75
|
|
|
return $this->ask(new ConfirmationQuestion($q)); |
76
|
|
|
} |
77
|
|
|
|
78
|
|
|
} |