Tejas Gosai
Tejas Gosai

Reputation: 362

Symfony 2 : validate console command arguments

I am creating a command to generate accounts from a file. In command I have passed some arguments.

   $this
  ->setName('batch:create')
  ->setDescription('xyz')
  ->setHelp('xyz')
  ->addArgument('account-id', InputArgument::REQUIRED, "Set the account id.")
  ->addArgument('name', InputArgument::REQUIRED, "Set the account name.");

I was just thinking if there is any way I can check type of argument passed. For now I am checking it like this,

   if (is_numeric($input->getArgument('account-id'))) {
    // ....
   }

Is there anyway I can create a validator that checks the type and I just have to call validate function.

   if ($input->validate() === false) {
     // show error message and return.
   }

Upvotes: 8

Views: 8810

Answers (1)

kix
kix

Reputation: 3319

Unfortunately, currently there's no way to implement command argument validation in Symfony. The best way to implement these checks would be overriding Symfony\Component\Console\Command::initialize method in your command and then applying the validation rules there, throwing exceptions if passed arguments are invalid.

Update: Matthias Noback has implemented symfony-console-form (https://github.com/matthiasnoback/symfony-console-form), and looks like implementing Matthias\SymfonyConsoleForm\Console\Command\FormBasedCommand interface would give you basic validation abilities through the form component (have to test it with validation, though).

Upvotes: 16

Related Questions