4 * This file is part of the Symfony package.
6 * (c) Fabien Potencier <fabien@symfony.com>
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
12 namespace Symfony\Component\Console;
14 use Symfony\Component\Console\Input\InputInterface;
15 use Symfony\Component\Console\Input\ArgvInput;
16 use Symfony\Component\Console\Input\ArrayInput;
17 use Symfony\Component\Console\Input\InputDefinition;
18 use Symfony\Component\Console\Input\InputOption;
19 use Symfony\Component\Console\Input\InputArgument;
20 use Symfony\Component\Console\Output\OutputInterface;
21 use Symfony\Component\Console\Output\Output;
22 use Symfony\Component\Console\Output\ConsoleOutput;
23 use Symfony\Component\Console\Output\ConsoleOutputInterface;
24 use Symfony\Component\Console\Command\Command;
25 use Symfony\Component\Console\Command\HelpCommand;
26 use Symfony\Component\Console\Command\ListCommand;
27 use Symfony\Component\Console\Helper\HelperSet;
28 use Symfony\Component\Console\Helper\FormatterHelper;
29 use Symfony\Component\Console\Helper\DialogHelper;
32 * An Application is the container for a collection of commands.
34 * It is the main entry point of a Console application.
36 * This class is optimized for a standard CLI environment.
40 * $app = new Application('myapp', '1.0 (stable)');
41 * $app->add(new SimpleCommand());
44 * @author Fabien Potencier <fabien@symfony.com>
51 private $wantHelps = false;
52 private $runningCommand;
55 private $catchExceptions;
63 * @param string $name The name of the application
64 * @param string $version The version of the application
68 public function __construct($name = 'UNKNOWN', $version = 'UNKNOWN')
71 $this->version = $version;
72 $this->catchExceptions = true;
73 $this->autoExit = true;
74 $this->commands = array();
75 $this->helperSet = $this->getDefaultHelperSet();
76 $this->definition = $this->getDefaultInputDefinition();
78 foreach ($this->getDefaultCommands() as $command) {
84 * Runs the current application.
86 * @param InputInterface $input An Input instance
87 * @param OutputInterface $output An Output instance
89 * @return integer 0 if everything went fine, or an error code
91 * @throws \Exception When doRun returns Exception
95 public function run(InputInterface $input = null, OutputInterface $output = null)
97 if (null === $input) {
98 $input = new ArgvInput();
101 if (null === $output) {
102 $output = new ConsoleOutput();
106 $statusCode = $this->doRun($input, $output);
107 } catch (\Exception $e) {
108 if (!$this->catchExceptions) {
112 if ($output instanceof ConsoleOutputInterface) {
113 $this->renderException($e, $output->getErrorOutput());
115 $this->renderException($e, $output);
117 $statusCode = $e->getCode();
119 $statusCode = is_numeric($statusCode) && $statusCode ? $statusCode : 1;
122 if ($this->autoExit) {
123 if ($statusCode > 255) {
126 // @codeCoverageIgnoreStart
128 // @codeCoverageIgnoreEnd
135 * Runs the current application.
137 * @param InputInterface $input An Input instance
138 * @param OutputInterface $output An Output instance
140 * @return integer 0 if everything went fine, or an error code
142 public function doRun(InputInterface $input, OutputInterface $output)
144 $name = $this->getCommandName($input);
146 if (true === $input->hasParameterOption(array('--ansi'))) {
147 $output->setDecorated(true);
148 } elseif (true === $input->hasParameterOption(array('--no-ansi'))) {
149 $output->setDecorated(false);
152 if (true === $input->hasParameterOption(array('--help', '-h'))) {
155 $input = new ArrayInput(array('command' => 'help'));
157 $this->wantHelps = true;
161 if (true === $input->hasParameterOption(array('--no-interaction', '-n'))) {
162 $input->setInteractive(false);
165 if (function_exists('posix_isatty') && $this->getHelperSet()->has('dialog')) {
166 $inputStream = $this->getHelperSet()->get('dialog')->getInputStream();
167 if (!posix_isatty($inputStream)) {
168 $input->setInteractive(false);
172 if (true === $input->hasParameterOption(array('--quiet', '-q'))) {
173 $output->setVerbosity(OutputInterface::VERBOSITY_QUIET);
174 } elseif (true === $input->hasParameterOption(array('--verbose', '-v'))) {
175 $output->setVerbosity(OutputInterface::VERBOSITY_VERBOSE);
178 if (true === $input->hasParameterOption(array('--version', '-V'))) {
179 $output->writeln($this->getLongVersion());
186 $input = new ArrayInput(array('command' => 'list'));
189 // the command name MUST be the first element of the input
190 $command = $this->find($name);
192 $this->runningCommand = $command;
193 $statusCode = $command->run($input, $output);
194 $this->runningCommand = null;
196 return is_numeric($statusCode) ? $statusCode : 0;
200 * Set a helper set to be used with the command.
202 * @param HelperSet $helperSet The helper set
206 public function setHelperSet(HelperSet $helperSet)
208 $this->helperSet = $helperSet;
212 * Get the helper set associated with the command.
214 * @return HelperSet The HelperSet instance associated with this command
218 public function getHelperSet()
220 return $this->helperSet;
224 * Gets the InputDefinition related to this Application.
226 * @return InputDefinition The InputDefinition instance
228 public function getDefinition()
230 return $this->definition;
234 * Gets the help message.
236 * @return string A help message.
238 public function getHelp()
241 $this->getLongVersion(),
243 '<comment>Usage:</comment>',
244 sprintf(" [options] command [arguments]\n"),
245 '<comment>Options:</comment>',
248 foreach ($this->getDefinition()->getOptions() as $option) {
249 $messages[] = sprintf(' %-29s %s %s',
250 '<info>--'.$option->getName().'</info>',
251 $option->getShortcut() ? '<info>-'.$option->getShortcut().'</info>' : ' ',
252 $option->getDescription()
256 return implode(PHP_EOL, $messages);
260 * Sets whether to catch exceptions or not during commands execution.
262 * @param Boolean $boolean Whether to catch exceptions or not during commands execution
266 public function setCatchExceptions($boolean)
268 $this->catchExceptions = (Boolean) $boolean;
272 * Sets whether to automatically exit after a command execution or not.
274 * @param Boolean $boolean Whether to automatically exit after a command execution or not
278 public function setAutoExit($boolean)
280 $this->autoExit = (Boolean) $boolean;
284 * Gets the name of the application.
286 * @return string The application name
290 public function getName()
296 * Sets the application name.
298 * @param string $name The application name
302 public function setName($name)
308 * Gets the application version.
310 * @return string The application version
314 public function getVersion()
316 return $this->version;
320 * Sets the application version.
322 * @param string $version The application version
326 public function setVersion($version)
328 $this->version = $version;
332 * Returns the long version of the application.
334 * @return string The long application version
338 public function getLongVersion()
340 if ('UNKNOWN' !== $this->getName() && 'UNKNOWN' !== $this->getVersion()) {
341 return sprintf('<info>%s</info> version <comment>%s</comment>', $this->getName(), $this->getVersion());
344 return '<info>Console Tool</info>';
348 * Registers a new command.
350 * @param string $name The command name
352 * @return Command The newly created command
356 public function register($name)
358 return $this->add(new Command($name));
362 * Adds an array of command objects.
364 * @param Command[] $commands An array of commands
368 public function addCommands(array $commands)
370 foreach ($commands as $command) {
371 $this->add($command);
376 * Adds a command object.
378 * If a command with the same name already exists, it will be overridden.
380 * @param Command $command A Command object
382 * @return Command The registered command
386 public function add(Command $command)
388 $command->setApplication($this);
390 if (!$command->isEnabled()) {
391 $command->setApplication(null);
396 $this->commands[$command->getName()] = $command;
398 foreach ($command->getAliases() as $alias) {
399 $this->commands[$alias] = $command;
406 * Returns a registered command by name or alias.
408 * @param string $name The command name or alias
410 * @return Command A Command object
412 * @throws \InvalidArgumentException When command name given does not exist
416 public function get($name)
418 if (!isset($this->commands[$name])) {
419 throw new \InvalidArgumentException(sprintf('The command "%s" does not exist.', $name));
422 $command = $this->commands[$name];
424 if ($this->wantHelps) {
425 $this->wantHelps = false;
427 $helpCommand = $this->get('help');
428 $helpCommand->setCommand($command);
437 * Returns true if the command exists, false otherwise.
439 * @param string $name The command name or alias
441 * @return Boolean true if the command exists, false otherwise
445 public function has($name)
447 return isset($this->commands[$name]);
451 * Returns an array of all unique namespaces used by currently registered commands.
453 * It does not returns the global namespace which always exists.
455 * @return array An array of namespaces
457 public function getNamespaces()
459 $namespaces = array();
460 foreach ($this->commands as $command) {
461 $namespaces[] = $this->extractNamespace($command->getName());
463 foreach ($command->getAliases() as $alias) {
464 $namespaces[] = $this->extractNamespace($alias);
468 return array_values(array_unique(array_filter($namespaces)));
472 * Finds a registered namespace by a name or an abbreviation.
474 * @param string $namespace A namespace or abbreviation to search for
476 * @return string A registered namespace
478 * @throws \InvalidArgumentException When namespace is incorrect or ambiguous
480 public function findNamespace($namespace)
482 $allNamespaces = array();
483 foreach ($this->getNamespaces() as $n) {
484 $allNamespaces[$n] = explode(':', $n);
488 foreach (explode(':', $namespace) as $i => $part) {
489 $abbrevs = static::getAbbreviations(array_unique(array_values(array_filter(array_map(function ($p) use ($i) { return isset($p[$i]) ? $p[$i] : ''; }, $allNamespaces)))));
491 if (!isset($abbrevs[$part])) {
492 $message = sprintf('There are no commands defined in the "%s" namespace.', $namespace);
495 $part = implode(':', $found).':'.$part;
498 if ($alternatives = $this->findAlternativeNamespace($part, $abbrevs)) {
499 if (1 == count($alternatives)) {
500 $message .= "\n\nDid you mean this?\n ";
502 $message .= "\n\nDid you mean one of these?\n ";
505 $message .= implode("\n ", $alternatives);
508 throw new \InvalidArgumentException($message);
511 if (count($abbrevs[$part]) > 1) {
512 throw new \InvalidArgumentException(sprintf('The namespace "%s" is ambiguous (%s).', $namespace, $this->getAbbreviationSuggestions($abbrevs[$part])));
515 $found[] = $abbrevs[$part][0];
518 return implode(':', $found);
522 * Finds a command by name or alias.
524 * Contrary to get, this command tries to find the best
525 * match if you give it an abbreviation of a name or alias.
527 * @param string $name A command name or a command alias
529 * @return Command A Command instance
531 * @throws \InvalidArgumentException When command name is incorrect or ambiguous
535 public function find($name)
540 if (false !== $pos = strrpos($name, ':')) {
541 $namespace = $this->findNamespace(substr($name, 0, $pos));
542 $searchName = $namespace.substr($name, $pos);
547 foreach ($this->commands as $command) {
548 if ($this->extractNamespace($command->getName()) == $namespace) {
549 $commands[] = $command->getName();
553 $abbrevs = static::getAbbreviations(array_unique($commands));
554 if (isset($abbrevs[$searchName]) && 1 == count($abbrevs[$searchName])) {
555 return $this->get($abbrevs[$searchName][0]);
558 if (isset($abbrevs[$searchName]) && count($abbrevs[$searchName]) > 1) {
559 $suggestions = $this->getAbbreviationSuggestions($abbrevs[$searchName]);
561 throw new \InvalidArgumentException(sprintf('Command "%s" is ambiguous (%s).', $name, $suggestions));
566 foreach ($this->commands as $command) {
567 foreach ($command->getAliases() as $alias) {
568 if ($this->extractNamespace($alias) == $namespace) {
574 $aliases = static::getAbbreviations(array_unique($aliases));
575 if (!isset($aliases[$searchName])) {
576 $message = sprintf('Command "%s" is not defined.', $name);
578 if ($alternatives = $this->findAlternativeCommands($searchName, $abbrevs)) {
579 if (1 == count($alternatives)) {
580 $message .= "\n\nDid you mean this?\n ";
582 $message .= "\n\nDid you mean one of these?\n ";
584 $message .= implode("\n ", $alternatives);
587 throw new \InvalidArgumentException($message);
590 if (count($aliases[$searchName]) > 1) {
591 throw new \InvalidArgumentException(sprintf('Command "%s" is ambiguous (%s).', $name, $this->getAbbreviationSuggestions($aliases[$searchName])));
594 return $this->get($aliases[$searchName][0]);
598 * Gets the commands (registered in the given namespace if provided).
600 * The array keys are the full names and the values the command instances.
602 * @param string $namespace A namespace name
604 * @return array An array of Command instances
608 public function all($namespace = null)
610 if (null === $namespace) {
611 return $this->commands;
615 foreach ($this->commands as $name => $command) {
616 if ($namespace === $this->extractNamespace($name, substr_count($namespace, ':') + 1)) {
617 $commands[$name] = $command;
625 * Returns an array of possible abbreviations given a set of names.
627 * @param array $names An array of names
629 * @return array An array of abbreviations
631 public static function getAbbreviations($names)
634 foreach ($names as $name) {
635 for ($len = strlen($name) - 1; $len > 0; --$len) {
636 $abbrev = substr($name, 0, $len);
637 if (!isset($abbrevs[$abbrev])) {
638 $abbrevs[$abbrev] = array($name);
640 $abbrevs[$abbrev][] = $name;
645 // Non-abbreviations always get entered, even if they aren't unique
646 foreach ($names as $name) {
647 $abbrevs[$name] = array($name);
654 * Returns a text representation of the Application.
656 * @param string $namespace An optional namespace name
657 * @param boolean $raw Whether to return raw command list
659 * @return string A string representing the Application
661 public function asText($namespace = null, $raw = false)
663 $commands = $namespace ? $this->all($this->findNamespace($namespace)) : $this->commands;
666 foreach ($commands as $command) {
667 $width = strlen($command->getName()) > $width ? strlen($command->getName()) : $width;
673 foreach ($this->sortCommands($commands) as $space => $commands) {
674 foreach ($commands as $name => $command) {
675 $messages[] = sprintf("%-${width}s %s", $name, $command->getDescription());
679 return implode(PHP_EOL, $messages);
682 $messages = array($this->getHelp(), '');
684 $messages[] = sprintf("<comment>Available commands for the \"%s\" namespace:</comment>", $namespace);
686 $messages[] = '<comment>Available commands:</comment>';
689 // add commands by namespace
690 foreach ($this->sortCommands($commands) as $space => $commands) {
691 if (!$namespace && '_global' !== $space) {
692 $messages[] = '<comment>'.$space.'</comment>';
695 foreach ($commands as $name => $command) {
696 $messages[] = sprintf(" <info>%-${width}s</info> %s", $name, $command->getDescription());
700 return implode(PHP_EOL, $messages);
704 * Returns an XML representation of the Application.
706 * @param string $namespace An optional namespace name
707 * @param Boolean $asDom Whether to return a DOM or an XML string
709 * @return string|DOMDocument An XML string representing the Application
711 public function asXml($namespace = null, $asDom = false)
713 $commands = $namespace ? $this->all($this->findNamespace($namespace)) : $this->commands;
715 $dom = new \DOMDocument('1.0', 'UTF-8');
716 $dom->formatOutput = true;
717 $dom->appendChild($xml = $dom->createElement('symfony'));
719 $xml->appendChild($commandsXML = $dom->createElement('commands'));
722 $commandsXML->setAttribute('namespace', $namespace);
724 $namespacesXML = $dom->createElement('namespaces');
725 $xml->appendChild($namespacesXML);
728 // add commands by namespace
729 foreach ($this->sortCommands($commands) as $space => $commands) {
731 $namespaceArrayXML = $dom->createElement('namespace');
732 $namespacesXML->appendChild($namespaceArrayXML);
733 $namespaceArrayXML->setAttribute('id', $space);
736 foreach ($commands as $name => $command) {
737 if ($name !== $command->getName()) {
742 $commandXML = $dom->createElement('command');
743 $namespaceArrayXML->appendChild($commandXML);
744 $commandXML->appendChild($dom->createTextNode($name));
747 $node = $command->asXml(true)->getElementsByTagName('command')->item(0);
748 $node = $dom->importNode($node, true);
750 $commandsXML->appendChild($node);
754 return $asDom ? $dom : $dom->saveXml();
758 * Renders a caught exception.
760 * @param Exception $e An exception instance
761 * @param OutputInterface $output An OutputInterface instance
763 public function renderException($e, $output)
765 $strlen = function ($string) {
766 if (!function_exists('mb_strlen')) {
767 return strlen($string);
770 if (false === $encoding = mb_detect_encoding($string)) {
771 return strlen($string);
774 return mb_strlen($string, $encoding);
778 $title = sprintf(' [%s] ', get_class($e));
779 $len = $strlen($title);
780 $width = $this->getTerminalWidth() ? $this->getTerminalWidth() - 1 : PHP_INT_MAX;
782 foreach (preg_split("{\r?\n}", $e->getMessage()) as $line) {
783 foreach (str_split($line, $width - 4) as $line) {
784 $lines[] = sprintf(' %s ', $line);
785 $len = max($strlen($line) + 4, $len);
789 $messages = array(str_repeat(' ', $len), $title.str_repeat(' ', max(0, $len - $strlen($title))));
791 foreach ($lines as $line) {
792 $messages[] = $line.str_repeat(' ', $len - $strlen($line));
795 $messages[] = str_repeat(' ', $len);
797 $output->writeln("");
798 $output->writeln("");
799 foreach ($messages as $message) {
800 $output->writeln('<error>'.$message.'</error>');
802 $output->writeln("");
803 $output->writeln("");
805 if (OutputInterface::VERBOSITY_VERBOSE === $output->getVerbosity()) {
806 $output->writeln('<comment>Exception trace:</comment>');
808 // exception related properties
809 $trace = $e->getTrace();
810 array_unshift($trace, array(
812 'file' => $e->getFile() != null ? $e->getFile() : 'n/a',
813 'line' => $e->getLine() != null ? $e->getLine() : 'n/a',
817 for ($i = 0, $count = count($trace); $i < $count; $i++) {
818 $class = isset($trace[$i]['class']) ? $trace[$i]['class'] : '';
819 $type = isset($trace[$i]['type']) ? $trace[$i]['type'] : '';
820 $function = $trace[$i]['function'];
821 $file = isset($trace[$i]['file']) ? $trace[$i]['file'] : 'n/a';
822 $line = isset($trace[$i]['line']) ? $trace[$i]['line'] : 'n/a';
824 $output->writeln(sprintf(' %s%s%s() at <info>%s:%s</info>', $class, $type, $function, $file, $line));
827 $output->writeln("");
828 $output->writeln("");
830 } while ($e = $e->getPrevious());
832 if (null !== $this->runningCommand) {
833 $output->writeln(sprintf('<info>%s</info>', sprintf($this->runningCommand->getSynopsis(), $this->getName())));
834 $output->writeln("");
835 $output->writeln("");
840 * Tries to figure out the terminal width in which this application runs
844 protected function getTerminalWidth()
846 if (defined('PHP_WINDOWS_VERSION_BUILD')) {
847 if ($ansicon = getenv('ANSICON')) {
848 return preg_replace('{^(\d+)x.*$}', '$1', $ansicon);
851 exec('mode CON', $execData);
852 if (preg_match('{columns:\s*(\d+)}i', $execData[4], $matches)) {
857 if (preg_match("{rows.(\d+);.columns.(\d+);}i", $this->getSttyColumns(), $match)) {
863 * Tries to figure out the terminal height in which this application runs
867 protected function getTerminalHeight()
869 if (defined('PHP_WINDOWS_VERSION_BUILD')) {
870 if ($ansicon = getenv('ANSICON')) {
871 return preg_replace('{^\d+x\d+ \(\d+x(\d+)\)$}', '$1', trim($ansicon));
874 exec('mode CON', $execData);
875 if (preg_match('{lines:\s*(\d+)}i', $execData[3], $matches)) {
880 if (preg_match("{rows.(\d+);.columns.(\d+);}i", $this->getSttyColumns(), $match)) {
886 * Gets the name of the command based on input.
888 * @param InputInterface $input The input interface
890 * @return string The command name
892 protected function getCommandName(InputInterface $input)
894 return $input->getFirstArgument();
898 * Gets the default input definition.
900 * @return InputDefinition An InputDefinition instance
902 protected function getDefaultInputDefinition()
904 return new InputDefinition(array(
905 new InputArgument('command', InputArgument::REQUIRED, 'The command to execute'),
907 new InputOption('--help', '-h', InputOption::VALUE_NONE, 'Display this help message.'),
908 new InputOption('--quiet', '-q', InputOption::VALUE_NONE, 'Do not output any message.'),
909 new InputOption('--verbose', '-v', InputOption::VALUE_NONE, 'Increase verbosity of messages.'),
910 new InputOption('--version', '-V', InputOption::VALUE_NONE, 'Display this application version.'),
911 new InputOption('--ansi', '', InputOption::VALUE_NONE, 'Force ANSI output.'),
912 new InputOption('--no-ansi', '', InputOption::VALUE_NONE, 'Disable ANSI output.'),
913 new InputOption('--no-interaction', '-n', InputOption::VALUE_NONE, 'Do not ask any interactive question.'),
918 * Gets the default commands that should always be available.
920 * @return array An array of default Command instances
922 protected function getDefaultCommands()
924 return array(new HelpCommand(), new ListCommand());
928 * Gets the default helper set with the helpers that should always be available.
930 * @return HelperSet A HelperSet instance
932 protected function getDefaultHelperSet()
934 return new HelperSet(array(
935 new FormatterHelper(),
941 * Runs and parses stty -a if it's available, suppressing any error output
945 private function getSttyColumns()
947 if (!function_exists('proc_open')) {
951 $descriptorspec = array(1 => array('pipe', 'w'), 2 => array('pipe', 'w'));
952 $process = proc_open('stty -a | grep columns', $descriptorspec, $pipes, null, null, array('suppress_errors' => true));
953 if (is_resource($process)) {
954 $info = stream_get_contents($pipes[1]);
957 proc_close($process);
964 * Sorts commands in alphabetical order.
966 * @param array $commands An associative array of commands to sort
968 * @return array A sorted array of commands
970 private function sortCommands($commands)
972 $namespacedCommands = array();
973 foreach ($commands as $name => $command) {
974 $key = $this->extractNamespace($name, 1);
979 $namespacedCommands[$key][$name] = $command;
981 ksort($namespacedCommands);
983 foreach ($namespacedCommands as &$commands) {
987 return $namespacedCommands;
991 * Returns abbreviated suggestions in string format.
993 * @param array $abbrevs Abbreviated suggestions to convert
995 * @return string A formatted string of abbreviated suggestions
997 private function getAbbreviationSuggestions($abbrevs)
999 return sprintf('%s, %s%s', $abbrevs[0], $abbrevs[1], count($abbrevs) > 2 ? sprintf(' and %d more', count($abbrevs) - 2) : '');
1003 * Returns the namespace part of the command name.
1005 * @param string $name The full name of the command
1006 * @param string $limit The maximum number of parts of the namespace
1008 * @return string The namespace of the command
1010 private function extractNamespace($name, $limit = null)
1012 $parts = explode(':', $name);
1015 return implode(':', null === $limit ? $parts : array_slice($parts, 0, $limit));
1019 * Finds alternative commands of $name
1021 * @param string $name The full name of the command
1022 * @param array $abbrevs The abbreviations
1024 * @return array A sorted array of similar commands
1026 private function findAlternativeCommands($name, $abbrevs)
1028 $callback = function($item) {
1029 return $item->getName();
1032 return $this->findAlternatives($name, $this->commands, $abbrevs, $callback);
1036 * Finds alternative namespace of $name
1038 * @param string $name The full name of the namespace
1039 * @param array $abbrevs The abbreviations
1041 * @return array A sorted array of similar namespace
1043 private function findAlternativeNamespace($name, $abbrevs)
1045 return $this->findAlternatives($name, $this->getNamespaces(), $abbrevs);
1049 * Finds alternative of $name among $collection,
1050 * if nothing is found in $collection, try in $abbrevs
1052 * @param string $name The string
1053 * @param array|Traversable $collection The collection
1054 * @param array $abbrevs The abbreviations
1055 * @param Closure|string|array $callback The callable to transform collection item before comparison
1057 * @return array A sorted array of similar string
1059 private function findAlternatives($name, $collection, $abbrevs, $callback = null)
1061 $alternatives = array();
1063 foreach ($collection as $item) {
1064 if (null !== $callback) {
1065 $item = call_user_func($callback, $item);
1068 $lev = levenshtein($name, $item);
1069 if ($lev <= strlen($name) / 3 || false !== strpos($item, $name)) {
1070 $alternatives[$item] = $lev;
1074 if (!$alternatives) {
1075 foreach ($abbrevs as $key => $values) {
1076 $lev = levenshtein($name, $key);
1077 if ($lev <= strlen($name) / 3 || false !== strpos($key, $name)) {
1078 foreach ($values as $value) {
1079 $alternatives[$value] = $lev;
1085 asort($alternatives);
1087 return array_keys($alternatives);