123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139 |
- <?php
- namespace Symfony\Component\Console\Helper;
- use Symfony\Component\Console\Output\OutputInterface;
- class DialogHelper extends Helper
- {
- private $inputStream;
-
- public function ask(OutputInterface $output, $question, $default = null)
- {
- $output->write($question);
- $ret = fgets($this->inputStream ?: STDIN, 4096);
- if (false === $ret) {
- throw new \RuntimeException('Aborted');
- }
- $ret = trim($ret);
- return strlen($ret) > 0 ? $ret : $default;
- }
-
- public function askConfirmation(OutputInterface $output, $question, $default = true)
- {
- $answer = 'z';
- while ($answer && !in_array(strtolower($answer[0]), array('y', 'n'))) {
- $answer = $this->ask($output, $question);
- }
- if (false === $default) {
- return $answer && 'y' == strtolower($answer[0]);
- }
- return !$answer || 'y' == strtolower($answer[0]);
- }
-
- public function askAndValidate(OutputInterface $output, $question, $validator, $attempts = false, $default = null)
- {
- $error = null;
- while (false === $attempts || $attempts--) {
- if (null !== $error) {
- $output->writeln($this->getHelperSet()->get('formatter')->formatBlock($error->getMessage(), 'error'));
- }
- $value = $this->ask($output, $question, $default);
- try {
- return call_user_func($validator, $value);
- } catch (\Exception $error) {
- }
- }
- throw $error;
- }
-
- public function setInputStream($stream)
- {
- $this->inputStream = $stream;
- }
-
- public function getInputStream()
- {
- return $this->inputStream;
- }
-
- public function getName()
- {
- return 'dialog';
- }
- }
|