Console.php 11 KB

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