@@ -209,6 +209,41 @@ convenient for passwords::
209
209
like in the example above. In this case, a ``RuntimeException ``
210
210
would be thrown.
211
211
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
+
212
247
Validating the Answer
213
248
---------------------
214
249
@@ -226,11 +261,12 @@ method::
226
261
// ...
227
262
$question = new Question('Please enter the name of the bundle', 'AcmeDemoBundle');
228
263
$question->setValidator(function ($answer) {
229
- if ('Bundle' !== substr($answer, -6)) {
264
+ if (!is_string($answer) || 'Bundle' !== substr($answer, -6)) {
230
265
throw new \RuntimeException(
231
266
'The name of the bundle should be suffixed with \'Bundle\''
232
267
);
233
268
}
269
+
234
270
return $answer;
235
271
});
236
272
$question->setMaxAttempts(2);
0 commit comments