fix: 上传TP框架
This commit is contained in:
340
thinkphp/library/think/console/output/Ask.php
Normal file
340
thinkphp/library/think/console/output/Ask.php
Normal file
@ -0,0 +1,340 @@
|
||||
<?php
|
||||
// +----------------------------------------------------------------------
|
||||
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
|
||||
// +----------------------------------------------------------------------
|
||||
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
|
||||
// +----------------------------------------------------------------------
|
||||
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
|
||||
// +----------------------------------------------------------------------
|
||||
// | Author: yunwuxin <448901948@qq.com>
|
||||
// +----------------------------------------------------------------------
|
||||
|
||||
namespace think\console\output;
|
||||
|
||||
use think\console\Input;
|
||||
use think\console\Output;
|
||||
use think\console\output\question\Choice;
|
||||
use think\console\output\question\Confirmation;
|
||||
|
||||
class Ask
|
||||
{
|
||||
private static $stty;
|
||||
|
||||
private static $shell;
|
||||
|
||||
/** @var Input */
|
||||
protected $input;
|
||||
|
||||
/** @var Output */
|
||||
protected $output;
|
||||
|
||||
/** @var Question */
|
||||
protected $question;
|
||||
|
||||
public function __construct(Input $input, Output $output, Question $question)
|
||||
{
|
||||
$this->input = $input;
|
||||
$this->output = $output;
|
||||
$this->question = $question;
|
||||
}
|
||||
|
||||
public function run()
|
||||
{
|
||||
if (!$this->input->isInteractive()) {
|
||||
return $this->question->getDefault();
|
||||
}
|
||||
|
||||
if (!$this->question->getValidator()) {
|
||||
return $this->doAsk();
|
||||
}
|
||||
|
||||
$that = $this;
|
||||
|
||||
$interviewer = function () use ($that) {
|
||||
return $that->doAsk();
|
||||
};
|
||||
|
||||
return $this->validateAttempts($interviewer);
|
||||
}
|
||||
|
||||
protected function doAsk()
|
||||
{
|
||||
$this->writePrompt();
|
||||
|
||||
$inputStream = STDIN;
|
||||
$autocomplete = $this->question->getAutocompleterValues();
|
||||
|
||||
if (null === $autocomplete || !$this->hasSttyAvailable()) {
|
||||
$ret = false;
|
||||
if ($this->question->isHidden()) {
|
||||
try {
|
||||
$ret = trim($this->getHiddenResponse($inputStream));
|
||||
} catch (\RuntimeException $e) {
|
||||
if (!$this->question->isHiddenFallback()) {
|
||||
throw $e;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (false === $ret) {
|
||||
$ret = fgets($inputStream, 4096);
|
||||
if (false === $ret) {
|
||||
throw new \RuntimeException('Aborted');
|
||||
}
|
||||
$ret = trim($ret);
|
||||
}
|
||||
} else {
|
||||
$ret = trim($this->autocomplete($inputStream));
|
||||
}
|
||||
|
||||
$ret = strlen($ret) > 0 ? $ret : $this->question->getDefault();
|
||||
|
||||
if ($normalizer = $this->question->getNormalizer()) {
|
||||
return $normalizer($ret);
|
||||
}
|
||||
|
||||
return $ret;
|
||||
}
|
||||
|
||||
private function autocomplete($inputStream)
|
||||
{
|
||||
$autocomplete = $this->question->getAutocompleterValues();
|
||||
$ret = '';
|
||||
|
||||
$i = 0;
|
||||
$ofs = -1;
|
||||
$matches = $autocomplete;
|
||||
$numMatches = count($matches);
|
||||
|
||||
$sttyMode = shell_exec('stty -g');
|
||||
|
||||
shell_exec('stty -icanon -echo');
|
||||
|
||||
while (!feof($inputStream)) {
|
||||
$c = fread($inputStream, 1);
|
||||
|
||||
if ("\177" === $c) {
|
||||
if (0 === $numMatches && 0 !== $i) {
|
||||
--$i;
|
||||
$this->output->write("\033[1D");
|
||||
}
|
||||
|
||||
if ($i === 0) {
|
||||
$ofs = -1;
|
||||
$matches = $autocomplete;
|
||||
$numMatches = count($matches);
|
||||
} else {
|
||||
$numMatches = 0;
|
||||
}
|
||||
|
||||
$ret = substr($ret, 0, $i);
|
||||
} elseif ("\033" === $c) {
|
||||
$c .= fread($inputStream, 2);
|
||||
|
||||
if (isset($c[2]) && ('A' === $c[2] || 'B' === $c[2])) {
|
||||
if ('A' === $c[2] && -1 === $ofs) {
|
||||
$ofs = 0;
|
||||
}
|
||||
|
||||
if (0 === $numMatches) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$ofs += ('A' === $c[2]) ? -1 : 1;
|
||||
$ofs = ($numMatches + $ofs) % $numMatches;
|
||||
}
|
||||
} elseif (ord($c) < 32) {
|
||||
if ("\t" === $c || "\n" === $c) {
|
||||
if ($numMatches > 0 && -1 !== $ofs) {
|
||||
$ret = $matches[$ofs];
|
||||
$this->output->write(substr($ret, $i));
|
||||
$i = strlen($ret);
|
||||
}
|
||||
|
||||
if ("\n" === $c) {
|
||||
$this->output->write($c);
|
||||
break;
|
||||
}
|
||||
|
||||
$numMatches = 0;
|
||||
}
|
||||
|
||||
continue;
|
||||
} else {
|
||||
$this->output->write($c);
|
||||
$ret .= $c;
|
||||
++$i;
|
||||
|
||||
$numMatches = 0;
|
||||
$ofs = 0;
|
||||
|
||||
foreach ($autocomplete as $value) {
|
||||
if (0 === strpos($value, $ret) && $i !== strlen($value)) {
|
||||
$matches[$numMatches++] = $value;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$this->output->write("\033[K");
|
||||
|
||||
if ($numMatches > 0 && -1 !== $ofs) {
|
||||
$this->output->write("\0337");
|
||||
$this->output->highlight(substr($matches[$ofs], $i));
|
||||
$this->output->write("\0338");
|
||||
}
|
||||
}
|
||||
|
||||
shell_exec(sprintf('stty %s', $sttyMode));
|
||||
|
||||
return $ret;
|
||||
}
|
||||
|
||||
protected function getHiddenResponse($inputStream)
|
||||
{
|
||||
if ('\\' === DIRECTORY_SEPARATOR) {
|
||||
$exe = __DIR__ . '/../bin/hiddeninput.exe';
|
||||
|
||||
$value = rtrim(shell_exec($exe));
|
||||
$this->output->writeln('');
|
||||
|
||||
if (isset($tmpExe)) {
|
||||
unlink($tmpExe);
|
||||
}
|
||||
|
||||
return $value;
|
||||
}
|
||||
|
||||
if ($this->hasSttyAvailable()) {
|
||||
$sttyMode = shell_exec('stty -g');
|
||||
|
||||
shell_exec('stty -echo');
|
||||
$value = fgets($inputStream, 4096);
|
||||
shell_exec(sprintf('stty %s', $sttyMode));
|
||||
|
||||
if (false === $value) {
|
||||
throw new \RuntimeException('Aborted');
|
||||
}
|
||||
|
||||
$value = trim($value);
|
||||
$this->output->writeln('');
|
||||
|
||||
return $value;
|
||||
}
|
||||
|
||||
if (false !== $shell = $this->getShell()) {
|
||||
$readCmd = $shell === 'csh' ? 'set mypassword = $<' : 'read -r mypassword';
|
||||
$command = sprintf("/usr/bin/env %s -c 'stty -echo; %s; stty echo; echo \$mypassword'", $shell, $readCmd);
|
||||
$value = rtrim(shell_exec($command));
|
||||
$this->output->writeln('');
|
||||
|
||||
return $value;
|
||||
}
|
||||
|
||||
throw new \RuntimeException('Unable to hide the response.');
|
||||
}
|
||||
|
||||
protected function validateAttempts($interviewer)
|
||||
{
|
||||
/** @var \Exception $error */
|
||||
$error = null;
|
||||
$attempts = $this->question->getMaxAttempts();
|
||||
while (null === $attempts || $attempts--) {
|
||||
if (null !== $error) {
|
||||
$this->output->error($error->getMessage());
|
||||
}
|
||||
|
||||
try {
|
||||
return call_user_func($this->question->getValidator(), $interviewer());
|
||||
} catch (\Exception $error) {
|
||||
}
|
||||
}
|
||||
|
||||
throw $error;
|
||||
}
|
||||
|
||||
/**
|
||||
* 显示问题的提示信息
|
||||
*/
|
||||
protected function writePrompt()
|
||||
{
|
||||
$text = $this->question->getQuestion();
|
||||
$default = $this->question->getDefault();
|
||||
|
||||
switch (true) {
|
||||
case null === $default:
|
||||
$text = sprintf(' <info>%s</info>:', $text);
|
||||
|
||||
break;
|
||||
|
||||
case $this->question instanceof Confirmation:
|
||||
$text = sprintf(' <info>%s (yes/no)</info> [<comment>%s</comment>]:', $text, $default ? 'yes' : 'no');
|
||||
|
||||
break;
|
||||
|
||||
case $this->question instanceof Choice && $this->question->isMultiselect():
|
||||
$choices = $this->question->getChoices();
|
||||
$default = explode(',', $default);
|
||||
|
||||
foreach ($default as $key => $value) {
|
||||
$default[$key] = $choices[trim($value)];
|
||||
}
|
||||
|
||||
$text = sprintf(' <info>%s</info> [<comment>%s</comment>]:', $text, implode(', ', $default));
|
||||
|
||||
break;
|
||||
|
||||
case $this->question instanceof Choice:
|
||||
$choices = $this->question->getChoices();
|
||||
$text = sprintf(' <info>%s</info> [<comment>%s</comment>]:', $text, $choices[$default]);
|
||||
|
||||
break;
|
||||
|
||||
default:
|
||||
$text = sprintf(' <info>%s</info> [<comment>%s</comment>]:', $text, $default);
|
||||
}
|
||||
|
||||
$this->output->writeln($text);
|
||||
|
||||
if ($this->question instanceof Choice) {
|
||||
$width = max(array_map('strlen', array_keys($this->question->getChoices())));
|
||||
|
||||
foreach ($this->question->getChoices() as $key => $value) {
|
||||
$this->output->writeln(sprintf(" [<comment>%-${width}s</comment>] %s", $key, $value));
|
||||
}
|
||||
}
|
||||
|
||||
$this->output->write(' > ');
|
||||
}
|
||||
|
||||
private function getShell()
|
||||
{
|
||||
if (null !== self::$shell) {
|
||||
return self::$shell;
|
||||
}
|
||||
|
||||
self::$shell = false;
|
||||
|
||||
if (file_exists('/usr/bin/env')) {
|
||||
$test = "/usr/bin/env %s -c 'echo OK' 2> /dev/null";
|
||||
foreach (['bash', 'zsh', 'ksh', 'csh'] as $sh) {
|
||||
if ('OK' === rtrim(shell_exec(sprintf($test, $sh)))) {
|
||||
self::$shell = $sh;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return self::$shell;
|
||||
}
|
||||
|
||||
private function hasSttyAvailable()
|
||||
{
|
||||
if (null !== self::$stty) {
|
||||
return self::$stty;
|
||||
}
|
||||
|
||||
exec('stty 2>&1', $output, $exitcode);
|
||||
|
||||
return self::$stty = $exitcode === 0;
|
||||
}
|
||||
}
|
319
thinkphp/library/think/console/output/Descriptor.php
Normal file
319
thinkphp/library/think/console/output/Descriptor.php
Normal file
@ -0,0 +1,319 @@
|
||||
<?php
|
||||
// +----------------------------------------------------------------------
|
||||
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
|
||||
// +----------------------------------------------------------------------
|
||||
// | Copyright (c) 2006~2015 http://thinkphp.cn All rights reserved.
|
||||
// +----------------------------------------------------------------------
|
||||
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
|
||||
// +----------------------------------------------------------------------
|
||||
// | Author: yunwuxin <448901948@qq.com>
|
||||
// +----------------------------------------------------------------------
|
||||
|
||||
namespace think\console\output;
|
||||
|
||||
use think\Console;
|
||||
use think\console\Command;
|
||||
use think\console\input\Argument as InputArgument;
|
||||
use think\console\input\Definition as InputDefinition;
|
||||
use think\console\input\Option as InputOption;
|
||||
use think\console\Output;
|
||||
use think\console\output\descriptor\Console as ConsoleDescription;
|
||||
|
||||
class Descriptor
|
||||
{
|
||||
|
||||
/**
|
||||
* @var Output
|
||||
*/
|
||||
protected $output;
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function describe(Output $output, $object, array $options = [])
|
||||
{
|
||||
$this->output = $output;
|
||||
|
||||
switch (true) {
|
||||
case $object instanceof InputArgument:
|
||||
$this->describeInputArgument($object, $options);
|
||||
break;
|
||||
case $object instanceof InputOption:
|
||||
$this->describeInputOption($object, $options);
|
||||
break;
|
||||
case $object instanceof InputDefinition:
|
||||
$this->describeInputDefinition($object, $options);
|
||||
break;
|
||||
case $object instanceof Command:
|
||||
$this->describeCommand($object, $options);
|
||||
break;
|
||||
case $object instanceof Console:
|
||||
$this->describeConsole($object, $options);
|
||||
break;
|
||||
default:
|
||||
throw new \InvalidArgumentException(sprintf('Object of type "%s" is not describable.', get_class($object)));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 输出内容
|
||||
* @param string $content
|
||||
* @param bool $decorated
|
||||
*/
|
||||
protected function write($content, $decorated = false)
|
||||
{
|
||||
$this->output->write($content, false, $decorated ? Output::OUTPUT_NORMAL : Output::OUTPUT_RAW);
|
||||
}
|
||||
|
||||
/**
|
||||
* 描述参数
|
||||
* @param InputArgument $argument
|
||||
* @param array $options
|
||||
* @return void
|
||||
*/
|
||||
protected function describeInputArgument(InputArgument $argument, array $options = [])
|
||||
{
|
||||
if (null !== $argument->getDefault()
|
||||
&& (!is_array($argument->getDefault())
|
||||
|| count($argument->getDefault()))
|
||||
) {
|
||||
$default = sprintf('<comment> [default: %s]</comment>', $this->formatDefaultValue($argument->getDefault()));
|
||||
} else {
|
||||
$default = '';
|
||||
}
|
||||
|
||||
$totalWidth = isset($options['total_width']) ? $options['total_width'] : strlen($argument->getName());
|
||||
$spacingWidth = $totalWidth - strlen($argument->getName()) + 2;
|
||||
|
||||
$this->writeText(sprintf(" <info>%s</info>%s%s%s", $argument->getName(), str_repeat(' ', $spacingWidth), // + 17 = 2 spaces + <info> + </info> + 2 spaces
|
||||
preg_replace('/\s*\R\s*/', PHP_EOL . str_repeat(' ', $totalWidth + 17), $argument->getDescription()), $default), $options);
|
||||
}
|
||||
|
||||
/**
|
||||
* 描述选项
|
||||
* @param InputOption $option
|
||||
* @param array $options
|
||||
* @return void
|
||||
*/
|
||||
protected function describeInputOption(InputOption $option, array $options = [])
|
||||
{
|
||||
if ($option->acceptValue() && null !== $option->getDefault()
|
||||
&& (!is_array($option->getDefault())
|
||||
|| count($option->getDefault()))
|
||||
) {
|
||||
$default = sprintf('<comment> [default: %s]</comment>', $this->formatDefaultValue($option->getDefault()));
|
||||
} else {
|
||||
$default = '';
|
||||
}
|
||||
|
||||
$value = '';
|
||||
if ($option->acceptValue()) {
|
||||
$value = '=' . strtoupper($option->getName());
|
||||
|
||||
if ($option->isValueOptional()) {
|
||||
$value = '[' . $value . ']';
|
||||
}
|
||||
}
|
||||
|
||||
$totalWidth = isset($options['total_width']) ? $options['total_width'] : $this->calculateTotalWidthForOptions([$option]);
|
||||
$synopsis = sprintf('%s%s', $option->getShortcut() ? sprintf('-%s, ', $option->getShortcut()) : ' ', sprintf('--%s%s', $option->getName(), $value));
|
||||
|
||||
$spacingWidth = $totalWidth - strlen($synopsis) + 2;
|
||||
|
||||
$this->writeText(sprintf(" <info>%s</info>%s%s%s%s", $synopsis, str_repeat(' ', $spacingWidth), // + 17 = 2 spaces + <info> + </info> + 2 spaces
|
||||
preg_replace('/\s*\R\s*/', "\n" . str_repeat(' ', $totalWidth + 17), $option->getDescription()), $default, $option->isArray() ? '<comment> (multiple values allowed)</comment>' : ''), $options);
|
||||
}
|
||||
|
||||
/**
|
||||
* 描述输入
|
||||
* @param InputDefinition $definition
|
||||
* @param array $options
|
||||
* @return void
|
||||
*/
|
||||
protected function describeInputDefinition(InputDefinition $definition, array $options = [])
|
||||
{
|
||||
$totalWidth = $this->calculateTotalWidthForOptions($definition->getOptions());
|
||||
foreach ($definition->getArguments() as $argument) {
|
||||
$totalWidth = max($totalWidth, strlen($argument->getName()));
|
||||
}
|
||||
|
||||
if ($definition->getArguments()) {
|
||||
$this->writeText('<comment>Arguments:</comment>', $options);
|
||||
$this->writeText("\n");
|
||||
foreach ($definition->getArguments() as $argument) {
|
||||
$this->describeInputArgument($argument, array_merge($options, ['total_width' => $totalWidth]));
|
||||
$this->writeText("\n");
|
||||
}
|
||||
}
|
||||
|
||||
if ($definition->getArguments() && $definition->getOptions()) {
|
||||
$this->writeText("\n");
|
||||
}
|
||||
|
||||
if ($definition->getOptions()) {
|
||||
$laterOptions = [];
|
||||
|
||||
$this->writeText('<comment>Options:</comment>', $options);
|
||||
foreach ($definition->getOptions() as $option) {
|
||||
if (strlen($option->getShortcut()) > 1) {
|
||||
$laterOptions[] = $option;
|
||||
continue;
|
||||
}
|
||||
$this->writeText("\n");
|
||||
$this->describeInputOption($option, array_merge($options, ['total_width' => $totalWidth]));
|
||||
}
|
||||
foreach ($laterOptions as $option) {
|
||||
$this->writeText("\n");
|
||||
$this->describeInputOption($option, array_merge($options, ['total_width' => $totalWidth]));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 描述指令
|
||||
* @param Command $command
|
||||
* @param array $options
|
||||
* @return void
|
||||
*/
|
||||
protected function describeCommand(Command $command, array $options = [])
|
||||
{
|
||||
$command->getSynopsis(true);
|
||||
$command->getSynopsis(false);
|
||||
$command->mergeConsoleDefinition(false);
|
||||
|
||||
$this->writeText('<comment>Usage:</comment>', $options);
|
||||
foreach (array_merge([$command->getSynopsis(true)], $command->getAliases(), $command->getUsages()) as $usage) {
|
||||
$this->writeText("\n");
|
||||
$this->writeText(' ' . $usage, $options);
|
||||
}
|
||||
$this->writeText("\n");
|
||||
|
||||
$definition = $command->getNativeDefinition();
|
||||
if ($definition->getOptions() || $definition->getArguments()) {
|
||||
$this->writeText("\n");
|
||||
$this->describeInputDefinition($definition, $options);
|
||||
$this->writeText("\n");
|
||||
}
|
||||
|
||||
if ($help = $command->getProcessedHelp()) {
|
||||
$this->writeText("\n");
|
||||
$this->writeText('<comment>Help:</comment>', $options);
|
||||
$this->writeText("\n");
|
||||
$this->writeText(' ' . str_replace("\n", "\n ", $help), $options);
|
||||
$this->writeText("\n");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 描述控制台
|
||||
* @param Console $console
|
||||
* @param array $options
|
||||
* @return void
|
||||
*/
|
||||
protected function describeConsole(Console $console, array $options = [])
|
||||
{
|
||||
$describedNamespace = isset($options['namespace']) ? $options['namespace'] : null;
|
||||
$description = new ConsoleDescription($console, $describedNamespace);
|
||||
|
||||
if (isset($options['raw_text']) && $options['raw_text']) {
|
||||
$width = $this->getColumnWidth($description->getCommands());
|
||||
|
||||
foreach ($description->getCommands() as $command) {
|
||||
$this->writeText(sprintf("%-${width}s %s", $command->getName(), $command->getDescription()), $options);
|
||||
$this->writeText("\n");
|
||||
}
|
||||
} else {
|
||||
if ('' != $help = $console->getHelp()) {
|
||||
$this->writeText("$help\n\n", $options);
|
||||
}
|
||||
|
||||
$this->writeText("<comment>Usage:</comment>\n", $options);
|
||||
$this->writeText(" command [options] [arguments]\n\n", $options);
|
||||
|
||||
$this->describeInputDefinition(new InputDefinition($console->getDefinition()->getOptions()), $options);
|
||||
|
||||
$this->writeText("\n");
|
||||
$this->writeText("\n");
|
||||
|
||||
$width = $this->getColumnWidth($description->getCommands());
|
||||
|
||||
if ($describedNamespace) {
|
||||
$this->writeText(sprintf('<comment>Available commands for the "%s" namespace:</comment>', $describedNamespace), $options);
|
||||
} else {
|
||||
$this->writeText('<comment>Available commands:</comment>', $options);
|
||||
}
|
||||
|
||||
// add commands by namespace
|
||||
foreach ($description->getNamespaces() as $namespace) {
|
||||
if (!$describedNamespace && ConsoleDescription::GLOBAL_NAMESPACE !== $namespace['id']) {
|
||||
$this->writeText("\n");
|
||||
$this->writeText(' <comment>' . $namespace['id'] . '</comment>', $options);
|
||||
}
|
||||
|
||||
foreach ($namespace['commands'] as $name) {
|
||||
$this->writeText("\n");
|
||||
$spacingWidth = $width - strlen($name);
|
||||
$this->writeText(sprintf(" <info>%s</info>%s%s", $name, str_repeat(' ', $spacingWidth), $description->getCommand($name)
|
||||
->getDescription()), $options);
|
||||
}
|
||||
}
|
||||
|
||||
$this->writeText("\n");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
private function writeText($content, array $options = [])
|
||||
{
|
||||
$this->write(isset($options['raw_text'])
|
||||
&& $options['raw_text'] ? strip_tags($content) : $content, isset($options['raw_output']) ? !$options['raw_output'] : true);
|
||||
}
|
||||
|
||||
/**
|
||||
* 格式化
|
||||
* @param mixed $default
|
||||
* @return string
|
||||
*/
|
||||
private function formatDefaultValue($default)
|
||||
{
|
||||
return json_encode($default, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param Command[] $commands
|
||||
* @return int
|
||||
*/
|
||||
private function getColumnWidth(array $commands)
|
||||
{
|
||||
$width = 0;
|
||||
foreach ($commands as $command) {
|
||||
$width = strlen($command->getName()) > $width ? strlen($command->getName()) : $width;
|
||||
}
|
||||
|
||||
return $width + 2;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param InputOption[] $options
|
||||
* @return int
|
||||
*/
|
||||
private function calculateTotalWidthForOptions($options)
|
||||
{
|
||||
$totalWidth = 0;
|
||||
foreach ($options as $option) {
|
||||
$nameLength = 4 + strlen($option->getName()) + 2; // - + shortcut + , + whitespace + name + --
|
||||
|
||||
if ($option->acceptValue()) {
|
||||
$valueLength = 1 + strlen($option->getName()); // = + value
|
||||
$valueLength += $option->isValueOptional() ? 2 : 0; // [ + ]
|
||||
|
||||
$nameLength += $valueLength;
|
||||
}
|
||||
$totalWidth = max($totalWidth, $nameLength);
|
||||
}
|
||||
|
||||
return $totalWidth;
|
||||
}
|
||||
}
|
198
thinkphp/library/think/console/output/Formatter.php
Normal file
198
thinkphp/library/think/console/output/Formatter.php
Normal file
@ -0,0 +1,198 @@
|
||||
<?php
|
||||
// +----------------------------------------------------------------------
|
||||
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
|
||||
// +----------------------------------------------------------------------
|
||||
// | Copyright (c) 2006~2015 http://thinkphp.cn All rights reserved.
|
||||
// +----------------------------------------------------------------------
|
||||
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
|
||||
// +----------------------------------------------------------------------
|
||||
// | Author: yunwuxin <448901948@qq.com>
|
||||
// +----------------------------------------------------------------------
|
||||
namespace think\console\output;
|
||||
|
||||
use think\console\output\formatter\Stack as StyleStack;
|
||||
use think\console\output\formatter\Style;
|
||||
|
||||
class Formatter
|
||||
{
|
||||
|
||||
private $decorated = false;
|
||||
private $styles = [];
|
||||
private $styleStack;
|
||||
|
||||
/**
|
||||
* 转义
|
||||
* @param string $text
|
||||
* @return string
|
||||
*/
|
||||
public static function escape($text)
|
||||
{
|
||||
return preg_replace('/([^\\\\]?)</is', '$1\\<', $text);
|
||||
}
|
||||
|
||||
/**
|
||||
* 初始化命令行输出格式
|
||||
*/
|
||||
public function __construct()
|
||||
{
|
||||
$this->setStyle('error', new Style('white', 'red'));
|
||||
$this->setStyle('info', new Style('green'));
|
||||
$this->setStyle('comment', new Style('yellow'));
|
||||
$this->setStyle('question', new Style('black', 'cyan'));
|
||||
$this->setStyle('highlight', new Style('red'));
|
||||
$this->setStyle('warning', new Style('black', 'yellow'));
|
||||
|
||||
$this->styleStack = new StyleStack();
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置外观标识
|
||||
* @param bool $decorated 是否美化文字
|
||||
*/
|
||||
public function setDecorated($decorated)
|
||||
{
|
||||
$this->decorated = (bool) $decorated;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取外观标识
|
||||
* @return bool
|
||||
*/
|
||||
public function isDecorated()
|
||||
{
|
||||
return $this->decorated;
|
||||
}
|
||||
|
||||
/**
|
||||
* 添加一个新样式
|
||||
* @param string $name 样式名
|
||||
* @param Style $style 样式实例
|
||||
*/
|
||||
public function setStyle($name, Style $style)
|
||||
{
|
||||
$this->styles[strtolower($name)] = $style;
|
||||
}
|
||||
|
||||
/**
|
||||
* 是否有这个样式
|
||||
* @param string $name
|
||||
* @return bool
|
||||
*/
|
||||
public function hasStyle($name)
|
||||
{
|
||||
return isset($this->styles[strtolower($name)]);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取样式
|
||||
* @param string $name
|
||||
* @return Style
|
||||
* @throws \InvalidArgumentException
|
||||
*/
|
||||
public function getStyle($name)
|
||||
{
|
||||
if (!$this->hasStyle($name)) {
|
||||
throw new \InvalidArgumentException(sprintf('Undefined style: %s', $name));
|
||||
}
|
||||
|
||||
return $this->styles[strtolower($name)];
|
||||
}
|
||||
|
||||
/**
|
||||
* 使用所给的样式格式化文字
|
||||
* @param string $message 文字
|
||||
* @return string
|
||||
*/
|
||||
public function format($message)
|
||||
{
|
||||
$offset = 0;
|
||||
$output = '';
|
||||
$tagRegex = '[a-z][a-z0-9_=;-]*';
|
||||
preg_match_all("#<(($tagRegex) | /($tagRegex)?)>#isx", $message, $matches, PREG_OFFSET_CAPTURE);
|
||||
foreach ($matches[0] as $i => $match) {
|
||||
$pos = $match[1];
|
||||
$text = $match[0];
|
||||
|
||||
if (0 != $pos && '\\' == $message[$pos - 1]) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$output .= $this->applyCurrentStyle(substr($message, $offset, $pos - $offset));
|
||||
$offset = $pos + strlen($text);
|
||||
|
||||
if ($open = '/' != $text[1]) {
|
||||
$tag = $matches[1][$i][0];
|
||||
} else {
|
||||
$tag = isset($matches[3][$i][0]) ? $matches[3][$i][0] : '';
|
||||
}
|
||||
|
||||
if (!$open && !$tag) {
|
||||
// </>
|
||||
$this->styleStack->pop();
|
||||
} elseif (false === $style = $this->createStyleFromString(strtolower($tag))) {
|
||||
$output .= $this->applyCurrentStyle($text);
|
||||
} elseif ($open) {
|
||||
$this->styleStack->push($style);
|
||||
} else {
|
||||
$this->styleStack->pop($style);
|
||||
}
|
||||
}
|
||||
|
||||
$output .= $this->applyCurrentStyle(substr($message, $offset));
|
||||
|
||||
return str_replace('\\<', '<', $output);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return StyleStack
|
||||
*/
|
||||
public function getStyleStack()
|
||||
{
|
||||
return $this->styleStack;
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据字符串创建新的样式实例
|
||||
* @param string $string
|
||||
* @return Style|bool
|
||||
*/
|
||||
private function createStyleFromString($string)
|
||||
{
|
||||
if (isset($this->styles[$string])) {
|
||||
return $this->styles[$string];
|
||||
}
|
||||
|
||||
if (!preg_match_all('/([^=]+)=([^;]+)(;|$)/', strtolower($string), $matches, PREG_SET_ORDER)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$style = new Style();
|
||||
foreach ($matches as $match) {
|
||||
array_shift($match);
|
||||
|
||||
if ('fg' == $match[0]) {
|
||||
$style->setForeground($match[1]);
|
||||
} elseif ('bg' == $match[0]) {
|
||||
$style->setBackground($match[1]);
|
||||
} else {
|
||||
try {
|
||||
$style->setOption($match[1]);
|
||||
} catch (\InvalidArgumentException $e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $style;
|
||||
}
|
||||
|
||||
/**
|
||||
* 从堆栈应用样式到文字
|
||||
* @param string $text 文字
|
||||
* @return string
|
||||
*/
|
||||
private function applyCurrentStyle($text)
|
||||
{
|
||||
return $this->isDecorated() && strlen($text) > 0 ? $this->styleStack->getCurrent()->apply($text) : $text;
|
||||
}
|
||||
}
|
211
thinkphp/library/think/console/output/Question.php
Normal file
211
thinkphp/library/think/console/output/Question.php
Normal file
@ -0,0 +1,211 @@
|
||||
<?php
|
||||
// +----------------------------------------------------------------------
|
||||
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
|
||||
// +----------------------------------------------------------------------
|
||||
// | Copyright (c) 2006~2015 http://thinkphp.cn All rights reserved.
|
||||
// +----------------------------------------------------------------------
|
||||
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
|
||||
// +----------------------------------------------------------------------
|
||||
// | Author: yunwuxin <448901948@qq.com>
|
||||
// +----------------------------------------------------------------------
|
||||
|
||||
namespace think\console\output;
|
||||
|
||||
class Question
|
||||
{
|
||||
|
||||
private $question;
|
||||
private $attempts;
|
||||
private $hidden = false;
|
||||
private $hiddenFallback = true;
|
||||
private $autocompleterValues;
|
||||
private $validator;
|
||||
private $default;
|
||||
private $normalizer;
|
||||
|
||||
/**
|
||||
* 构造方法
|
||||
* @param string $question 问题
|
||||
* @param mixed $default 默认答案
|
||||
*/
|
||||
public function __construct($question, $default = null)
|
||||
{
|
||||
$this->question = $question;
|
||||
$this->default = $default;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取问题
|
||||
* @return string
|
||||
*/
|
||||
public function getQuestion()
|
||||
{
|
||||
return $this->question;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取默认答案
|
||||
* @return mixed
|
||||
*/
|
||||
public function getDefault()
|
||||
{
|
||||
return $this->default;
|
||||
}
|
||||
|
||||
/**
|
||||
* 是否隐藏答案
|
||||
* @return bool
|
||||
*/
|
||||
public function isHidden()
|
||||
{
|
||||
return $this->hidden;
|
||||
}
|
||||
|
||||
/**
|
||||
* 隐藏答案
|
||||
* @param bool $hidden
|
||||
* @return Question
|
||||
*/
|
||||
public function setHidden($hidden)
|
||||
{
|
||||
if ($this->autocompleterValues) {
|
||||
throw new \LogicException('A hidden question cannot use the autocompleter.');
|
||||
}
|
||||
|
||||
$this->hidden = (bool) $hidden;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* 不能被隐藏是否撤销
|
||||
* @return bool
|
||||
*/
|
||||
public function isHiddenFallback()
|
||||
{
|
||||
return $this->hiddenFallback;
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置不能被隐藏的时候的操作
|
||||
* @param bool $fallback
|
||||
* @return Question
|
||||
*/
|
||||
public function setHiddenFallback($fallback)
|
||||
{
|
||||
$this->hiddenFallback = (bool) $fallback;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取自动完成
|
||||
* @return null|array|\Traversable
|
||||
*/
|
||||
public function getAutocompleterValues()
|
||||
{
|
||||
return $this->autocompleterValues;
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置自动完成的值
|
||||
* @param null|array|\Traversable $values
|
||||
* @return Question
|
||||
* @throws \InvalidArgumentException
|
||||
* @throws \LogicException
|
||||
*/
|
||||
public function setAutocompleterValues($values)
|
||||
{
|
||||
if (is_array($values) && $this->isAssoc($values)) {
|
||||
$values = array_merge(array_keys($values), array_values($values));
|
||||
}
|
||||
|
||||
if (null !== $values && !is_array($values)) {
|
||||
if (!$values instanceof \Traversable || $values instanceof \Countable) {
|
||||
throw new \InvalidArgumentException('Autocompleter values can be either an array, `null` or an object implementing both `Countable` and `Traversable` interfaces.');
|
||||
}
|
||||
}
|
||||
|
||||
if ($this->hidden) {
|
||||
throw new \LogicException('A hidden question cannot use the autocompleter.');
|
||||
}
|
||||
|
||||
$this->autocompleterValues = $values;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置答案的验证器
|
||||
* @param null|callable $validator
|
||||
* @return Question The current instance
|
||||
*/
|
||||
public function setValidator($validator)
|
||||
{
|
||||
$this->validator = $validator;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取验证器
|
||||
* @return null|callable
|
||||
*/
|
||||
public function getValidator()
|
||||
{
|
||||
return $this->validator;
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置最大重试次数
|
||||
* @param null|int $attempts
|
||||
* @return Question
|
||||
* @throws \InvalidArgumentException
|
||||
*/
|
||||
public function setMaxAttempts($attempts)
|
||||
{
|
||||
if (null !== $attempts && $attempts < 1) {
|
||||
throw new \InvalidArgumentException('Maximum number of attempts must be a positive value.');
|
||||
}
|
||||
|
||||
$this->attempts = $attempts;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取最大重试次数
|
||||
* @return null|int
|
||||
*/
|
||||
public function getMaxAttempts()
|
||||
{
|
||||
return $this->attempts;
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置响应的回调
|
||||
* @param string|\Closure $normalizer
|
||||
* @return Question
|
||||
*/
|
||||
public function setNormalizer($normalizer)
|
||||
{
|
||||
$this->normalizer = $normalizer;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取响应回调
|
||||
* The normalizer can ba a callable (a string), a closure or a class implementing __invoke.
|
||||
* @return string|\Closure
|
||||
*/
|
||||
public function getNormalizer()
|
||||
{
|
||||
return $this->normalizer;
|
||||
}
|
||||
|
||||
protected function isAssoc($array)
|
||||
{
|
||||
return (bool) count(array_filter(array_keys($array), 'is_string'));
|
||||
}
|
||||
}
|
149
thinkphp/library/think/console/output/descriptor/Console.php
Normal file
149
thinkphp/library/think/console/output/descriptor/Console.php
Normal file
@ -0,0 +1,149 @@
|
||||
<?php
|
||||
// +----------------------------------------------------------------------
|
||||
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
|
||||
// +----------------------------------------------------------------------
|
||||
// | Copyright (c) 2006~2015 http://thinkphp.cn All rights reserved.
|
||||
// +----------------------------------------------------------------------
|
||||
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
|
||||
// +----------------------------------------------------------------------
|
||||
// | Author: yunwuxin <448901948@qq.com>
|
||||
// +----------------------------------------------------------------------
|
||||
|
||||
namespace think\console\output\descriptor;
|
||||
|
||||
use think\Console as ThinkConsole;
|
||||
use think\console\Command;
|
||||
|
||||
class Console
|
||||
{
|
||||
|
||||
const GLOBAL_NAMESPACE = '_global';
|
||||
|
||||
/**
|
||||
* @var ThinkConsole
|
||||
*/
|
||||
private $console;
|
||||
|
||||
/**
|
||||
* @var null|string
|
||||
*/
|
||||
private $namespace;
|
||||
|
||||
/**
|
||||
* @var array
|
||||
*/
|
||||
private $namespaces;
|
||||
|
||||
/**
|
||||
* @var Command[]
|
||||
*/
|
||||
private $commands;
|
||||
|
||||
/**
|
||||
* @var Command[]
|
||||
*/
|
||||
private $aliases;
|
||||
|
||||
/**
|
||||
* 构造方法
|
||||
* @param ThinkConsole $console
|
||||
* @param string|null $namespace
|
||||
*/
|
||||
public function __construct(ThinkConsole $console, $namespace = null)
|
||||
{
|
||||
$this->console = $console;
|
||||
$this->namespace = $namespace;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array
|
||||
*/
|
||||
public function getNamespaces()
|
||||
{
|
||||
if (null === $this->namespaces) {
|
||||
$this->inspectConsole();
|
||||
}
|
||||
|
||||
return $this->namespaces;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Command[]
|
||||
*/
|
||||
public function getCommands()
|
||||
{
|
||||
if (null === $this->commands) {
|
||||
$this->inspectConsole();
|
||||
}
|
||||
|
||||
return $this->commands;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $name
|
||||
* @return Command
|
||||
* @throws \InvalidArgumentException
|
||||
*/
|
||||
public function getCommand($name)
|
||||
{
|
||||
if (!isset($this->commands[$name]) && !isset($this->aliases[$name])) {
|
||||
throw new \InvalidArgumentException(sprintf('Command %s does not exist.', $name));
|
||||
}
|
||||
|
||||
return isset($this->commands[$name]) ? $this->commands[$name] : $this->aliases[$name];
|
||||
}
|
||||
|
||||
private function inspectConsole()
|
||||
{
|
||||
$this->commands = [];
|
||||
$this->namespaces = [];
|
||||
|
||||
$all = $this->console->all($this->namespace ? $this->console->findNamespace($this->namespace) : null);
|
||||
foreach ($this->sortCommands($all) as $namespace => $commands) {
|
||||
$names = [];
|
||||
|
||||
/** @var Command $command */
|
||||
foreach ($commands as $name => $command) {
|
||||
if (!$command->getName()) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($command->getName() === $name) {
|
||||
$this->commands[$name] = $command;
|
||||
} else {
|
||||
$this->aliases[$name] = $command;
|
||||
}
|
||||
|
||||
$names[] = $name;
|
||||
}
|
||||
|
||||
$this->namespaces[$namespace] = ['id' => $namespace, 'commands' => $names];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array $commands
|
||||
* @return array
|
||||
*/
|
||||
private function sortCommands(array $commands)
|
||||
{
|
||||
$namespacedCommands = [];
|
||||
foreach ($commands as $name => $command) {
|
||||
$key = $this->console->extractNamespace($name, 1);
|
||||
if (!$key) {
|
||||
$key = self::GLOBAL_NAMESPACE;
|
||||
}
|
||||
|
||||
$namespacedCommands[$key][$name] = $command;
|
||||
}
|
||||
ksort($namespacedCommands);
|
||||
|
||||
foreach ($namespacedCommands as &$commandsSet) {
|
||||
ksort($commandsSet);
|
||||
}
|
||||
// unset reference to keep scope clear
|
||||
unset($commandsSet);
|
||||
|
||||
return $namespacedCommands;
|
||||
}
|
||||
}
|
52
thinkphp/library/think/console/output/driver/Buffer.php
Normal file
52
thinkphp/library/think/console/output/driver/Buffer.php
Normal file
@ -0,0 +1,52 @@
|
||||
<?php
|
||||
// +----------------------------------------------------------------------
|
||||
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
|
||||
// +----------------------------------------------------------------------
|
||||
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
|
||||
// +----------------------------------------------------------------------
|
||||
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
|
||||
// +----------------------------------------------------------------------
|
||||
// | Author: yunwuxin <448901948@qq.com>
|
||||
// +----------------------------------------------------------------------
|
||||
|
||||
namespace think\console\output\driver;
|
||||
|
||||
use think\console\Output;
|
||||
|
||||
class Buffer
|
||||
{
|
||||
/**
|
||||
* @var string
|
||||
*/
|
||||
private $buffer = '';
|
||||
|
||||
public function __construct(Output $output)
|
||||
{
|
||||
// do nothing
|
||||
}
|
||||
|
||||
public function fetch()
|
||||
{
|
||||
$content = $this->buffer;
|
||||
$this->buffer = '';
|
||||
return $content;
|
||||
}
|
||||
|
||||
public function write($messages, $newline = false, $options = Output::OUTPUT_NORMAL)
|
||||
{
|
||||
$messages = (array) $messages;
|
||||
|
||||
foreach ($messages as $message) {
|
||||
$this->buffer .= $message;
|
||||
}
|
||||
if ($newline) {
|
||||
$this->buffer .= "\n";
|
||||
}
|
||||
}
|
||||
|
||||
public function renderException(\Exception $e)
|
||||
{
|
||||
// do nothing
|
||||
}
|
||||
|
||||
}
|
373
thinkphp/library/think/console/output/driver/Console.php
Normal file
373
thinkphp/library/think/console/output/driver/Console.php
Normal file
@ -0,0 +1,373 @@
|
||||
<?php
|
||||
// +----------------------------------------------------------------------
|
||||
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
|
||||
// +----------------------------------------------------------------------
|
||||
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
|
||||
// +----------------------------------------------------------------------
|
||||
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
|
||||
// +----------------------------------------------------------------------
|
||||
// | Author: yunwuxin <448901948@qq.com>
|
||||
// +----------------------------------------------------------------------
|
||||
|
||||
namespace think\console\output\driver;
|
||||
|
||||
use think\console\Output;
|
||||
use think\console\output\Formatter;
|
||||
|
||||
class Console
|
||||
{
|
||||
|
||||
/** @var Resource */
|
||||
private $stdout;
|
||||
|
||||
/** @var Formatter */
|
||||
private $formatter;
|
||||
|
||||
private $terminalDimensions;
|
||||
|
||||
/** @var Output */
|
||||
private $output;
|
||||
|
||||
public function __construct(Output $output)
|
||||
{
|
||||
$this->output = $output;
|
||||
$this->formatter = new Formatter();
|
||||
$this->stdout = $this->openOutputStream();
|
||||
$decorated = $this->hasColorSupport($this->stdout);
|
||||
$this->formatter->setDecorated($decorated);
|
||||
}
|
||||
|
||||
public function getFormatter()
|
||||
{
|
||||
return $this->formatter;
|
||||
}
|
||||
|
||||
public function setDecorated($decorated)
|
||||
{
|
||||
$this->formatter->setDecorated($decorated);
|
||||
}
|
||||
|
||||
public function write($messages, $newline = false, $type = Output::OUTPUT_NORMAL, $stream = null)
|
||||
{
|
||||
if (Output::VERBOSITY_QUIET === $this->output->getVerbosity()) {
|
||||
return;
|
||||
}
|
||||
|
||||
$messages = (array) $messages;
|
||||
|
||||
foreach ($messages as $message) {
|
||||
switch ($type) {
|
||||
case Output::OUTPUT_NORMAL:
|
||||
$message = $this->formatter->format($message);
|
||||
break;
|
||||
case Output::OUTPUT_RAW:
|
||||
break;
|
||||
case Output::OUTPUT_PLAIN:
|
||||
$message = strip_tags($this->formatter->format($message));
|
||||
break;
|
||||
default:
|
||||
throw new \InvalidArgumentException(sprintf('Unknown output type given (%s)', $type));
|
||||
}
|
||||
|
||||
$this->doWrite($message, $newline, $stream);
|
||||
}
|
||||
}
|
||||
|
||||
public function renderException(\Exception $e)
|
||||
{
|
||||
$stderr = $this->openErrorStream();
|
||||
$decorated = $this->hasColorSupport($stderr);
|
||||
$this->formatter->setDecorated($decorated);
|
||||
|
||||
do {
|
||||
$title = sprintf(' [%s] ', get_class($e));
|
||||
|
||||
$len = $this->stringWidth($title);
|
||||
|
||||
$width = $this->getTerminalWidth() ? $this->getTerminalWidth() - 1 : PHP_INT_MAX;
|
||||
|
||||
if (defined('HHVM_VERSION') && $width > 1 << 31) {
|
||||
$width = 1 << 31;
|
||||
}
|
||||
$lines = [];
|
||||
foreach (preg_split('/\r?\n/', $e->getMessage()) as $line) {
|
||||
foreach ($this->splitStringByWidth($line, $width - 4) as $line) {
|
||||
|
||||
$lineLength = $this->stringWidth(preg_replace('/\[[^m]*m/', '', $line)) + 4;
|
||||
$lines[] = [$line, $lineLength];
|
||||
|
||||
$len = max($lineLength, $len);
|
||||
}
|
||||
}
|
||||
|
||||
$messages = ['', ''];
|
||||
$messages[] = $emptyLine = sprintf('<error>%s</error>', str_repeat(' ', $len));
|
||||
$messages[] = sprintf('<error>%s%s</error>', $title, str_repeat(' ', max(0, $len - $this->stringWidth($title))));
|
||||
foreach ($lines as $line) {
|
||||
$messages[] = sprintf('<error> %s %s</error>', $line[0], str_repeat(' ', $len - $line[1]));
|
||||
}
|
||||
$messages[] = $emptyLine;
|
||||
$messages[] = '';
|
||||
$messages[] = '';
|
||||
|
||||
$this->write($messages, true, Output::OUTPUT_NORMAL, $stderr);
|
||||
|
||||
if (Output::VERBOSITY_VERBOSE <= $this->output->getVerbosity()) {
|
||||
$this->write('<comment>Exception trace:</comment>', true, Output::OUTPUT_NORMAL, $stderr);
|
||||
|
||||
// exception related properties
|
||||
$trace = $e->getTrace();
|
||||
array_unshift($trace, [
|
||||
'function' => '',
|
||||
'file' => $e->getFile() !== null ? $e->getFile() : 'n/a',
|
||||
'line' => $e->getLine() !== null ? $e->getLine() : 'n/a',
|
||||
'args' => [],
|
||||
]);
|
||||
|
||||
for ($i = 0, $count = count($trace); $i < $count; ++$i) {
|
||||
$class = isset($trace[$i]['class']) ? $trace[$i]['class'] : '';
|
||||
$type = isset($trace[$i]['type']) ? $trace[$i]['type'] : '';
|
||||
$function = $trace[$i]['function'];
|
||||
$file = isset($trace[$i]['file']) ? $trace[$i]['file'] : 'n/a';
|
||||
$line = isset($trace[$i]['line']) ? $trace[$i]['line'] : 'n/a';
|
||||
|
||||
$this->write(sprintf(' %s%s%s() at <info>%s:%s</info>', $class, $type, $function, $file, $line), true, Output::OUTPUT_NORMAL, $stderr);
|
||||
}
|
||||
|
||||
$this->write('', true, Output::OUTPUT_NORMAL, $stderr);
|
||||
$this->write('', true, Output::OUTPUT_NORMAL, $stderr);
|
||||
}
|
||||
} while ($e = $e->getPrevious());
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取终端宽度
|
||||
* @return int|null
|
||||
*/
|
||||
protected function getTerminalWidth()
|
||||
{
|
||||
$dimensions = $this->getTerminalDimensions();
|
||||
|
||||
return $dimensions[0];
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取终端高度
|
||||
* @return int|null
|
||||
*/
|
||||
protected function getTerminalHeight()
|
||||
{
|
||||
$dimensions = $this->getTerminalDimensions();
|
||||
|
||||
return $dimensions[1];
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取当前终端的尺寸
|
||||
* @return array
|
||||
*/
|
||||
public function getTerminalDimensions()
|
||||
{
|
||||
if ($this->terminalDimensions) {
|
||||
return $this->terminalDimensions;
|
||||
}
|
||||
|
||||
if ('\\' === DS) {
|
||||
if (preg_match('/^(\d+)x\d+ \(\d+x(\d+)\)$/', trim(getenv('ANSICON')), $matches)) {
|
||||
return [(int) $matches[1], (int) $matches[2]];
|
||||
}
|
||||
if (preg_match('/^(\d+)x(\d+)$/', $this->getMode(), $matches)) {
|
||||
return [(int) $matches[1], (int) $matches[2]];
|
||||
}
|
||||
}
|
||||
|
||||
if ($sttyString = $this->getSttyColumns()) {
|
||||
if (preg_match('/rows.(\d+);.columns.(\d+);/i', $sttyString, $matches)) {
|
||||
return [(int) $matches[2], (int) $matches[1]];
|
||||
}
|
||||
if (preg_match('/;.(\d+).rows;.(\d+).columns/i', $sttyString, $matches)) {
|
||||
return [(int) $matches[2], (int) $matches[1]];
|
||||
}
|
||||
}
|
||||
|
||||
return [null, null];
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取stty列数
|
||||
* @return string
|
||||
*/
|
||||
private function getSttyColumns()
|
||||
{
|
||||
if (!function_exists('proc_open')) {
|
||||
return;
|
||||
}
|
||||
|
||||
$descriptorspec = [1 => ['pipe', 'w'], 2 => ['pipe', 'w']];
|
||||
$process = proc_open('stty -a | grep columns', $descriptorspec, $pipes, null, null, ['suppress_errors' => true]);
|
||||
if (is_resource($process)) {
|
||||
$info = stream_get_contents($pipes[1]);
|
||||
fclose($pipes[1]);
|
||||
fclose($pipes[2]);
|
||||
proc_close($process);
|
||||
|
||||
return $info;
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取终端模式
|
||||
* @return string <width>x<height> 或 null
|
||||
*/
|
||||
private function getMode()
|
||||
{
|
||||
if (!function_exists('proc_open')) {
|
||||
return;
|
||||
}
|
||||
|
||||
$descriptorspec = [1 => ['pipe', 'w'], 2 => ['pipe', 'w']];
|
||||
$process = proc_open('mode CON', $descriptorspec, $pipes, null, null, ['suppress_errors' => true]);
|
||||
if (is_resource($process)) {
|
||||
$info = stream_get_contents($pipes[1]);
|
||||
fclose($pipes[1]);
|
||||
fclose($pipes[2]);
|
||||
proc_close($process);
|
||||
|
||||
if (preg_match('/--------+\r?\n.+?(\d+)\r?\n.+?(\d+)\r?\n/', $info, $matches)) {
|
||||
return $matches[2] . 'x' . $matches[1];
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
private function stringWidth($string)
|
||||
{
|
||||
if (!function_exists('mb_strwidth')) {
|
||||
return strlen($string);
|
||||
}
|
||||
|
||||
if (false === $encoding = mb_detect_encoding($string)) {
|
||||
return strlen($string);
|
||||
}
|
||||
|
||||
return mb_strwidth($string, $encoding);
|
||||
}
|
||||
|
||||
private function splitStringByWidth($string, $width)
|
||||
{
|
||||
if (!function_exists('mb_strwidth')) {
|
||||
return str_split($string, $width);
|
||||
}
|
||||
|
||||
if (false === $encoding = mb_detect_encoding($string)) {
|
||||
return str_split($string, $width);
|
||||
}
|
||||
|
||||
$utf8String = mb_convert_encoding($string, 'utf8', $encoding);
|
||||
$lines = [];
|
||||
$line = '';
|
||||
foreach (preg_split('//u', $utf8String) as $char) {
|
||||
if (mb_strwidth($line . $char, 'utf8') <= $width) {
|
||||
$line .= $char;
|
||||
continue;
|
||||
}
|
||||
$lines[] = str_pad($line, $width);
|
||||
$line = $char;
|
||||
}
|
||||
if (strlen($line)) {
|
||||
$lines[] = count($lines) ? str_pad($line, $width) : $line;
|
||||
}
|
||||
|
||||
mb_convert_variables($encoding, 'utf8', $lines);
|
||||
|
||||
return $lines;
|
||||
}
|
||||
|
||||
private function isRunningOS400()
|
||||
{
|
||||
$checks = [
|
||||
function_exists('php_uname') ? php_uname('s') : '',
|
||||
getenv('OSTYPE'),
|
||||
PHP_OS,
|
||||
];
|
||||
return false !== stripos(implode(';', $checks), 'OS400');
|
||||
}
|
||||
|
||||
/**
|
||||
* 当前环境是否支持写入控制台输出到stdout.
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
protected function hasStdoutSupport()
|
||||
{
|
||||
return false === $this->isRunningOS400();
|
||||
}
|
||||
|
||||
/**
|
||||
* 当前环境是否支持写入控制台输出到stderr.
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
protected function hasStderrSupport()
|
||||
{
|
||||
return false === $this->isRunningOS400();
|
||||
}
|
||||
|
||||
/**
|
||||
* @return resource
|
||||
*/
|
||||
private function openOutputStream()
|
||||
{
|
||||
if (!$this->hasStdoutSupport()) {
|
||||
return fopen('php://output', 'w');
|
||||
}
|
||||
return @fopen('php://stdout', 'w') ?: fopen('php://output', 'w');
|
||||
}
|
||||
|
||||
/**
|
||||
* @return resource
|
||||
*/
|
||||
private function openErrorStream()
|
||||
{
|
||||
return fopen($this->hasStderrSupport() ? 'php://stderr' : 'php://output', 'w');
|
||||
}
|
||||
|
||||
/**
|
||||
* 将消息写入到输出。
|
||||
* @param string $message 消息
|
||||
* @param bool $newline 是否另起一行
|
||||
* @param null $stream
|
||||
*/
|
||||
protected function doWrite($message, $newline, $stream = null)
|
||||
{
|
||||
if (null === $stream) {
|
||||
$stream = $this->stdout;
|
||||
}
|
||||
if (false === @fwrite($stream, $message . ($newline ? PHP_EOL : ''))) {
|
||||
throw new \RuntimeException('Unable to write output.');
|
||||
}
|
||||
|
||||
fflush($stream);
|
||||
}
|
||||
|
||||
/**
|
||||
* 是否支持着色
|
||||
* @param $stream
|
||||
* @return bool
|
||||
*/
|
||||
protected function hasColorSupport($stream)
|
||||
{
|
||||
if (DIRECTORY_SEPARATOR === '\\') {
|
||||
return
|
||||
'10.0.10586' === PHP_WINDOWS_VERSION_MAJOR . '.' . PHP_WINDOWS_VERSION_MINOR . '.' . PHP_WINDOWS_VERSION_BUILD
|
||||
|| false !== getenv('ANSICON')
|
||||
|| 'ON' === getenv('ConEmuANSI')
|
||||
|| 'xterm' === getenv('TERM');
|
||||
}
|
||||
|
||||
return function_exists('posix_isatty') && @posix_isatty($stream);
|
||||
}
|
||||
|
||||
}
|
33
thinkphp/library/think/console/output/driver/Nothing.php
Normal file
33
thinkphp/library/think/console/output/driver/Nothing.php
Normal file
@ -0,0 +1,33 @@
|
||||
<?php
|
||||
// +----------------------------------------------------------------------
|
||||
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
|
||||
// +----------------------------------------------------------------------
|
||||
// | Copyright (c) 2006~2015 http://thinkphp.cn All rights reserved.
|
||||
// +----------------------------------------------------------------------
|
||||
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
|
||||
// +----------------------------------------------------------------------
|
||||
// | Author: yunwuxin <448901948@qq.com>
|
||||
// +----------------------------------------------------------------------
|
||||
|
||||
namespace think\console\output\driver;
|
||||
|
||||
use think\console\Output;
|
||||
|
||||
class Nothing
|
||||
{
|
||||
|
||||
public function __construct(Output $output)
|
||||
{
|
||||
// do nothing
|
||||
}
|
||||
|
||||
public function write($messages, $newline = false, $options = Output::OUTPUT_NORMAL)
|
||||
{
|
||||
// do nothing
|
||||
}
|
||||
|
||||
public function renderException(\Exception $e)
|
||||
{
|
||||
// do nothing
|
||||
}
|
||||
}
|
116
thinkphp/library/think/console/output/formatter/Stack.php
Normal file
116
thinkphp/library/think/console/output/formatter/Stack.php
Normal file
@ -0,0 +1,116 @@
|
||||
<?php
|
||||
// +----------------------------------------------------------------------
|
||||
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
|
||||
// +----------------------------------------------------------------------
|
||||
// | Copyright (c) 2006~2015 http://thinkphp.cn All rights reserved.
|
||||
// +----------------------------------------------------------------------
|
||||
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
|
||||
// +----------------------------------------------------------------------
|
||||
// | Author: yunwuxin <448901948@qq.com>
|
||||
// +----------------------------------------------------------------------
|
||||
|
||||
namespace think\console\output\formatter;
|
||||
|
||||
class Stack
|
||||
{
|
||||
|
||||
/**
|
||||
* @var Style[]
|
||||
*/
|
||||
private $styles;
|
||||
|
||||
/**
|
||||
* @var Style
|
||||
*/
|
||||
private $emptyStyle;
|
||||
|
||||
/**
|
||||
* 构造方法
|
||||
* @param Style|null $emptyStyle
|
||||
*/
|
||||
public function __construct(Style $emptyStyle = null)
|
||||
{
|
||||
$this->emptyStyle = $emptyStyle ?: new Style();
|
||||
$this->reset();
|
||||
}
|
||||
|
||||
/**
|
||||
* 重置堆栈
|
||||
*/
|
||||
public function reset()
|
||||
{
|
||||
$this->styles = [];
|
||||
}
|
||||
|
||||
/**
|
||||
* 推一个样式进入堆栈
|
||||
* @param Style $style
|
||||
*/
|
||||
public function push(Style $style)
|
||||
{
|
||||
$this->styles[] = $style;
|
||||
}
|
||||
|
||||
/**
|
||||
* 从堆栈中弹出一个样式
|
||||
* @param Style|null $style
|
||||
* @return Style
|
||||
* @throws \InvalidArgumentException
|
||||
*/
|
||||
public function pop(Style $style = null)
|
||||
{
|
||||
if (empty($this->styles)) {
|
||||
return $this->emptyStyle;
|
||||
}
|
||||
|
||||
if (null === $style) {
|
||||
return array_pop($this->styles);
|
||||
}
|
||||
|
||||
/**
|
||||
* @var int $index
|
||||
* @var Style $stackedStyle
|
||||
*/
|
||||
foreach (array_reverse($this->styles, true) as $index => $stackedStyle) {
|
||||
if ($style->apply('') === $stackedStyle->apply('')) {
|
||||
$this->styles = array_slice($this->styles, 0, $index);
|
||||
|
||||
return $stackedStyle;
|
||||
}
|
||||
}
|
||||
|
||||
throw new \InvalidArgumentException('Incorrectly nested style tag found.');
|
||||
}
|
||||
|
||||
/**
|
||||
* 计算堆栈的当前样式。
|
||||
* @return Style
|
||||
*/
|
||||
public function getCurrent()
|
||||
{
|
||||
if (empty($this->styles)) {
|
||||
return $this->emptyStyle;
|
||||
}
|
||||
|
||||
return $this->styles[count($this->styles) - 1];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param Style $emptyStyle
|
||||
* @return Stack
|
||||
*/
|
||||
public function setEmptyStyle(Style $emptyStyle)
|
||||
{
|
||||
$this->emptyStyle = $emptyStyle;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Style
|
||||
*/
|
||||
public function getEmptyStyle()
|
||||
{
|
||||
return $this->emptyStyle;
|
||||
}
|
||||
}
|
189
thinkphp/library/think/console/output/formatter/Style.php
Normal file
189
thinkphp/library/think/console/output/formatter/Style.php
Normal file
@ -0,0 +1,189 @@
|
||||
<?php
|
||||
// +----------------------------------------------------------------------
|
||||
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
|
||||
// +----------------------------------------------------------------------
|
||||
// | Copyright (c) 2006~2015 http://thinkphp.cn All rights reserved.
|
||||
// +----------------------------------------------------------------------
|
||||
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
|
||||
// +----------------------------------------------------------------------
|
||||
// | Author: yunwuxin <448901948@qq.com>
|
||||
// +----------------------------------------------------------------------
|
||||
|
||||
namespace think\console\output\formatter;
|
||||
|
||||
class Style
|
||||
{
|
||||
|
||||
private static $availableForegroundColors = [
|
||||
'black' => ['set' => 30, 'unset' => 39],
|
||||
'red' => ['set' => 31, 'unset' => 39],
|
||||
'green' => ['set' => 32, 'unset' => 39],
|
||||
'yellow' => ['set' => 33, 'unset' => 39],
|
||||
'blue' => ['set' => 34, 'unset' => 39],
|
||||
'magenta' => ['set' => 35, 'unset' => 39],
|
||||
'cyan' => ['set' => 36, 'unset' => 39],
|
||||
'white' => ['set' => 37, 'unset' => 39],
|
||||
];
|
||||
private static $availableBackgroundColors = [
|
||||
'black' => ['set' => 40, 'unset' => 49],
|
||||
'red' => ['set' => 41, 'unset' => 49],
|
||||
'green' => ['set' => 42, 'unset' => 49],
|
||||
'yellow' => ['set' => 43, 'unset' => 49],
|
||||
'blue' => ['set' => 44, 'unset' => 49],
|
||||
'magenta' => ['set' => 45, 'unset' => 49],
|
||||
'cyan' => ['set' => 46, 'unset' => 49],
|
||||
'white' => ['set' => 47, 'unset' => 49],
|
||||
];
|
||||
private static $availableOptions = [
|
||||
'bold' => ['set' => 1, 'unset' => 22],
|
||||
'underscore' => ['set' => 4, 'unset' => 24],
|
||||
'blink' => ['set' => 5, 'unset' => 25],
|
||||
'reverse' => ['set' => 7, 'unset' => 27],
|
||||
'conceal' => ['set' => 8, 'unset' => 28],
|
||||
];
|
||||
|
||||
private $foreground;
|
||||
private $background;
|
||||
private $options = [];
|
||||
|
||||
/**
|
||||
* 初始化输出的样式
|
||||
* @param string|null $foreground 字体颜色
|
||||
* @param string|null $background 背景色
|
||||
* @param array $options 格式
|
||||
* @api
|
||||
*/
|
||||
public function __construct($foreground = null, $background = null, array $options = [])
|
||||
{
|
||||
if (null !== $foreground) {
|
||||
$this->setForeground($foreground);
|
||||
}
|
||||
if (null !== $background) {
|
||||
$this->setBackground($background);
|
||||
}
|
||||
if (count($options)) {
|
||||
$this->setOptions($options);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置字体颜色
|
||||
* @param string|null $color 颜色名
|
||||
* @throws \InvalidArgumentException
|
||||
* @api
|
||||
*/
|
||||
public function setForeground($color = null)
|
||||
{
|
||||
if (null === $color) {
|
||||
$this->foreground = null;
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (!isset(static::$availableForegroundColors[$color])) {
|
||||
throw new \InvalidArgumentException(sprintf('Invalid foreground color specified: "%s". Expected one of (%s)', $color, implode(', ', array_keys(static::$availableForegroundColors))));
|
||||
}
|
||||
|
||||
$this->foreground = static::$availableForegroundColors[$color];
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置背景色
|
||||
* @param string|null $color 颜色名
|
||||
* @throws \InvalidArgumentException
|
||||
* @api
|
||||
*/
|
||||
public function setBackground($color = null)
|
||||
{
|
||||
if (null === $color) {
|
||||
$this->background = null;
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (!isset(static::$availableBackgroundColors[$color])) {
|
||||
throw new \InvalidArgumentException(sprintf('Invalid background color specified: "%s". Expected one of (%s)', $color, implode(', ', array_keys(static::$availableBackgroundColors))));
|
||||
}
|
||||
|
||||
$this->background = static::$availableBackgroundColors[$color];
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置字体格式
|
||||
* @param string $option 格式名
|
||||
* @throws \InvalidArgumentException When the option name isn't defined
|
||||
* @api
|
||||
*/
|
||||
public function setOption($option)
|
||||
{
|
||||
if (!isset(static::$availableOptions[$option])) {
|
||||
throw new \InvalidArgumentException(sprintf('Invalid option specified: "%s". Expected one of (%s)', $option, implode(', ', array_keys(static::$availableOptions))));
|
||||
}
|
||||
|
||||
if (!in_array(static::$availableOptions[$option], $this->options)) {
|
||||
$this->options[] = static::$availableOptions[$option];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 重置字体格式
|
||||
* @param string $option 格式名
|
||||
* @throws \InvalidArgumentException
|
||||
*/
|
||||
public function unsetOption($option)
|
||||
{
|
||||
if (!isset(static::$availableOptions[$option])) {
|
||||
throw new \InvalidArgumentException(sprintf('Invalid option specified: "%s". Expected one of (%s)', $option, implode(', ', array_keys(static::$availableOptions))));
|
||||
}
|
||||
|
||||
$pos = array_search(static::$availableOptions[$option], $this->options);
|
||||
if (false !== $pos) {
|
||||
unset($this->options[$pos]);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量设置字体格式
|
||||
* @param array $options
|
||||
*/
|
||||
public function setOptions(array $options)
|
||||
{
|
||||
$this->options = [];
|
||||
|
||||
foreach ($options as $option) {
|
||||
$this->setOption($option);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 应用样式到文字
|
||||
* @param string $text 文字
|
||||
* @return string
|
||||
*/
|
||||
public function apply($text)
|
||||
{
|
||||
$setCodes = [];
|
||||
$unsetCodes = [];
|
||||
|
||||
if (null !== $this->foreground) {
|
||||
$setCodes[] = $this->foreground['set'];
|
||||
$unsetCodes[] = $this->foreground['unset'];
|
||||
}
|
||||
if (null !== $this->background) {
|
||||
$setCodes[] = $this->background['set'];
|
||||
$unsetCodes[] = $this->background['unset'];
|
||||
}
|
||||
if (count($this->options)) {
|
||||
foreach ($this->options as $option) {
|
||||
$setCodes[] = $option['set'];
|
||||
$unsetCodes[] = $option['unset'];
|
||||
}
|
||||
}
|
||||
|
||||
if (0 === count($setCodes)) {
|
||||
return $text;
|
||||
}
|
||||
|
||||
return sprintf("\033[%sm%s\033[%sm", implode(';', $setCodes), $text, implode(';', $unsetCodes));
|
||||
}
|
||||
}
|
163
thinkphp/library/think/console/output/question/Choice.php
Normal file
163
thinkphp/library/think/console/output/question/Choice.php
Normal file
@ -0,0 +1,163 @@
|
||||
<?php
|
||||
// +----------------------------------------------------------------------
|
||||
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
|
||||
// +----------------------------------------------------------------------
|
||||
// | Copyright (c) 2006~2015 http://thinkphp.cn All rights reserved.
|
||||
// +----------------------------------------------------------------------
|
||||
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
|
||||
// +----------------------------------------------------------------------
|
||||
// | Author: yunwuxin <448901948@qq.com>
|
||||
// +----------------------------------------------------------------------
|
||||
|
||||
namespace think\console\output\question;
|
||||
|
||||
use think\console\output\Question;
|
||||
|
||||
class Choice extends Question
|
||||
{
|
||||
|
||||
private $choices;
|
||||
private $multiselect = false;
|
||||
private $prompt = ' > ';
|
||||
private $errorMessage = 'Value "%s" is invalid';
|
||||
|
||||
/**
|
||||
* 构造方法
|
||||
* @param string $question 问题
|
||||
* @param array $choices 选项
|
||||
* @param mixed $default 默认答案
|
||||
*/
|
||||
public function __construct($question, array $choices, $default = null)
|
||||
{
|
||||
parent::__construct($question, $default);
|
||||
|
||||
$this->choices = $choices;
|
||||
$this->setValidator($this->getDefaultValidator());
|
||||
$this->setAutocompleterValues($choices);
|
||||
}
|
||||
|
||||
/**
|
||||
* 可选项
|
||||
* @return array
|
||||
*/
|
||||
public function getChoices()
|
||||
{
|
||||
return $this->choices;
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置可否多选
|
||||
* @param bool $multiselect
|
||||
* @return self
|
||||
*/
|
||||
public function setMultiselect($multiselect)
|
||||
{
|
||||
$this->multiselect = $multiselect;
|
||||
$this->setValidator($this->getDefaultValidator());
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function isMultiselect()
|
||||
{
|
||||
return $this->multiselect;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取提示
|
||||
* @return string
|
||||
*/
|
||||
public function getPrompt()
|
||||
{
|
||||
return $this->prompt;
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置提示
|
||||
* @param string $prompt
|
||||
* @return self
|
||||
*/
|
||||
public function setPrompt($prompt)
|
||||
{
|
||||
$this->prompt = $prompt;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置错误提示信息
|
||||
* @param string $errorMessage
|
||||
* @return self
|
||||
*/
|
||||
public function setErrorMessage($errorMessage)
|
||||
{
|
||||
$this->errorMessage = $errorMessage;
|
||||
$this->setValidator($this->getDefaultValidator());
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取默认的验证方法
|
||||
* @return callable
|
||||
*/
|
||||
private function getDefaultValidator()
|
||||
{
|
||||
$choices = $this->choices;
|
||||
$errorMessage = $this->errorMessage;
|
||||
$multiselect = $this->multiselect;
|
||||
$isAssoc = $this->isAssoc($choices);
|
||||
|
||||
return function ($selected) use ($choices, $errorMessage, $multiselect, $isAssoc) {
|
||||
// Collapse all spaces.
|
||||
$selectedChoices = str_replace(' ', '', $selected);
|
||||
|
||||
if ($multiselect) {
|
||||
// Check for a separated comma values
|
||||
if (!preg_match('/^[a-zA-Z0-9_-]+(?:,[a-zA-Z0-9_-]+)*$/', $selectedChoices, $matches)) {
|
||||
throw new \InvalidArgumentException(sprintf($errorMessage, $selected));
|
||||
}
|
||||
$selectedChoices = explode(',', $selectedChoices);
|
||||
} else {
|
||||
$selectedChoices = [$selected];
|
||||
}
|
||||
|
||||
$multiselectChoices = [];
|
||||
foreach ($selectedChoices as $value) {
|
||||
$results = [];
|
||||
foreach ($choices as $key => $choice) {
|
||||
if ($choice === $value) {
|
||||
$results[] = $key;
|
||||
}
|
||||
}
|
||||
|
||||
if (count($results) > 1) {
|
||||
throw new \InvalidArgumentException(sprintf('The provided answer is ambiguous. Value should be one of %s.', implode(' or ', $results)));
|
||||
}
|
||||
|
||||
$result = array_search($value, $choices);
|
||||
|
||||
if (!$isAssoc) {
|
||||
if (!empty($result)) {
|
||||
$result = $choices[$result];
|
||||
} elseif (isset($choices[$value])) {
|
||||
$result = $choices[$value];
|
||||
}
|
||||
} elseif (empty($result) && array_key_exists($value, $choices)) {
|
||||
$result = $value;
|
||||
}
|
||||
|
||||
if (empty($result)) {
|
||||
throw new \InvalidArgumentException(sprintf($errorMessage, $value));
|
||||
}
|
||||
array_push($multiselectChoices, $result);
|
||||
}
|
||||
|
||||
if ($multiselect) {
|
||||
return $multiselectChoices;
|
||||
}
|
||||
|
||||
return current($multiselectChoices);
|
||||
};
|
||||
}
|
||||
}
|
@ -0,0 +1,57 @@
|
||||
<?php
|
||||
// +----------------------------------------------------------------------
|
||||
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
|
||||
// +----------------------------------------------------------------------
|
||||
// | Copyright (c) 2006~2015 http://thinkphp.cn All rights reserved.
|
||||
// +----------------------------------------------------------------------
|
||||
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
|
||||
// +----------------------------------------------------------------------
|
||||
// | Author: yunwuxin <448901948@qq.com>
|
||||
// +----------------------------------------------------------------------
|
||||
|
||||
namespace think\console\output\question;
|
||||
|
||||
use think\console\output\Question;
|
||||
|
||||
class Confirmation extends Question
|
||||
{
|
||||
|
||||
private $trueAnswerRegex;
|
||||
|
||||
/**
|
||||
* 构造方法
|
||||
* @param string $question 问题
|
||||
* @param bool $default 默认答案
|
||||
* @param string $trueAnswerRegex 验证正则
|
||||
*/
|
||||
public function __construct($question, $default = true, $trueAnswerRegex = '/^y/i')
|
||||
{
|
||||
parent::__construct($question, (bool) $default);
|
||||
|
||||
$this->trueAnswerRegex = $trueAnswerRegex;
|
||||
$this->setNormalizer($this->getDefaultNormalizer());
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取默认的答案回调
|
||||
* @return callable
|
||||
*/
|
||||
private function getDefaultNormalizer()
|
||||
{
|
||||
$default = $this->getDefault();
|
||||
$regex = $this->trueAnswerRegex;
|
||||
|
||||
return function ($answer) use ($default, $regex) {
|
||||
if (is_bool($answer)) {
|
||||
return $answer;
|
||||
}
|
||||
|
||||
$answerIsTrue = (bool) preg_match($regex, $answer);
|
||||
if (false === $default) {
|
||||
return $answer && $answerIsTrue;
|
||||
}
|
||||
|
||||
return !$answer || $answerIsTrue;
|
||||
};
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user