delmalki
delmalki

Reputation: 1364

Associative Array symfony2 console

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:

Upvotes: 3

Views: 1850

Answers (1)

felipsmartins
felipsmartins

Reputation: 13549

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.

Upvotes: 4

Related Questions