3

given this configuration command:

protected function configure() {
    $this->setName('command:test')
         ->addOption("service", null, InputOption::VALUE_IS_ARRAY | InputOption::VALUE_OPTIONAL, "What services are desired ?", array(
             "s1" => true,
             "s2" => true,
             "s3" => true,
             "s4" => false,
             "s5" => true,
             "s6" => true,
             "s7" => true,
             "s8" => true,
             "s9" => true
         ))
}

Now when calling the command, how do you pass the associate array.

#!/bin/bash
php app/console command:test --service s1:true --service s2:false --s3:true

Condition:

  • I dont want to create 9+ options for this command.
  • Ideally, I would like to preserve the defaults when I pass a new service.
  • All, within the command definition if that's possible. That is no supporting code. No if

1 Answer 1

4

As far I know it's not possible when using Command Options (at least not like you've described...).

The best workaround (IMO) is using Command Arguments (instead of Command Options) and writing extra code (not, it is not nice to put all of extra code inside command definition although is possible).

It would be something like this:

class TestCommand extends ContainerAwareCommand
{
    protected function getDefaultServicesSettings()
    {
        return [
            's1' => true,
            's2' => true,
            's3' => true,
            's4' => false,
            's5' => true,
            's6' => true,
            's7' => true,
            's8' => true,
            's9' => true
        ];
    }

    private function normalizeServicesValues($values)
    {
        if (!$values) {
            return $this->getDefaultServicesSettings();
        }

        $new = [];

        foreach ($values as $item) {
            list($service, $value) = explode(':', $item);
            $new[$service] = $value == 'true' ? true : false;
        }
        return array_merge($this->getDefaultServicesSettings(), $new);
    }

    protected function configure()
    {
        $this
            ->setName('commant:test')
            ->addArgument(
                'services',
                InputArgument::IS_ARRAY|InputArgument::OPTIONAL,
                'What services are desired ?');
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {

        $services = $this->normalizeServicesValues(
            $input->getArgument('services'));
        // ...
    }
}

Then

$ bin/console commant:test s1:false s9:false

That overwrites s1 and s2 values while keeping defaults.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.