The validator receives the data to validate. It must return the
validated data when the data is valid and throw an exception
otherwise.
public askAndValidate ( Symfony\Component\Console\Output\OutputInterface $output, string | array $question, callback $validator, integer $attempts = false, string $default = null ) : mixed | ||
$output | Symfony\Component\Console\Output\OutputInterface | |
$question | string | array | |
$validator | callback | A PHP callback |
$attempts | integer | Max number of times to ask before giving up (false by default, which means infinite) |
$default | string | The default answer if none is given by the user |
return | mixed |
public function ask($question, $regex, $errorText = null, $default = null) { if ($default) { $question = "{$question} [{$default}]"; } return $this->dialog->askAndValidate($this->output, "<question>{$question}</question> ", $this->validateWith($regex, $errorText), false, $default); }
/** * Asks user what the path to javascript source is. */ public function configure() { if (!$this->settings['enableJsHint']) { return; } $baseDir = $this->settings->getBaseDir(); $default = $this->settings->getDefaultValueFor('javaScriptSrcPath', 'src'); $this->settings['javaScriptSrcPath'] = $this->dialog->askAndValidate($this->output, "What is the path to the JavaScript source code? [{$default}] ", function ($data) use($baseDir) { if (is_dir($baseDir . '/' . $data)) { return $data; } throw new \Exception("That path doesn't exist"); }, false, $default); }
/** * Asks in the commandline if the user want to enable the codesniffer for the given project * */ protected function askEnable() { $default = $this->settings->getDefaultValueFor('enablePhpCodeSniffer', true); $this->settings['enablePhpCodeSniffer'] = $this->dialog->askConfirmation($this->output, "Do you want to enable the PHP Code Sniffer?", $default); if (!$this->settings['enablePhpCodeSniffer']) { return; } $default = $this->settings->getDefaultValueFor('phpCodeSnifferCodingStyle', 'PSR2'); $this->settings['phpCodeSnifferCodingStyle'] = $this->dialog->askAndValidate($this->output, " - Which coding standard do you want to use? (PEAR, PHPCS, PSR1, PSR2, Squiz, Zend) [{$default}] ", function ($data) { if (in_array($data, array("PEAR", "PHPCS", "PSR1", "PSR2", "Squiz", "Zend"))) { return $data; } throw new \Exception("That coding style is not supported"); }, false, $default); }
/** * @param InputInterface $input * @param OutputInterface $output * @return int */ protected final function execute(InputInterface $input, OutputInterface $output) { /* @var FormatterHelper $formatterHelper */ $formatterHelper = $this->getHelperSet()->get('formatter'); $that = $this; // Main exception catching to allow quiting command try { while (true) { // sub exception catching to display error without giving up context changes try { // Do not display available commands $commandToExecute = $this->dialog->askAndValidate($output, 'loop > ', function ($answer) use($that) { // command accepts arguments, lets explode it and keep the trailing args in a simple string $allArgs = explode(' ', $answer, 2); if (empty($allArgs[0])) { return array(); } elseif (array_key_exists($allArgs[0], $this->commands)) { $command = array_shift($allArgs); $arguments = !empty($allArgs) ? $allArgs[0] : null; // check if args are required, optional, or shouldn't exist if (empty($arguments) && $this->commands[$command]['mode'] == self::COMMAND_VALUE_REQUIRED) { throw new \RuntimeException('The command "' . $command . '" needs one or many arguments, nothing given.'); } elseif (!empty($arguments) && $this->commands[$command]['mode'] == self::COMMAND_VALUE_NONE) { throw new \RuntimeException('The command "' . $command . '" doesn\'t accept arguments, "' . $arguments . '" given.'); } return array('command' => $command, 'arguments' => $arguments); } else { throw new \RuntimeException('Unknown command'); } }, false, null, array_keys($that->commands)); if (!empty($commandToExecute)) { call_user_func_array($this->commands[$commandToExecute['command']]['callable'], array($input, $output, $this->dialog, $this->context, $commandToExecute['arguments'])); } } catch (LoopCommandFinishedException $lcfe) { throw $lcfe; } catch (\Exception $e) { $output->writeln($formatterHelper->formatBlock('Exception ' . get_class($e) . ': ' . $e->getMessage(), 'error', true)); } } } catch (LoopCommandFinishedException $lcfe) { // Nothing to do but return with a message $output->writeln('<comment>Bye</comment>'); return 0; } // we shouldn't be able to get there return 10; }
/** * Ask Base url for an different environment environment * * @param OutputInterface $output * @param string $environment */ protected function askBaseDifferentEnvironment(OutputInterface $output, $environment) { $default = $this->settings->getDefaultValueFor('baseUrl' . $environment, $this->suggestDomain($this->settings['baseUrl'], strtolower($environment))); $this->settings['baseUrl' . $environment] = $this->dialog->askAndValidate($output, "What is base url of the " . strtolower($environment) . " environment? [{$default}] ", function ($data) { if (substr($data, 0, 4) == 'http') { return $data; } throw new \Exception("Url needs to start with http"); }, false, $default); }
/** * Ask and validate operation by typing MASTER release_code */ protected function confirmOperation() { $that = $this; $bundle = $this->dialog->askAndValidate($this->output, "\nConfirm operation by typing MASTER release code: ", function ($answer) use($that) { if ($that->master_branch !== trim($answer)) { throw new \RunTimeException("Wrong release code: {$answer}"); } return $answer; }); }
/** * @param OutputInterface $output * @param DialogHelper $dialog * @return array */ public function getValues(OutputInterface $output, DialogHelper $dialog) { $defaults = $this->getDefaults(); $value = $dialog->askAndValidate($output, "<info>PHP Namespace</info> ({$defaults[0]}): ", function ($namespace) { if (preg_match("/^([\\w\\\\]+)*\\w+\$/", $namespace)) { return $namespace; } throw new RuntimeException(sprintf('%s is not a valid namespace', $namespace)); }, false, reset($defaults), $defaults); return ['php_namespace' => $value, 'php_namespace_escaped' => addslashes($value)]; }
/** * @param OutputInterface $output * @param DialogHelper $dialog * @return array */ public function getValues(OutputInterface $output, DialogHelper $dialog) { $default = $this->getDefault(); $value = $dialog->askAndValidate($output, "<info>Issues url</info> ({$default}): ", function ($email) { if (false === filter_var($email, FILTER_VALIDATE_URL)) { throw new RuntimeException('Not a valid url'); } return $email; }, false, $default); return ['bugs' => $value]; }
protected function configureProjectName(InputInterface $input, OutputInterface $output) { $dirName = basename($this->settings->getBaseDir()); $guessedName = $this->guessName($dirName); $default = empty($this->settings['projectName']) ? $guessedName : $this->settings['projectName']; $this->settings['projectName'] = $this->dialog->askAndValidate($output, "What is the name of the project? [{$default}] ", function ($data) { if (preg_match('/^[\\w\\.\\s]+$/', $data)) { return $data; } throw new \Exception("The project name may only contain 'a-zA-Z0-9_. '"); }, false, $default); }
/** * @return string */ private function askSlackToken() { $question = "Please paste your slack credentials \n" . " (see http://docs.travis-ci.com/user/notifications/#Slack-notifications): \n"; // very basic validation $validator = function ($token) { // we must have a string, that contains a : not at the starting position // token format is username:hashedtoken if (is_string($token) && strpos($token, ':')) { return $token; } throw new \Exception("Please enter a valid token"); }; return $this->dialog->askAndValidate($this->output, $question, $validator, false, $this->settings->getDefaultValueFor('travis.slack.token', null)); }
public function testAskAndValidate() { $dialog = new DialogHelper(); $helperSet = new HelperSet(array(new FormatterHelper())); $dialog->setHelperSet($helperSet); $question = 'What color was the white horse of Henry IV?'; $error = 'This is not a color!'; $validator = function ($color) use($error) { if (!in_array($color, array('white', 'black'))) { throw new \InvalidArgumentException($error); } return $color; }; $dialog->setInputStream($this->getInputStream("\nblack\n")); $this->assertEquals('white', $dialog->askAndValidate($this->getOutputStream(), $question, $validator, 2, 'white')); $this->assertEquals('black', $dialog->askAndValidate($this->getOutputStream(), $question, $validator, 2, 'white')); $dialog->setInputStream($this->getInputStream("green\nyellow\norange\n")); try { $this->assertEquals('white', $dialog->askAndValidate($this->getOutputStream(), $question, $validator, 2, 'white')); $this->fail(); } catch (\InvalidArgumentException $e) { $this->assertEquals($error, $e->getMessage()); } }
/** * @param OutputInterface $output * @param Settings $settings * @return bool */ protected function enablePhpUnitAutoLoad(OutputInterface $output, Settings $settings) { $default = $this->settings->getDefaultValueFor('enablePhpUnitAutoload', true); $settings['enablePhpUnitAutoload'] = $this->dialog->askConfirmation($output, "Do you want to enable an autoload script for PHPUnit?", $default); if (false === $settings['enablePhpUnitAutoload']) { return false; } if ($settings['enablePhpUnitAutoload']) { $default = $this->settings->getDefaultValueFor('phpUnitAutoloadPath', 'vendor/autoload.php'); $settings['phpUnitAutoloadPath'] = $this->dialog->askAndValidate($output, "What is the path to the autoload script for PHPUnit? [{$default}] ", function ($data) use($settings) { if (file_exists($settings->getBaseDir() . '/' . $data)) { return $data; } throw new \Exception("That path doesn't exist"); }, false, $default); } return true; }
/** * Ask the user for one or more paths/patterns * * @param string $pathQuestion * @param string $defaultPaths * @param null $confirmationQuestion Optional question to ask if you want to set the value * @param bool $defaultConfirmation * @param callable $callback * * @throws \Exception when callable is not callable. * * @return string */ protected function ask($pathQuestion, $defaultPaths, $confirmationQuestion, $defaultConfirmation, $callback) { /** * Type hinting with callable (@see http://www.php.net/manual/en/language.types.callable.php) * is only from PHP5.4+ and therefore we check with is_callable() */ if (!is_callable($callback)) { throw new \Exception('Error calling callable'); } if ($defaultPaths) { $pathQuestion .= ' [' . (is_array($defaultPaths) ? implode(',', $defaultPaths) : $defaultPaths) . ']'; } if ($confirmationQuestion) { if (!$this->dialog->askConfirmation($this->output, $confirmationQuestion, $defaultConfirmation)) { return array(); } } return $this->dialog->askAndValidate($this->output, $pathQuestion . " (comma separated)\n", $callback, false, $defaultPaths); }
public function askQuestion(InteractiveQuestion $question, $position = null, InputInterface $input = null) { $text = ($position !== null ? $position . ') ' : null) . $question->getFormatedText(); if ($this->dialogHelper instanceof QuestionHelper) { if (!$input) { throw new \InvalidArgumentException('With symfony 3, the input stream may not be null'); } $q = new Question($text, $question->getDefault()); $q->setValidator($question->getValidator()); if ($question->isHiddenAnswer()) { $q->setHidden(true); } return $this->dialogHelper->ask($input, $this, $q); } if ($this->dialogHelper instanceof DialogHelper) { if ($question->isHiddenAnswer()) { return $this->dialogHelper->askHiddenResponseAndValidate($this, $text, $question->getValidator(), false); } return $this->dialogHelper->askAndValidate($this, $text, $question->getValidator(), false, $question->getDefault()); } throw new \RuntimeException("Invalid dialogHelper"); }
protected function setParams() { $this->scroll_time = $this->dialog->askAndValidate($this->output, "Select scroll time, ie 10m: ", function ($answer) { if (!preg_match('/\\d+(s|m|h|d|w|M|y)/', trim($answer))) { throw new \RunTimeException("Wrong scroll time format, ie '10m': {$answer}"); } return $answer; }); $this->scroll_size = $this->dialog->askAndValidate($this->output, "Select scroll size, ie 100: ", function ($answer) { if (!preg_match('/\\d+/', trim($answer))) { throw new \RunTimeException("Wrong scroll size format, ie '100': {$answer}"); } return $answer; }); $this->from_index = $this->dialog->askAndValidate($this->output, "Index to index from: ", function ($answer) { if (!trim($answer)) { throw new \RunTimeException("You have to select an index name."); } return $answer; }); $this->to_index = $this->dialog->askAndValidate($this->output, "Index to index to: ", function ($answer) { if (!trim($answer)) { throw new \RunTimeException("You have to select an index name."); } return $answer; }); $this->types_to_index = $this->input->getArgument('types_to_index'); if (!$this->types_to_index) { $this->out($this->output, '<fg=red;bg=black>No mapping selected, please select a mapping to index.</fg=red;bg=black>'); $this->types_to_index[] = $this->dialog->askAndValidate($this->output, "Mapping to index: ", function ($answer) { if (!trim($answer)) { throw new \RunTimeException("You have to select a mapping"); } return $answer; }); } }
/** * @return string */ private function askArtifactWritePath() { $default = $this->settings->getDefaultValueFor('buildArtifacts.path', self::DEFAULT_ARTIFACT_PATH); return $this->dialog->askAndValidate($this->output, sprintf('Where do you want to store the build artifacts? [%s] ', $default), array($this, 'validateArtifactWritePath'), false, $default); }
/** * @param OutputInterface $output * @param DialogHelper $dialog */ protected function createAdminUser(OutputInterface $output, DialogHelper $dialog) { // Try to create a user account: $adminEmail = $dialog->askAndValidate($output, 'Your email address: ', function ($answer) { if (!filter_var($answer, FILTER_VALIDATE_EMAIL)) { throw new Exception('Must be a valid email address.'); } return $answer; }, false); $adminPass = $dialog->askHiddenResponse($output, 'Enter your desired admin password: '******'Enter your name: '); try { $user = new User(); $user->setEmail($adminEmail); $user->setName($adminName); $user->setIsAdmin(1); $user->setHash(password_hash($adminPass, PASSWORD_DEFAULT)); $this->reloadConfig(); $store = Factory::getStore('User'); $store->save($user); $output->writeln('<info>User account created!</info>'); } catch (\Exception $ex) { $output->writeln('<error>PHPCI failed to create your admin account.</error>'); $output->writeln('<error>' . $ex->getMessage() . '</error>'); die; } }
protected function askFile(DialogHelper $dialog, OutputInterface $output, $title, $required) { $result = $dialog->askAndValidate($output, "{$title} [empty for none]: ", function ($answer) use($required) { if (!$required && !$answer) { return null; } if (!is_file($answer)) { throw new \RuntimeException('Specified file not found'); } return $answer; }); return $result; }
/** * @param DialogHelper $dialog * @param OutputInterface $output * @return BundleInterface */ protected function pickBundle(DialogHelper $dialog, OutputInterface $output) { $output->writeln(""); $arr = $this->getContainer()->get('kernel')->getBundles(); /** @var BundleInterface[] $arrBundles */ $arrBundles = array(); foreach ($arr as $bundle) { if (strpos($bundle->getNamespace(), 'Symfony') === 0 || strpos($bundle->getNamespace(), 'Sensio') === 0 || strpos($bundle->getNamespace(), 'Doctrine') === 0) { continue; } if (strpos($bundle->getPath(), '/vendor/') > 0 || strpos($bundle->getPath(), '\\vendor\\') > 0) { continue; } $arrBundles[] = $bundle; } foreach ($arrBundles as $k => $bundle) { $output->writeln(sprintf(" %s - %s", str_pad($k, 3, ' '), $bundle->getNamespace())); } $output->writeln(''); $max = count($arrBundles) - 1; $k = $dialog->askAndValidate($output, "In which bundle you wish to generate new model? [0 - {$max}] : ", function ($a) use($max) { if (trim($a) == '') { throw new \InvalidArgumentException('You must pick a bundle'); } $b = intval($a); if ($b < 0 || $b > $max) { throw new \InvalidArgumentException(sprintf('Enter a number between 1 and %s', $max)); } return $b; }); return $arrBundles[$k]; }
/** * @param string $question * @param callable $validator * @param int|false $attempts * @param string|null $default * * @return string */ public function askAndValidate($question, $validator, $attempts = false, $default = null) { return $this->dialogHelper->askAndValidate($this->output, $question, $validator, $attempts, $default); }
/** * Gets the extension path. * @param DialogHelper $dialogHelper * @param OutputInterface $output * @return string */ private function getExtensionPath(DialogHelper $dialogHelper, OutputInterface $output) { return $dialogHelper->askAndValidate($output, $this->createQuestion('Enter your package name'), function ($answer) { if (is_dir(\WFP2Environment::getExtPath() . $answer)) { throw new \RuntimeException('Extension ' . $answer . ' already exists'); } return \WFP2Environment::getExtPath() . $answer; }); }
/** * @param \Symfony\Component\Console\Input\InputInterface $input * @param \Symfony\Component\Console\Output\OutputInterface $output * @return bool|void */ protected function execute(InputInterface $input, OutputInterface $output) { $this->detectMagento($output, true); if ($this->initMagento()) { $this->input = $input; $this->output = $output; /** @var DialogHelper dialog */ $this->dialog = $this->getHelperSet()->get('dialog'); // Defaults $range = $all = false; $id = $this->input->getArgument('id'); $range = $this->input->getOption('range'); $all = $this->input->getOption('all'); // Get args required if (!$id && !$range && !$all) { // Delete more than one customer ? $batchDelete = $this->dialog->askConfirmation($this->output, $this->getQuestion('Delete more than 1 customer?', 'n'), false); if ($batchDelete) { // Batch deletion $all = $this->dialog->askConfirmation($this->output, $this->getQuestion('Delete all customers?', 'n'), false); if (!$all) { $range = $this->dialog->askConfirmation($this->output, $this->getQuestion('Delete a range of customers?', 'n'), false); if (!$range) { // Nothing to do $this->output->writeln('<error>Finished nothing to do</error>'); return false; } } } } if (!$range && !$all) { // Single customer deletion if (!$id) { $id = $this->dialog->ask($this->output, $this->getQuestion('Customer Id'), null); } try { $customer = $this->getCustomer($id); } catch (\Exception $e) { $this->output->writeln('<error>No customer found!</error>'); return false; } if ($this->shouldRemove()) { $this->deleteCustomer($customer); } else { $this->output->writeln('<error>Aborting delete</error>'); } } else { $customers = $this->getCustomerCollection(); $customers->addAttributeToSelect('firstname')->addAttributeToSelect('lastname')->addAttributeToSelect('email'); if ($range) { // Get Range $ranges = array(); $ranges[0] = $this->dialog->askAndValidate($this->output, $this->getQuestion('Range start Id', '1'), array($this, 'validateInt'), false, '1'); $ranges[1] = $this->dialog->askAndValidate($this->output, $this->getQuestion('Range end Id', '1'), array($this, 'validateInt'), false, '1'); // Ensure ascending order sort($ranges); // Range delete, takes precedence over --all $customers->addAttributeToFilter('entity_id', array('from' => $ranges[0], 'to' => $ranges[1])); } if ($this->shouldRemove()) { $count = $this->batchDelete($customers); $this->output->writeln('<info>Successfully deleted ' . $count . ' customer/s</info>'); } else { $this->output->writeln('<error>Aborting delete</error>'); } } } }