8000 Update Console Input Optional Options by Matt-PMCT · Pull Request #12951 · symfony/symfony-docs · GitHub
[go: up one dir, main page]

Skip to content

Update Console Input Optional Options #12951

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

Merged
merged 1 commit into from
Apr 3, 2020
Merged
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
34 changes: 30 additions & 4 deletions console/input.rst
Original file line number Diff line number Diff line change
Expand Up @@ -247,11 +247,12 @@ optionally accepts a value, but it's a bit tricky. Consider this example::
)
;

This option can be used in 3 ways: ``--yell``, ``yell=louder``, and not passing
the option at all. However, it's hard to distinguish between passing the option
This option can be used in 3 ways: ``greet --yell``, ``greet yell=louder``,
and ``greet``. However, it's hard to distinguish between passing the option
without a value (``greet --yell``) and not passing the option (``greet``).

To solve this issue, you have to set the option's default value to ``false``::
To solve this issue, you have to set the option's default value to
``false``::

// ...
use Symfony\Component\Console\Input\InputOption;
Expand All @@ -267,7 +268,32 @@ To solve this issue, you have to set the option's default value to ``false``::
)
;

Now check the value of the option and keep in mind that ``false !== null``::
The input will now return the default value for the option when it is not
specified (``greet``), a null value when it is specified but not explicitly
defined (``greet --yell``), and the defined value when defined
(``greet --yell=lounder``). Now check the value of the option::

$optionValue = $input->getOption('yell');
if ($optionValue === false ) {
// option was not specified
$yell = false;
$yellLouder = false;
} elseif ($optionValue === null) {
// option was specified but no value given
$yell = true;
$yellLouder = false;
} else {
// option was specified with a value which is now stored in $optionValue
$yell = true;
if ($optionValue === 'louder') {
$yellLouder = true;
} else {
$yellLouder = false;
}
}

Once you are clear on how the default value is implemented you could consense the
above code into less lines of code since ``false !== null``::

$optionValue = $input->getOption('yell');
$yell = ($optionValue !== false);
Expand Down
0