Skip to content

[RFC][Console] Ability to check if VALUE_OPTIONAL option was provided #43703

Closed
@colinodell

Description

@colinodell

Description

Given a command option defined like this:

$this->addOption('save', 's', InputOption::VALUE_OPTIONAL, 'A file to save the results to', 'default.csv');

I would like to support three different behaviors in my application:

  1. If --save is omitted, my command will write the results to stdout
  2. If --save is provided (without any value), I would like it to default to the given default value of default.csv
  3. If --save=elsewhere.csv is provided, I would like to obtain that user-defined value of elsewhere.csv

Symfony does not seem to currently support this because:

  • Input::getOption() always returns the default value in scenarios 1 and 2 above
  • Input::getOptions() does the same
  • Input::hasOption() returns whether the option was defined by the command, not whether the command received the option
  • Input::$options has the information I need but it's not public

In other words, it's currently impossible to differentiate between scenarios 1 and 2.

Example

My ideal solution would be one where I can simply call getOption('save') and get some indication that the user did not specify the option at all, similar to how VALUE_NONE works. Perhaps it could return null in that case?

To avoid breaking BC, perhaps we'd also need a new flag like InputOption::VALUE_NULL_IF_OMITTED that can be ORed with VALUE_OPTIONAL to enable this behavior?

I'm definitely open to other ideas too.

Workarounds

Some workarounds do exist for this, but none of them seem ideal for my requirements:

  1. Extend the Input class to add this functionality myself
  2. Use two different options instead of one; add manual validation to ensure the user didn't provide both
  3. Follow the Unix Way and always output to stdout; let the user pipe that into a file if they really want to (doesn't meet my requirements)

But perhaps Symfony does support what I'm looking for and I'm just missing it?

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions