input = $input;
$this->output = $output;
return $this->handle();
}
/**
* 命令的主体
*
* @return int 命令执行结果 {@see self::SUCCESS} 或 {@see self::FAILURE} 或 {@see self::INVALID}
*/
abstract protected function handle(): int;
/**
* 输出一段文本,默认样式
*
* @param string $message 要输出的文本
* @param bool $newline 是否在文本后换行
* @see OutputInterface::write()
*/
protected function write(string $message, bool $newline = true): void
{
$this->output->write($message, $newline);
}
/**
* 输出文本,一般用于提示信息
*
* @param string $message 要输出的文本
* @param bool $newline 是否在文本后换行
*/
protected function info(string $message, bool $newline = true): void
{
$this->write("{$message}", $newline);
}
/**
* 输出文本,一般用于错误信息
*
* @param string $message 要输出的文本
* @param bool $newline 是否在文本后换行
*/
protected function error(string $message, bool $newline = true): void
{
$this->write("{$message}", $newline);
}
/**
* 输出文本,一般用于警告或附注信息
*
* @param string $message 要输出的文本
* @param bool $newline 是否在文本后换行
*/
protected function comment(string $message, bool $newline = true): void
{
$this->write("{$message}", $newline);
}
/**
* 输出文本,一般用于提问信息
*
* @param string $message 要输出的文本
* @param bool $newline 是否在文本后换行
*/
protected function question(string $message, bool $newline = true): void
{
$this->write("{$message}", $newline);
}
/**
* 输出文本,一般用于详细信息
*
* @param string $message 要输出的文本
* @param bool $newline 是否在文本后换行
*/
protected function detail(string $message, bool $newline = true): void
{
$this->write("{$message}>", $newline);
}
/**
* 输出一个区块,区块内内容可以覆写
*
* 此功能需要 $output 为 {@see ConsoleOutputInterface} 类型
*
* @param string $message 作为标题的文本
* @param callable $callback 回调函数,接收一个参数,类型为 {@see ConsoleSectionOutput}
*/
protected function section(string $message, callable $callback): void
{
$output = $this->output;
if (!$output instanceof ConsoleOutputInterface) {
throw new \LogicException('Section 功能只能在 ConsoleOutputInterface 中使用');
}
$this->info($message);
$section = $output->section();
try {
$callback($section);
} catch (ZMException $e) {
$this->error($e->getMessage());
exit(self::FAILURE);
}
}
}