Skip to content

Commit 5f81796

Browse files
SpacePossumxabbuh
authored andcommitted
Add docs about console question answer normalizing.
1 parent c698051 commit 5f81796

File tree

1 file changed

+37
-1
lines changed

1 file changed

+37
-1
lines changed

components/console/helpers/questionhelper.rst

+37-1
Original file line numberDiff line numberDiff line change
@@ -209,6 +209,41 @@ convenient for passwords::
209209
like in the example above. In this case, a ``RuntimeException``
210210
would be thrown.
211211

212+
Normalizing the Answer
213+
---------------------
214+
215+
You can normalize the answer. For instance, in a previous example you asked for
216+
the bundle name. If the user accidentally adds spaces before and/or after the name we
217+
want to remove this from the answer. You can set the normalizer using
218+
:method:`Symfony\\Component\\Console\\Question\\Question::setNormalizer`
219+
method::
220+
221+
use Symfony\Component\Console\Question\Question;
222+
223+
// ...
224+
public function execute(InputInterface $input, OutputInterface $output)
225+
{
226+
// ...
227+
$question = new Question('Please enter the name of the bundle', 'AcmeDemoBundle');
228+
$question->setNormalizer(function ($answer) {
229+
if (!is_string($value)) { // $value can be null here
230+
return $value;
231+
}
232+
233+
return trim($value);
234+
});
235+
236+
$name = $helper->ask($input, $output, $question);
237+
}
238+
239+
240+
.. caution::
241+
242+
The normalizer is called before the validator and the returned value by the
243+
normalizer is used as input for the validator (and not the original answer
244+
of the user). The normalizer should not throw an exception if the answer is invalid;
245+
for validation use a validator.
246+
212247
Validating the Answer
213248
---------------------
214249

@@ -226,11 +261,12 @@ method::
226261
// ...
227262
$question = new Question('Please enter the name of the bundle', 'AcmeDemoBundle');
228263
$question->setValidator(function ($answer) {
229-
if ('Bundle' !== substr($answer, -6)) {
264+
if (!is_string($answer) || 'Bundle' !== substr($answer, -6)) {
230265
throw new \RuntimeException(
231266
'The name of the bundle should be suffixed with \'Bundle\''
232267
);
233268
}
269+
234270
return $answer;
235271
});
236272
$question->setMaxAttempts(2);

0 commit comments

Comments
 (0)