Skip to content

Commit 56c7294

Browse files
When an unknown option is used, display a helpful message rather than the entire command help message
1 parent 822c923 commit 56c7294

File tree

2 files changed

+30
-2
lines changed

2 files changed

+30
-2
lines changed

src/Console/ConsoleOptionParser.php

Lines changed: 30 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -818,6 +818,35 @@ public function getCommandError($command)
818818
return implode("\n", $out);
819819
}
820820

821+
/**
822+
* Get the message output in the console stating that the option can not be found and tries to guess what the user
823+
* wanted to say. Output a list of available options as well.
824+
*
825+
* @param string $option Unknown option name trying to be used.
826+
* @return string The message to be displayed in the console.
827+
*/
828+
public function getOptionError($option)
829+
{
830+
$availableOptions = array_keys($this->_options);
831+
$bestGuess = $this->findClosestItem($option, $availableOptions);
832+
$out = [];
833+
$out[] = sprintf('Unknown option `%s`.', $option);
834+
$out[] = '';
835+
836+
if ($bestGuess !== null) {
837+
$out[] = sprintf('Did you mean `%s` ?', $bestGuess);
838+
$out[] = '';
839+
}
840+
841+
$out[] = 'Available options are :';
842+
$out[] = '';
843+
foreach ($availableOptions as $availableOption) {
844+
$out[] = ' - ' . $availableOption;
845+
}
846+
847+
return implode("\n", $out);
848+
}
849+
821850
/**
822851
* Tries to guess the item name the user originally wanted using the levenshtein algorithm.
823852
*
@@ -908,7 +937,7 @@ protected function _parseShortOption($option, $params)
908937
protected function _parseOption($name, $params)
909938
{
910939
if (!isset($this->_options[$name])) {
911-
throw new ConsoleException(sprintf('Unknown option `%s`', $name));
940+
throw new ConsoleException($this->getOptionError($name));
912941
}
913942
$option = $this->_options[$name];
914943
$isBoolean = $option->isBoolean();

src/Console/Shell.php

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -459,7 +459,6 @@ public function runCommand($argv, $autoMethod = false, $extra = [])
459459
list($this->params, $this->args) = $this->OptionParser->parse($argv);
460460
} catch (ConsoleException $e) {
461461
$this->err('Error: ' . $e->getMessage());
462-
$this->out($this->OptionParser->help($command));
463462

464463
return false;
465464
}

0 commit comments

Comments
 (0)