Skip to content
Advertisement

How to identify if an option was supplied without a value with Symfony Console?

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 SymfonyComponentConsoleCommandCommand
{
    // ...

    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?

Advertisement

Answer

Since Symfony 3.4, you can just set the default to false and check:

  1. if the value is false the option doesn’t exist
  2. if the value is null the option exists without a value
  3. otherwise it has its value

e.g.

$this->addOption('force', null, InputOption::VALUE_OPTIONAL, 'Force something', false);

$force = $input->getOption('force') !== false;
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement