Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.
   }
like image 412
Tejas Gosai Avatar asked Nov 17 '14 10:11

Tejas Gosai


1 Answers

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).

like image 184
kix Avatar answered Oct 15 '22 04:10

kix