@@ -241,11 +241,12 @@ optionally accepts a value, but it's a bit tricky. Consider this example::
241
241
'Should I yell while greeting?'
242
242
);
243
243
244
- This option can be used in 3 ways: ``--yell ``, ``yell=louder ``, and not passing
245
- the option at all . However, it's hard to distinguish between passing the option
244
+ This option can be used in 3 ways: ``greet --yell ``, ``greet yell=louder ``,
245
+ and `` greet `` . However, it's hard to distinguish between passing the option
246
246
without a value (``greet --yell ``) and not passing the option (``greet ``).
247
247
248
- To solve this issue, you have to set the option's default value to ``false ``::
248
+ To solve this issue, you have to set the option's default value to
249
+ ``false ``::
249
250
250
251
// ...
251
252
use Symfony\Component\Console\Input\InputOption;
@@ -260,7 +261,32 @@ To solve this issue, you have to set the option's default value to ``false``::
260
261
false // this is the new default value, instead of null
261
262
);
262
263
263
- Now check the value of the option and keep in mind that ``false !== null ``::
264
+ The input will now return the default value for the option when it is not
265
+ specified (``greet ``), a null value when it is specified but not explicitly
266
+ defined (``greet --yell ``), and the defined value when defined
267
+ (``greet --yell=lounder ``). Now check the value of the option::
268
+
269
+ $optionValue = $input->getOption('yell');
270
+ if ($optionValue === false ) {
271
+ // option was not specified
272
+ $yell = false;
273
+ $yellLouder = false;
274
+ } elseif ($optionValue === null) {
275
+ // option was specified but no value given
276
+ $yell = true;
277
+ $yellLouder = false;
278
+ } else {
279
+ // option was specified with a value which is now stored in $optionValue
280
+ $yell = true;
281
+ if ($optionValue === 'louder') {
282
+ $yellLouder = true;
283
+ } else {
284
+ $yellLouder = false;
285
+ }
286
+ }
287
+
288
+ Once you are clear on how the default value is implemented you could consense the
289
+ above code into less lines of code since ``false !== null ``::
264
290
265
291
$optionValue = $input->getOption('yell');
266
292
$yell = ($optionValue !== false);
0 commit comments