Skip to content

Add docs about console question answer normalizing. #7125

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 34 additions & 1 deletion components/console/helpers/questionhelper.rst
Original file line number Diff line number Diff line change
Expand Up @@ -209,6 +209,38 @@ convenient for passwords::
like in the example above. In this case, a ``RuntimeException``
would be thrown.

Normalizing the Answer
----------------------

Before validating the answer, you can "normalize" it to fix minor errors or
tweak it as needed. For instance, in a previous example you asked for the bundle
name. In case the user adds white spaces around the name by mistake, you can
trim the name before validating it. To do so, configure a normalizer using the
:method:`Symfony\\Component\\Console\\Question\\Question::setNormalizer`
method::

use Symfony\Component\Console\Question\Question;

// ...
public function execute(InputInterface $input, OutputInterface $output)
{
// ...
$question = new Question('Please enter the name of the bundle', 'AppBundle');
$question->setNormalizer(function ($value) {
// $value can be null here
return $value ? trim($value) : '';
});

$name = $helper->ask($input, $output, $question);
}


.. caution::

The normalizer is called first and the returned value is used as the input
of the validator. If the answer is invalid, don't throw exceptions in the
normalizer and let the validator handle those errors.

Validating the Answer
---------------------

Expand All @@ -226,11 +258,12 @@ method::
// ...
$question = new Question('Please enter the name of the bundle', 'AcmeDemoBundle');
$question->setValidator(function ($answer) {
if ('Bundle' !== substr($answer, -6)) {
if (!is_string($answer) || 'Bundle' !== substr($answer, -6)) {
throw new \RuntimeException(
'The name of the bundle should be suffixed with \'Bundle\''
);
}

return $answer;
});
$question->setMaxAttempts(2);
Expand Down