protected function interact(InputInterface $input, OutputInterface $output) { $helper = $this->getHelper('question'); $this->selectedSchema = $input->getArgument('name'); if (!array_key_exists($this->selectedSchema, $this->schemaList)) { $question = new ChoiceQuestion('Please select of of the following templates:', array_keys($this->schemaList)); $validator = function ($answer) use($output) { if (!array_key_exists($answer, $this->schemaList)) { throw new \RuntimeException('The name of the template not found'); } return $answer; }; $question->setValidator($validator); $question->setMaxAttempts(2); $this->selectedSchema = $helper->ask($input, $output, $question); } $schema = $this->schemaList[$this->selectedSchema]; foreach ($schema->getUndefinedVariables() as $var) { $question = new Question(sprintf('Please enter value for variable %s:', $var)); $answer = $helper->ask($input, $output, $question); $schema->setVariable($var, $answer); } $dir = $input->getOption('dir'); if (!$dir) { $dir = str_replace('\\', '/', $schema->getVariable('NAMESPACE')); } $this->selectedDir = trim($dir, '/\\'); }
protected function interact(InputInterface $input, OutputInterface $output) { $helper = $this->getHelper('question'); if (trim($input->getOption('name')) == '') { $question = new Question\Question('Please enter the client name: '); $question->setValidator(function ($value) { if (trim($value) == '') { throw new \Exception('The client name can not be empty'); } $doctrine = $this->getContainer()->get('doctrine'); $client = $doctrine->getRepository('AppBundle:Client')->findOneBy(['name' => $value]); if ($client instanceof \AppBundle\Entity\Client) { throw new \Exception('The client name must be unique'); } return $value; }); $question->setMaxAttempts(5); $input->setOption('name', $helper->ask($input, $output, $question)); } $grants = $input->getOption('grant-type'); if (!(is_array($grants) && count($grants))) { $question = new Question\ChoiceQuestion('Please select the grant types (defaults to password and facebook_access_token): ', [\OAuth2\OAuth2::GRANT_TYPE_AUTH_CODE, \OAuth2\OAuth2::GRANT_TYPE_CLIENT_CREDENTIALS, \OAuth2\OAuth2::GRANT_TYPE_EXTENSIONS, \OAuth2\OAuth2::GRANT_TYPE_IMPLICIT, \OAuth2\OAuth2::GRANT_TYPE_REFRESH_TOKEN, \OAuth2\OAuth2::GRANT_TYPE_USER_CREDENTIALS, 'http://grants.api.schoolmanager.ledo.eu.org/facebook_access_token'], '5,6'); $question->setMultiselect(true); $question->setMaxAttempts(5); $input->setOption('grant-type', $helper->ask($input, $output, $question)); } parent::interact($input, $output); }
public function testAskChoice() { $questionHelper = new SymfonyQuestionHelper(); $helperSet = new HelperSet(array(new FormatterHelper())); $questionHelper->setHelperSet($helperSet); $heroes = array('Superman', 'Batman', 'Spiderman'); $inputStream = $this->getInputStream("\n1\n 1 \nFabien\n1\nFabien\n1\n0,2\n 0 , 2 \n\n\n"); $question = new ChoiceQuestion('What is your favorite superhero?', $heroes, '2'); $question->setMaxAttempts(1); // first answer is an empty answer, we're supposed to receive the default value $this->assertEquals('Spiderman', $questionHelper->ask($this->createStreamableInputInterfaceMock($inputStream), $output = $this->createOutputInterface(), $question)); $this->assertOutputContains('What is your favorite superhero? [Spiderman]', $output); $question = new ChoiceQuestion('What is your favorite superhero?', $heroes); $question->setMaxAttempts(1); $this->assertEquals('Batman', $questionHelper->ask($this->createStreamableInputInterfaceMock($inputStream), $this->createOutputInterface(), $question)); $this->assertEquals('Batman', $questionHelper->ask($this->createStreamableInputInterfaceMock($inputStream), $this->createOutputInterface(), $question)); $question = new ChoiceQuestion('What is your favorite superhero?', $heroes); $question->setErrorMessage('Input "%s" is not a superhero!'); $question->setMaxAttempts(2); $this->assertEquals('Batman', $questionHelper->ask($this->createStreamableInputInterfaceMock($inputStream), $output = $this->createOutputInterface(), $question)); $this->assertOutputContains('Input "Fabien" is not a superhero!', $output); try { $question = new ChoiceQuestion('What is your favorite superhero?', $heroes, '1'); $question->setMaxAttempts(1); $questionHelper->ask($this->createStreamableInputInterfaceMock($inputStream), $output = $this->createOutputInterface(), $question); $this->fail(); } catch (\InvalidArgumentException $e) { $this->assertEquals('Value "Fabien" is invalid', $e->getMessage()); } $question = new ChoiceQuestion('What is your favorite superhero?', $heroes, null); $question->setMaxAttempts(1); $question->setMultiselect(true); $this->assertEquals(array('Batman'), $questionHelper->ask($this->createStreamableInputInterfaceMock($inputStream), $this->createOutputInterface(), $question)); $this->assertEquals(array('Superman', 'Spiderman'), $questionHelper->ask($this->createStreamableInputInterfaceMock($inputStream), $this->createOutputInterface(), $question)); $this->assertEquals(array('Superman', 'Spiderman'), $questionHelper->ask($this->createStreamableInputInterfaceMock($inputStream), $this->createOutputInterface(), $question)); $question = new ChoiceQuestion('What is your favorite superhero?', $heroes, '0,1'); $question->setMaxAttempts(1); $question->setMultiselect(true); $this->assertEquals(array('Superman', 'Batman'), $questionHelper->ask($this->createStreamableInputInterfaceMock($inputStream), $output = $this->createOutputInterface(), $question)); $this->assertOutputContains('What is your favorite superhero? [Superman, Batman]', $output); $question = new ChoiceQuestion('What is your favorite superhero?', $heroes, ' 0 , 1 '); $question->setMaxAttempts(1); $question->setMultiselect(true); $this->assertEquals(array('Superman', 'Batman'), $questionHelper->ask($this->createStreamableInputInterfaceMock($inputStream), $output = $this->createOutputInterface(), $question)); $this->assertOutputContains('What is your favorite superhero? [Superman, Batman]', $output); }
/** * {@inheritdoc} */ protected function getChoiceQuestion() { // Translate the default into an array key. $defaultKey = $this->default !== null ? array_search($this->default, $this->options, true) : $this->default; $question = new ChoiceQuestion($this->name . " (enter a number to choose): ", $this->options, $defaultKey !== false ? $defaultKey : null); $question->setMaxAttempts($this->maxAttempts); return $question; }
/** * Execute command * * @param InputInterface $input Input instance * @param OutputInterface $output Output instance * * @return int|null|void */ public function execute(InputInterface $input, OutputInterface $output) { $this->elevateProcess($input, $output); $pid = null; $grep = $input->getArgument('grep'); $command = new CommandBuilder('strace', '-f'); $command->setOutputRedirect(CommandBuilder::OUTPUT_REDIRECT_ALL_STDOUT); $output->writeln('<h2>Starting process stracing</h2>'); if (empty($pid)) { list($pidList, $processList) = $this->buildProcessList(); if ($input->getOption('all')) { $pid = 'all'; } else { try { $question = new ChoiceQuestion('Please choose process for tracing', $processList); $question->setMaxAttempts(1); $questionDialog = new QuestionHelper(); $pid = $questionDialog->ask($input, $output, $question); } catch (\InvalidArgumentException $e) { // Invalid value, just stop here throw new \CliTools\Exception\StopException(1); } } } if (!empty($pid)) { switch ($pid) { case 'all': $command->addArgumentTemplate('-p %s', implode(',', $pidList)); break; default: $command->addArgumentTemplate('-p %s', $pid); break; } // Stats if ($input->getOption('c')) { $command->addArgument('-c'); } // Relative time if ($input->getOption('r')) { $command->addArgument('-r'); } else { $command->addArgument('-tt'); } // System trace filter if ($input->getOption('e')) { $command->addArgumentTemplate('-e %s', $input->getOption('e')); } // Add grep if (!empty($grep)) { $grepCommand = new CommandBuilder('grep'); $grepCommand->addArgument('--color=auto')->addArgument($grep); $command->addPipeCommand($grepCommand); } $command->executeInteractive(); } return 0; }
/** * @param array $items An associative array of choices. * @param string $text Some text to precede the choices. * @param InputInterface $input * @param OutputInterface $output * @param mixed $default A default (as a key in $items). * * @throws \RuntimeException on failure * * @return mixed * The chosen item (as a key in $items). */ public function choose(array $items, $text = 'Enter a number to choose an item:', InputInterface $input, OutputInterface $output, $default = null) { $itemList = array_values($items); $defaultKey = $default !== null ? array_search($default, $itemList) : null; $question = new ChoiceQuestion($text, $itemList, $defaultKey); $question->setMaxAttempts(5); $choice = $this->ask($input, $output, $question); $choiceKey = array_search($choice, $items); if ($choiceKey === false) { throw new \RuntimeException("Invalid value: {$choice}"); } return $choiceKey; }
protected function execute(InputInterface $input, OutputInterface $output) { $helper = $this->getHelper('question'); $config = ['email' => null, 'password' => null, 'user.agent' => null, 'proxy.http' => null]; // E-mail question $question = new Question('eRepublik account e-mail: '); $question->setValidator(function ($answer) { if (!filter_var($answer, FILTER_VALIDATE_EMAIL)) { throw new \RuntimeException("This is not a valid e-mail address."); } return $answer; }); $question->setMaxAttempts(2); $config['email'] = $helper->ask($input, $output, $question); // Password question $question = new Question('eRepublik password: '******'password'] = $helper->ask($input, $output, $question); // User-Agent question $question = new Question('What User-Agent string to use (you can leave it empty): '); $config['user.agent'] = $helper->ask($input, $output, $question); // Type of proxy question $question = new ChoiceQuestion('What kind of proxy do you want to use: ', ['No proxy at all (default)', 'HTTP proxy']); $question->setMaxAttempts(2); $question->setErrorMessage('Proxy %s is invalid.'); $proxyType = $helper->ask($input, $output, $question); switch ($proxyType) { case 'HTTP proxy': $question = new Question('HTTP proxy (ip:port:username:password): '); $question->setValidator(function ($answer) { if (empty($answer)) { throw new \RuntimeException("Proxy cannot be empty."); } return $answer; }); $question->setMaxAttempts(2); $config['proxy.http'] = $helper->ask($input, $output, $question); break; } $configPath = $this->getApplication()->getConfigPath(); file_put_contents($configPath, json_encode($config)); $output->writeln('Config file has been written to ' . realpath($configPath)); }
/** * @param array $items An associative array of choices. * @param string $text Some text to precede the choices. * @param InputInterface $input * @param OutputInterface $output * @param mixed $default A default (as a key in $items). * * @throws \RuntimeException on failure * * @return mixed * The chosen item (as a key in $items). */ public function choose(array $items, $text = 'Enter a number to choose an item:', InputInterface $input, OutputInterface $output, $default = null) { if (count($items) === 1) { return key($items); } $itemList = array_values($items); $defaultKey = $default !== null ? array_search($default, $itemList) : null; $question = new ChoiceQuestion($text, $itemList, $defaultKey); $question->setMaxAttempts(5); // Unfortunately the default autocompletion can cause '2' to be // completed to '20', etc. $question->setAutocompleterValues(null); $choice = $this->ask($input, $output, $question); $choiceKey = array_search($choice, $items); if ($choiceKey === false) { throw new \RuntimeException("Invalid value: {$choice}"); } return $choiceKey; }
/** * @expectedException \InvalidArgumentException * @expectedExceptionMessage The provided answer is ambiguous. Value should be one of env_2 or env_3. */ public function testAmbiguousChoiceFromChoicelist() { $possibleChoices = array('env_1' => 'My first environment', 'env_2' => 'My environment', 'env_3' => 'My environment'); $dialog = new QuestionHelper(); $dialog->setInputStream($this->getInputStream("My environment\n")); $helperSet = new HelperSet(array(new FormatterHelper())); $dialog->setHelperSet($helperSet); $question = new ChoiceQuestion('Please select the environment to load', $possibleChoices); $question->setMaxAttempts(1); $dialog->ask($this->createInputInterfaceMock(), $this->createOutputInterface(), $question); }
/** * Give the user a single choice from an array of answers. * * @param string $question * @param array $choices * @param string $default * @param bool $multiple * @param mixed $attempts * @return bool */ public function choice($question, array $choices, $default = null, $attempts = null, $multiple = null) { $helper = $this->getHelperSet()->get('question'); $question = new ChoiceQuestion("<question>{$question}</question>", $choices, $default); $question->setMaxAttempts($attempts)->setMultiselect($multiple); return $helper->ask($this->input, $this->output, $question); }
/** * Give the user a single choice from an array of answers. * * @param string $question * @param array $choices * @param string $default * @param mixed $attempts * @param bool $multiple * @return bool */ public function choice($question, array $choices, $default = null, $attempts = null, $multiple = null) { $question = new ChoiceQuestion($question, $choices, $default); $question->setMaxAttempts($attempts)->setMultiselect($multiple); return $this->output->askQuestion($question); }
/** * Returns the task name from the argument list or via an interactive dialog. * * @param InputInterface $input The input context * @param OutputInterface $output The output context * * @return string|null The task name or null */ private function getTaskFromInput(InputInterface $input, OutputInterface $output) { $commands = $this->getCommands(); $task = $input->getArgument('task'); if (null !== $task) { if (!in_array($task, $commands)) { throw new \InvalidArgumentException('Invalid task "' . $task . '"'); // no full stop here } return $task; } $question = new ChoiceQuestion('Please select a task:', $commands, 0); $question->setMaxAttempts(1); /** @var QuestionHelper $helper */ $helper = $this->getHelper('question'); return $helper->ask($input, $output, $question); }
/** * Get protocol * * @return string */ protected function getProtocol() { $ret = null; if (!$this->input->getArgument('protocol')) { $protocolList = array('http' => 'HTTP (requests only)', 'http-full' => 'HTTP (full)', 'solr' => 'Solr', 'elasticsearch' => 'Elasticsearch', 'memcache' => 'Memcache', 'redis' => 'Redis', 'smtp' => 'SMTP', 'mysql' => 'MySQL queries', 'dns' => 'DNS', 'tcp' => 'TCP', 'icmp' => 'ICMP', 'arp' => 'ARP'); try { $question = new ChoiceQuestion('Please choose network protocol for sniffing', $protocolList); $question->setMaxAttempts(1); $questionDialog = new QuestionHelper(); $ret = $questionDialog->ask($this->input, $this->output, $question); } catch (\InvalidArgumentException $e) { // Invalid server context, just stop here throw new \CliTools\Exception\StopException(1); } } else { $ret = $this->input->getArgument('protocol'); } return $ret; }
/** * Get context from user */ protected function getContextFromUser() { $ret = null; if (!$this->input->getArgument('context')) { // ######################## // Ask user for server context // ######################## $serverList = $this->config->getList($this->confArea); $serverList = array_diff($serverList, array(self::GLOBAL_KEY)); if (empty($serverList)) { throw new \RuntimeException('No valid servers found in configuration'); } $serverOptionList = array(); foreach ($serverList as $context) { $line = array(); // hostname $optPath = $this->confArea . '.' . $context . '.ssh.hostname'; if ($this->config->exists($optPath)) { $line[] = '<info>host:</info>' . $this->config->get($optPath); } // rsync path $optPath = $this->confArea . '.' . $context . '.rsync.path'; if ($this->config->exists($optPath)) { $line[] = '<info>rsync:</info>' . $this->config->get($optPath); } // mysql database list $optPath = $this->confArea . '.' . $context . '.mysql.database'; if ($this->config->exists($optPath)) { $dbList = $this->config->getArray($optPath); $foreignDbList = array(); foreach ($dbList as $databaseConf) { if (strpos($databaseConf, ':') !== false) { // local and foreign database in one string $databaseConf = explode(':', $databaseConf, 2); $foreignDbList[] = $databaseConf[1]; } else { // database equal $foreignDbList[] = $databaseConf; } } if (!empty($foreignDbList)) { $line[] .= '<info>mysql:</info>' . implode(', ', $foreignDbList); } } if (!empty($line)) { $line = implode(' ', $line); } else { // fallback $line = $context; } $serverOptionList[$context] = $line; } try { $question = new ChoiceQuestion('Please choose server context for synchronization', $serverOptionList); $question->setMaxAttempts(1); $questionDialog = new QuestionHelper(); $ret = $questionDialog->ask($this->input, $this->output, $question); } catch (\InvalidArgumentException $e) { // Invalid server context, just stop here throw new \CliTools\Exception\StopException(1); } } else { $ret = $this->input->getArgument('context'); } return $ret; }