Console.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
  8. // +----------------------------------------------------------------------
  9. // | Author: yunwuxin <448901948@qq.com>
  10. // +----------------------------------------------------------------------
  11. namespace think\console\output\driver;
  12. use think\console\Output;
  13. use think\console\output\Formatter;
  14. class Console
  15. {
  16. /** @var Resource */
  17. private $stdout;
  18. /** @var Formatter */
  19. private $formatter;
  20. private $terminalDimensions;
  21. /** @var Output */
  22. private $output;
  23. public function __construct(Output $output)
  24. {
  25. $this->output = $output;
  26. $this->formatter = new Formatter();
  27. $this->stdout = $this->openOutputStream();
  28. $decorated = $this->hasColorSupport($this->stdout);
  29. $this->formatter->setDecorated($decorated);
  30. }
  31. public function getFormatter()
  32. {
  33. return $this->formatter;
  34. }
  35. public function setDecorated($decorated)
  36. {
  37. $this->formatter->setDecorated($decorated);
  38. }
  39. public function write($messages, $newline = false, $type = Output::OUTPUT_NORMAL, $stream = null)
  40. {
  41. if (Output::VERBOSITY_QUIET === $this->output->getVerbosity()) {
  42. return;
  43. }
  44. $messages = (array) $messages;
  45. foreach ($messages as $message) {
  46. switch ($type) {
  47. case Output::OUTPUT_NORMAL:
  48. $message = $this->formatter->format($message);
  49. break;
  50. case Output::OUTPUT_RAW:
  51. break;
  52. case Output::OUTPUT_PLAIN:
  53. $message = strip_tags($this->formatter->format($message));
  54. break;
  55. default:
  56. throw new \InvalidArgumentException(sprintf('Unknown output type given (%s)', $type));
  57. }
  58. $this->doWrite($message, $newline, $stream);
  59. }
  60. }
  61. public function renderException(\Exception $e)
  62. {
  63. $stderr = $this->openErrorStream();
  64. $decorated = $this->hasColorSupport($stderr);
  65. $this->formatter->setDecorated($decorated);
  66. do {
  67. $title = sprintf(' [%s] ', get_class($e));
  68. $len = $this->stringWidth($title);
  69. $width = $this->getTerminalWidth() ? $this->getTerminalWidth() - 1 : PHP_INT_MAX;
  70. if (defined('HHVM_VERSION') && $width > 1 << 31) {
  71. $width = 1 << 31;
  72. }
  73. $lines = [];
  74. foreach (preg_split('/\r?\n/', $e->getMessage()) as $line) {
  75. foreach ($this->splitStringByWidth($line, $width - 4) as $line) {
  76. $lineLength = $this->stringWidth(preg_replace('/\[[^m]*m/', '', $line)) + 4;
  77. $lines[] = [$line, $lineLength];
  78. $len = max($lineLength, $len);
  79. }
  80. }
  81. $messages = ['', ''];
  82. $messages[] = $emptyLine = sprintf('<error>%s</error>', str_repeat(' ', $len));
  83. $messages[] = sprintf('<error>%s%s</error>', $title, str_repeat(' ', max(0, $len - $this->stringWidth($title))));
  84. foreach ($lines as $line) {
  85. $messages[] = sprintf('<error> %s %s</error>', $line[0], str_repeat(' ', $len - $line[1]));
  86. }
  87. $messages[] = $emptyLine;
  88. $messages[] = '';
  89. $messages[] = '';
  90. $this->write($messages, true, Output::OUTPUT_NORMAL, $stderr);
  91. if (Output::VERBOSITY_VERBOSE <= $this->output->getVerbosity()) {
  92. $this->write('<comment>Exception trace:</comment>', true, Output::OUTPUT_NORMAL, $stderr);
  93. // exception related properties
  94. $trace = $e->getTrace();
  95. array_unshift($trace, [
  96. 'function' => '',
  97. 'file' => $e->getFile() !== null ? $e->getFile() : 'n/a',
  98. 'line' => $e->getLine() !== null ? $e->getLine() : 'n/a',
  99. 'args' => [],
  100. ]);
  101. for ($i = 0, $count = count($trace); $i < $count; ++$i) {
  102. $class = isset($trace[$i]['class']) ? $trace[$i]['class'] : '';
  103. $type = isset($trace[$i]['type']) ? $trace[$i]['type'] : '';
  104. $function = $trace[$i]['function'];
  105. $file = isset($trace[$i]['file']) ? $trace[$i]['file'] : 'n/a';
  106. $line = isset($trace[$i]['line']) ? $trace[$i]['line'] : 'n/a';
  107. $this->write(sprintf(' %s%s%s() at <info>%s:%s</info>', $class, $type, $function, $file, $line), true, Output::OUTPUT_NORMAL, $stderr);
  108. }
  109. $this->write('', true, Output::OUTPUT_NORMAL, $stderr);
  110. $this->write('', true, Output::OUTPUT_NORMAL, $stderr);
  111. }
  112. } while ($e = $e->getPrevious());
  113. }
  114. /**
  115. * 获取终端宽度
  116. * @return int|null
  117. */
  118. protected function getTerminalWidth()
  119. {
  120. $dimensions = $this->getTerminalDimensions();
  121. return $dimensions[0];
  122. }
  123. /**
  124. * 获取终端高度
  125. * @return int|null
  126. */
  127. protected function getTerminalHeight()
  128. {
  129. $dimensions = $this->getTerminalDimensions();
  130. return $dimensions[1];
  131. }
  132. /**
  133. * 获取当前终端的尺寸
  134. * @return array
  135. */
  136. public function getTerminalDimensions()
  137. {
  138. if ($this->terminalDimensions) {
  139. return $this->terminalDimensions;
  140. }
  141. if ('\\' === DS) {
  142. if (preg_match('/^(\d+)x\d+ \(\d+x(\d+)\)$/', trim(getenv('ANSICON')), $matches)) {
  143. return [(int) $matches[1], (int) $matches[2]];
  144. }
  145. if (preg_match('/^(\d+)x(\d+)$/', $this->getMode(), $matches)) {
  146. return [(int) $matches[1], (int) $matches[2]];
  147. }
  148. }
  149. if ($sttyString = $this->getSttyColumns()) {
  150. if (preg_match('/rows.(\d+);.columns.(\d+);/i', $sttyString, $matches)) {
  151. return [(int) $matches[2], (int) $matches[1]];
  152. }
  153. if (preg_match('/;.(\d+).rows;.(\d+).columns/i', $sttyString, $matches)) {
  154. return [(int) $matches[2], (int) $matches[1]];
  155. }
  156. }
  157. return [null, null];
  158. }
  159. /**
  160. * 获取stty列数
  161. * @return string
  162. */
  163. private function getSttyColumns()
  164. {
  165. if (!function_exists('proc_open')) {
  166. return;
  167. }
  168. $descriptorspec = [1 => ['pipe', 'w'], 2 => ['pipe', 'w']];
  169. $process = proc_open('stty -a | grep columns', $descriptorspec, $pipes, null, null, ['suppress_errors' => true]);
  170. if (is_resource($process)) {
  171. $info = stream_get_contents($pipes[1]);
  172. fclose($pipes[1]);
  173. fclose($pipes[2]);
  174. proc_close($process);
  175. return $info;
  176. }
  177. return;
  178. }
  179. /**
  180. * 获取终端模式
  181. * @return string <width>x<height> 或 null
  182. */
  183. private function getMode()
  184. {
  185. if (!function_exists('proc_open')) {
  186. return;
  187. }
  188. $descriptorspec = [1 => ['pipe', 'w'], 2 => ['pipe', 'w']];
  189. $process = proc_open('mode CON', $descriptorspec, $pipes, null, null, ['suppress_errors' => true]);
  190. if (is_resource($process)) {
  191. $info = stream_get_contents($pipes[1]);
  192. fclose($pipes[1]);
  193. fclose($pipes[2]);
  194. proc_close($process);
  195. if (preg_match('/--------+\r?\n.+?(\d+)\r?\n.+?(\d+)\r?\n/', $info, $matches)) {
  196. return $matches[2] . 'x' . $matches[1];
  197. }
  198. }
  199. return;
  200. }
  201. private function stringWidth($string)
  202. {
  203. if (!function_exists('mb_strwidth')) {
  204. return strlen($string);
  205. }
  206. if (false === $encoding = mb_detect_encoding($string)) {
  207. return strlen($string);
  208. }
  209. return mb_strwidth($string, $encoding);
  210. }
  211. private function splitStringByWidth($string, $width)
  212. {
  213. if (!function_exists('mb_strwidth')) {
  214. return str_split($string, $width);
  215. }
  216. if (false === $encoding = mb_detect_encoding($string)) {
  217. return str_split($string, $width);
  218. }
  219. $utf8String = mb_convert_encoding($string, 'utf8', $encoding);
  220. $lines = [];
  221. $line = '';
  222. foreach (preg_split('//u', $utf8String) as $char) {
  223. if (mb_strwidth($line . $char, 'utf8') <= $width) {
  224. $line .= $char;
  225. continue;
  226. }
  227. $lines[] = str_pad($line, $width);
  228. $line = $char;
  229. }
  230. if (strlen($line)) {
  231. $lines[] = count($lines) ? str_pad($line, $width) : $line;
  232. }
  233. mb_convert_variables($encoding, 'utf8', $lines);
  234. return $lines;
  235. }
  236. private function isRunningOS400()
  237. {
  238. $checks = [
  239. function_exists('php_uname') ? php_uname('s') : '',
  240. getenv('OSTYPE'),
  241. PHP_OS,
  242. ];
  243. return false !== stripos(implode(';', $checks), 'OS400');
  244. }
  245. /**
  246. * 当前环境是否支持写入控制台输出到stdout.
  247. *
  248. * @return bool
  249. */
  250. protected function hasStdoutSupport()
  251. {
  252. return false === $this->isRunningOS400();
  253. }
  254. /**
  255. * 当前环境是否支持写入控制台输出到stderr.
  256. *
  257. * @return bool
  258. */
  259. protected function hasStderrSupport()
  260. {
  261. return false === $this->isRunningOS400();
  262. }
  263. /**
  264. * @return resource
  265. */
  266. private function openOutputStream()
  267. {
  268. if (!$this->hasStdoutSupport()) {
  269. return fopen('php://output', 'w');
  270. }
  271. return @fopen('php://stdout', 'w') ?: fopen('php://output', 'w');
  272. }
  273. /**
  274. * @return resource
  275. */
  276. private function openErrorStream()
  277. {
  278. return fopen($this->hasStderrSupport() ? 'php://stderr' : 'php://output', 'w');
  279. }
  280. /**
  281. * 将消息写入到输出。
  282. * @param string $message 消息
  283. * @param bool $newline 是否另起一行
  284. * @param null $stream
  285. */
  286. protected function doWrite($message, $newline, $stream = null)
  287. {
  288. if (null === $stream) {
  289. $stream = $this->stdout;
  290. }
  291. if (false === @fwrite($stream, $message . ($newline ? PHP_EOL : ''))) {
  292. throw new \RuntimeException('Unable to write output.');
  293. }
  294. fflush($stream);
  295. }
  296. /**
  297. * 是否支持着色
  298. * @param $stream
  299. * @return bool
  300. */
  301. protected function hasColorSupport($stream)
  302. {
  303. if (DIRECTORY_SEPARATOR === '\\') {
  304. return
  305. '10.0.10586' === PHP_WINDOWS_VERSION_MAJOR . '.' . PHP_WINDOWS_VERSION_MINOR . '.' . PHP_WINDOWS_VERSION_BUILD
  306. || false !== getenv('ANSICON')
  307. || 'ON' === getenv('ConEmuANSI')
  308. || 'xterm' === getenv('TERM');
  309. }
  310. return function_exists('posix_isatty') && @posix_isatty($stream);
  311. }
  312. }