Define Negatable Command Options in Symfony 7

Define Negatable Command Options in Symfony 7

Symfony framework provides a way to create the console command with two related options that has opposite behaviors. This tutorial provides example how to define negatable command options in Symfony 7 application.

The VALUE_NEGATABLE input mode allows defining negatable command options. This input mode creates two options in the command using the pattern --option-name and --no-option-name.

For example, the following command has options --backup and --no-backup:

src/Command/TestCommand.php

<?php

namespace App\Command;

use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;

#[AsCommand(name: 'app:test')]
class TestCommand extends Command
{
    protected function configure(): void
    {
        $this->addOption('backup', mode: InputOption::VALUE_NEGATABLE);
    }

    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        $backup = $input->getOption('backup');
        var_dump($backup);

        return Command::SUCCESS;
    }
}

There are three possible values:

  • $debug = null if command is run as php bin/console app:test
  • $debug = true if command is run as php bin/console app:test --backup
  • $debug = false if command is run as php bin/console app:test --no-backup

Leave a Comment

Cancel reply

Your email address will not be published.