Search code examples
symfonysymfony-console

I got an error on symfony/console -- "Option does not exits". How can I allow any options even without setting it out?


Is it possible in symfony/console to allow all options or argument even if it didn't set on config?

You see, based from the following example. It has ->addArgument() and ->addOption(), it sets name and yell param and option respectively.

http://symfony.com/doc/current/components/console/introduction.html

class GreetCommand extends Command
{

    protected function configure()
    {
        $this
            ->setName('demo:greet')
            ->setDescription('Greet someone')
            ->addArgument(
                'name',
                InputArgument::OPTIONAL,
                'Who do you want to greet?'
            )
            ->addOption(
               'yell',
               null,
               InputOption::VALUE_NONE,
               'If set, the task will yell in uppercase letters'
            )
        ;
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $name = $input->getArgument('name');
        if ($name) {
            $text = 'Hello '.$name;
        } else {
            $text = 'Hello';
        }

        if ($input->getOption('yell')) {
            $text = strtoupper($text);
        }

        $output->writeln($text);
    }
}

Is it possible to run the following command without setting arguments and options?

$ php application.php demo:greet Fabien John Doe --yell --greet --poke

Solution

  • Well, without refactoring base Command class you can't, and for good reason - all options should be validated by system and accepted. For remote CRON task, for example.

    However, you can make it like this:

    ->addOption(
        'parameters',
        InputOption::IS_ARRAY,
        'Enter parameters'
    );
    

    This way you can treat single parameter as an array, and take validation responsibility on your own, by accessing it:

    if ($names = $input->getOption('parameters')) {
        $text .= ' '.implode(', ', $parameters);
    }
    

    More info here.

    Cheers!