Issue
With the Symfony3 Console, how can I tell when a user supplied an option, but supplied it without a value? As opposed to not supplying the option at all?
As an example, take the following console configuration.
<?php
class MyCommand extends \Symfony\Component\Console\Command\Command
{
// ...
protected function configure()
{
$this->setName('test')
->setDescription('update an existing operation.')
->addOption(
'option',
null,
InputOption::VALUE_OPTIONAL,
'The ID of the operation to update.'
);
}
}
The command help will illustrate the option as --option[=OPTION]
, so I can call this the following ways.
bin/console test
bin/console test --option
bin/console test --option=foo
However, $input->getOption()
will return NULL
in the first two cases. I expected in the second case that it would return TRUE
, or something to indicate the option was supplied.
So I don't know how to identify the difference the option not being supplied at all, and it being supplied but without a value.
If there is no way to tell the difference, what is the use-case for InputOption::VALUE_OPTIONAL
?
Solution
Since Symfony 3.4, you can just set the default to false
and check:
- if the value is
false
the option doesn't exist - if the value is
null
the option exists without a value - otherwise it has its value
e.g.
$this->addOption('force', null, InputOption::VALUE_OPTIONAL, 'Force something', false);
$force = $input->getOption('force') !== false;
Answered By - ScorpioT1000
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.