Skip to content

Instantly share code, notes, and snippets.

@geekish
Created December 8, 2016 00:59
Show Gist options
  • Save geekish/569961ccf2318240d450f9aeca0ed8b4 to your computer and use it in GitHub Desktop.
Save geekish/569961ccf2318240d450f9aeca0ed8b4 to your computer and use it in GitHub Desktop.
Symfony Console interactive did you mean
[Symfony\Component\Console\Exception\CommandNotFoundException]  
  Command "mow" is not defined.                                   
  Did you mean this?                                              
      meow                  

That's a nice error message, but we can do better. This is an example.

Run composer install, then php console.php mow. Should give you:

That command doesn't exist, did you mean:
  [0] meow

Hit 0 or type meow and it will actually run the command you meant to run in the first place.

{
"require": {
"symfony/console": "^3.2"
}
}
<?php
use Symfony\Component\Console\Application;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Exception\CommandNotFoundException;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Question\ChoiceQuestion;
use Symfony\Component\Console\Output\OutputInterface;
require __DIR__ . "/vendor/autoload.php";
$name = "Example";
$version = "v1.0";
$app = new class($name, $version) extends Application {
public function doRun(InputInterface $input, OutputInterface $output)
{
$this->setCatchExceptions(false);
try {
return parent::doRun($input, $output);
} catch (CommandNotFoundException $e) {
$helper = $this->getHelperSet()->get('question');
$question = new ChoiceQuestion(
"That command doesn't exist, did you mean:",
$e->getAlternatives(),
0
);
$question->setErrorMessage('Try again.');
$name = $helper->ask($input, $output, $question);
$command = $this->find($name);
$this->runningCommand = $command;
$exitCode = $this->doRunCommand($command, $input, $output);
$this->runningCommand = null;
return $exitCode;
}
return 0;
}
};
$command = new class extends Command {
public function configure()
{
$this->setName("meow");
$this->setDescription("Meow");
}
public function execute(InputInterface $input, OutputInterface $output)
{
$output->writeln("MEOW");
return 0;
}
};
$app->add($command);
$app->run();
@geekish
Copy link
Author

geekish commented Dec 8, 2016

Oh hey, there's a pull request for basically the same thing: symfony/symfony#19282

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment