Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Associative Array symfony2 console

Tags:

php

symfony

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
like image 515
delmalki Avatar asked Sep 10 '26 17:09

delmalki


1 Answers

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.

like image 54
felipsmartins Avatar answered Sep 12 '26 06:09

felipsmartins



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!