/** * Creates an Help object from a class subclassing Command * * @param string $name * @param string $subCommand * @return Help */ public static function fromCommandClass($name, $subCommand = null) { $prefix = 'execute'; $class = new ReflectionClass($name); if ($subCommand) { $method = $prefix . ucfirst(Utils::camelize($subCommand)); if (!$class->hasMethod($method)) { throw new ConsoleException("Sub command '{$subCommand}' of '{$name}' does not exist"); } return new Help($class->getMethod($method)->getDocComment()); } $help = new Help($class->getDocComment()); foreach ($class->getMethods() as $method) { if (strlen($method->getName()) > strlen($prefix) && substr($method->getName(), 0, strlen($prefix)) === $prefix) { $help->subCommands[] = Utils::dashized(substr($method->getName(), strlen($prefix))); } } return $help; }
/** * Registers a command * * @param callback $callback Associated class name, function name, Command instance or closure * @param string $alias Command name to be used in the shell * @param bool $default True to set the command as the default one * @return Console */ public function addCommand($callback, $alias = null, $default = false) { if ($alias instanceof \Closure && is_string($callback)) { list($alias, $callback) = array($callback, $alias); } if (is_array($callback) && is_string($callback[0])) { $callback = implode('::', $callback); } $name = ''; if (is_string($callback)) { $name = $callback; if (is_callable($callback)) { if (strpos($callback, '::') !== false) { list($classname, $methodname) = explode('::', $callback); $name = Utils::dashized($methodname); } else { $name = strtolower(trim(str_replace('_', '-', $name), '-')); } } else { if (substr($name, -7) === 'Command') { $name = substr($name, 0, -7); } $name = Utils::dashized(basename(str_replace('\\', '/', $name))); } } else { if (is_object($callback) && !$callback instanceof Closure) { $classname = get_class($callback); if (!$callback instanceof Command) { throw new ConsoleException("'{$classname}' must inherit from 'ConsoleKit\\Command'"); } if (substr($classname, -7) === 'Command') { $classname = substr($classname, 0, -7); } $name = Utils::dashized(basename(str_replace('\\', '/', $classname))); } else { if (!$alias) { throw new ConsoleException("Commands using closures must have an alias"); } } } $name = $alias ?: $name; $this->commands[$name] = $callback; if ($default) { $this->defaultCommand = $name; } return $this; }
public function testDashized() { $this->assertEquals('foo-bar', Utils::dashized('fooBar')); }