PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, February 20, 2022

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

 February 20, 2022     php, symfony, symfony-console     No comments   

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:

  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;


Answered By - ScorpioT1000
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing