CliDumper.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\VarDumper\Dumper;
  11. use Symfony\Component\VarDumper\Cloner\Cursor;
  12. use Symfony\Component\VarDumper\Cloner\Stub;
  13. /**
  14. * CliDumper dumps variables for command line output.
  15. *
  16. * @author Nicolas Grekas <p@tchwork.com>
  17. */
  18. class CliDumper extends AbstractDumper
  19. {
  20. public static $defaultColors;
  21. public static $defaultOutput = 'php://stdout';
  22. protected $colors;
  23. protected $maxStringWidth = 0;
  24. protected $styles = [
  25. // See http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
  26. 'default' => '38;5;208',
  27. 'num' => '1;38;5;38',
  28. 'const' => '1;38;5;208',
  29. 'str' => '1;38;5;113',
  30. 'note' => '38;5;38',
  31. 'ref' => '38;5;247',
  32. 'public' => '',
  33. 'protected' => '',
  34. 'private' => '',
  35. 'meta' => '38;5;170',
  36. 'key' => '38;5;113',
  37. 'index' => '38;5;38',
  38. ];
  39. protected static $controlCharsRx = '/[\x00-\x1F\x7F]+/';
  40. protected static $controlCharsMap = [
  41. "\t" => '\t',
  42. "\n" => '\n',
  43. "\v" => '\v',
  44. "\f" => '\f',
  45. "\r" => '\r',
  46. "\033" => '\e',
  47. ];
  48. protected $collapseNextHash = false;
  49. protected $expandNextHash = false;
  50. /**
  51. * {@inheritdoc}
  52. */
  53. public function __construct($output = null, string $charset = null, int $flags = 0)
  54. {
  55. parent::__construct($output, $charset, $flags);
  56. if ('\\' === \DIRECTORY_SEPARATOR && !$this->isWindowsTrueColor()) {
  57. // Use only the base 16 xterm colors when using ANSICON or standard Windows 10 CLI
  58. $this->setStyles([
  59. 'default' => '31',
  60. 'num' => '1;34',
  61. 'const' => '1;31',
  62. 'str' => '1;32',
  63. 'note' => '34',
  64. 'ref' => '1;30',
  65. 'meta' => '35',
  66. 'key' => '32',
  67. 'index' => '34',
  68. ]);
  69. }
  70. }
  71. /**
  72. * Enables/disables colored output.
  73. *
  74. * @param bool $colors
  75. */
  76. public function setColors($colors)
  77. {
  78. $this->colors = (bool) $colors;
  79. }
  80. /**
  81. * Sets the maximum number of characters per line for dumped strings.
  82. *
  83. * @param int $maxStringWidth
  84. */
  85. public function setMaxStringWidth($maxStringWidth)
  86. {
  87. $this->maxStringWidth = (int) $maxStringWidth;
  88. }
  89. /**
  90. * Configures styles.
  91. *
  92. * @param array $styles A map of style names to style definitions
  93. */
  94. public function setStyles(array $styles)
  95. {
  96. $this->styles = $styles + $this->styles;
  97. }
  98. /**
  99. * {@inheritdoc}
  100. */
  101. public function dumpScalar(Cursor $cursor, $type, $value)
  102. {
  103. $this->dumpKey($cursor);
  104. $style = 'const';
  105. $attr = $cursor->attr;
  106. switch ($type) {
  107. case 'default':
  108. $style = 'default';
  109. break;
  110. case 'integer':
  111. $style = 'num';
  112. break;
  113. case 'double':
  114. $style = 'num';
  115. switch (true) {
  116. case INF === $value: $value = 'INF'; break;
  117. case -INF === $value: $value = '-INF'; break;
  118. case is_nan($value): $value = 'NAN'; break;
  119. default:
  120. $value = (string) $value;
  121. if (false === strpos($value, $this->decimalPoint)) {
  122. $value .= $this->decimalPoint.'0';
  123. }
  124. break;
  125. }
  126. break;
  127. case 'NULL':
  128. $value = 'null';
  129. break;
  130. case 'boolean':
  131. $value = $value ? 'true' : 'false';
  132. break;
  133. default:
  134. $attr += ['value' => $this->utf8Encode($value)];
  135. $value = $this->utf8Encode($type);
  136. break;
  137. }
  138. $this->line .= $this->style($style, $value, $attr);
  139. $this->endValue($cursor);
  140. }
  141. /**
  142. * {@inheritdoc}
  143. */
  144. public function dumpString(Cursor $cursor, $str, $bin, $cut)
  145. {
  146. $this->dumpKey($cursor);
  147. $attr = $cursor->attr;
  148. if ($bin) {
  149. $str = $this->utf8Encode($str);
  150. }
  151. if ('' === $str) {
  152. $this->line .= '""';
  153. $this->endValue($cursor);
  154. } else {
  155. $attr += [
  156. 'length' => 0 <= $cut ? mb_strlen($str, 'UTF-8') + $cut : 0,
  157. 'binary' => $bin,
  158. ];
  159. $str = explode("\n", $str);
  160. if (isset($str[1]) && !isset($str[2]) && !isset($str[1][0])) {
  161. unset($str[1]);
  162. $str[0] .= "\n";
  163. }
  164. $m = \count($str) - 1;
  165. $i = $lineCut = 0;
  166. if (self::DUMP_STRING_LENGTH & $this->flags) {
  167. $this->line .= '('.$attr['length'].') ';
  168. }
  169. if ($bin) {
  170. $this->line .= 'b';
  171. }
  172. if ($m) {
  173. $this->line .= '"""';
  174. $this->dumpLine($cursor->depth);
  175. } else {
  176. $this->line .= '"';
  177. }
  178. foreach ($str as $str) {
  179. if ($i < $m) {
  180. $str .= "\n";
  181. }
  182. if (0 < $this->maxStringWidth && $this->maxStringWidth < $len = mb_strlen($str, 'UTF-8')) {
  183. $str = mb_substr($str, 0, $this->maxStringWidth, 'UTF-8');
  184. $lineCut = $len - $this->maxStringWidth;
  185. }
  186. if ($m && 0 < $cursor->depth) {
  187. $this->line .= $this->indentPad;
  188. }
  189. if ('' !== $str) {
  190. $this->line .= $this->style('str', $str, $attr);
  191. }
  192. if ($i++ == $m) {
  193. if ($m) {
  194. if ('' !== $str) {
  195. $this->dumpLine($cursor->depth);
  196. if (0 < $cursor->depth) {
  197. $this->line .= $this->indentPad;
  198. }
  199. }
  200. $this->line .= '"""';
  201. } else {
  202. $this->line .= '"';
  203. }
  204. if ($cut < 0) {
  205. $this->line .= '…';
  206. $lineCut = 0;
  207. } elseif ($cut) {
  208. $lineCut += $cut;
  209. }
  210. }
  211. if ($lineCut) {
  212. $this->line .= '…'.$lineCut;
  213. $lineCut = 0;
  214. }
  215. if ($i > $m) {
  216. $this->endValue($cursor);
  217. } else {
  218. $this->dumpLine($cursor->depth);
  219. }
  220. }
  221. }
  222. }
  223. /**
  224. * {@inheritdoc}
  225. */
  226. public function enterHash(Cursor $cursor, $type, $class, $hasChild)
  227. {
  228. $this->dumpKey($cursor);
  229. if ($this->collapseNextHash) {
  230. $cursor->skipChildren = true;
  231. $this->collapseNextHash = $hasChild = false;
  232. }
  233. $class = $this->utf8Encode($class);
  234. if (Cursor::HASH_OBJECT === $type) {
  235. $prefix = $class && 'stdClass' !== $class ? $this->style('note', $class).' {' : '{';
  236. } elseif (Cursor::HASH_RESOURCE === $type) {
  237. $prefix = $this->style('note', $class.' resource').($hasChild ? ' {' : ' ');
  238. } else {
  239. $prefix = $class && !(self::DUMP_LIGHT_ARRAY & $this->flags) ? $this->style('note', 'array:'.$class).' [' : '[';
  240. }
  241. if ($cursor->softRefCount || 0 < $cursor->softRefHandle) {
  242. $prefix .= $this->style('ref', (Cursor::HASH_RESOURCE === $type ? '@' : '#').(0 < $cursor->softRefHandle ? $cursor->softRefHandle : $cursor->softRefTo), ['count' => $cursor->softRefCount]);
  243. } elseif ($cursor->hardRefTo && !$cursor->refIndex && $class) {
  244. $prefix .= $this->style('ref', '&'.$cursor->hardRefTo, ['count' => $cursor->hardRefCount]);
  245. } elseif (!$hasChild && Cursor::HASH_RESOURCE === $type) {
  246. $prefix = substr($prefix, 0, -1);
  247. }
  248. $this->line .= $prefix;
  249. if ($hasChild) {
  250. $this->dumpLine($cursor->depth);
  251. }
  252. }
  253. /**
  254. * {@inheritdoc}
  255. */
  256. public function leaveHash(Cursor $cursor, $type, $class, $hasChild, $cut)
  257. {
  258. $this->dumpEllipsis($cursor, $hasChild, $cut);
  259. $this->line .= Cursor::HASH_OBJECT === $type ? '}' : (Cursor::HASH_RESOURCE !== $type ? ']' : ($hasChild ? '}' : ''));
  260. $this->endValue($cursor);
  261. }
  262. /**
  263. * Dumps an ellipsis for cut children.
  264. *
  265. * @param Cursor $cursor The Cursor position in the dump
  266. * @param bool $hasChild When the dump of the hash has child item
  267. * @param int $cut The number of items the hash has been cut by
  268. */
  269. protected function dumpEllipsis(Cursor $cursor, $hasChild, $cut)
  270. {
  271. if ($cut) {
  272. $this->line .= ' …';
  273. if (0 < $cut) {
  274. $this->line .= $cut;
  275. }
  276. if ($hasChild) {
  277. $this->dumpLine($cursor->depth + 1);
  278. }
  279. }
  280. }
  281. /**
  282. * Dumps a key in a hash structure.
  283. *
  284. * @param Cursor $cursor The Cursor position in the dump
  285. */
  286. protected function dumpKey(Cursor $cursor)
  287. {
  288. if (null !== $key = $cursor->hashKey) {
  289. if ($cursor->hashKeyIsBinary) {
  290. $key = $this->utf8Encode($key);
  291. }
  292. $attr = ['binary' => $cursor->hashKeyIsBinary];
  293. $bin = $cursor->hashKeyIsBinary ? 'b' : '';
  294. $style = 'key';
  295. switch ($cursor->hashType) {
  296. default:
  297. case Cursor::HASH_INDEXED:
  298. if (self::DUMP_LIGHT_ARRAY & $this->flags) {
  299. break;
  300. }
  301. $style = 'index';
  302. // no break
  303. case Cursor::HASH_ASSOC:
  304. if (\is_int($key)) {
  305. $this->line .= $this->style($style, $key).' => ';
  306. } else {
  307. $this->line .= $bin.'"'.$this->style($style, $key).'" => ';
  308. }
  309. break;
  310. case Cursor::HASH_RESOURCE:
  311. $key = "\0~\0".$key;
  312. // no break
  313. case Cursor::HASH_OBJECT:
  314. if (!isset($key[0]) || "\0" !== $key[0]) {
  315. $this->line .= '+'.$bin.$this->style('public', $key).': ';
  316. } elseif (0 < strpos($key, "\0", 1)) {
  317. $key = explode("\0", substr($key, 1), 2);
  318. switch ($key[0][0]) {
  319. case '+': // User inserted keys
  320. $attr['dynamic'] = true;
  321. $this->line .= '+'.$bin.'"'.$this->style('public', $key[1], $attr).'": ';
  322. break 2;
  323. case '~':
  324. $style = 'meta';
  325. if (isset($key[0][1])) {
  326. parse_str(substr($key[0], 1), $attr);
  327. $attr += ['binary' => $cursor->hashKeyIsBinary];
  328. }
  329. break;
  330. case '*':
  331. $style = 'protected';
  332. $bin = '#'.$bin;
  333. break;
  334. default:
  335. $attr['class'] = $key[0];
  336. $style = 'private';
  337. $bin = '-'.$bin;
  338. break;
  339. }
  340. if (isset($attr['collapse'])) {
  341. if ($attr['collapse']) {
  342. $this->collapseNextHash = true;
  343. } else {
  344. $this->expandNextHash = true;
  345. }
  346. }
  347. $this->line .= $bin.$this->style($style, $key[1], $attr).(isset($attr['separator']) ? $attr['separator'] : ': ');
  348. } else {
  349. // This case should not happen
  350. $this->line .= '-'.$bin.'"'.$this->style('private', $key, ['class' => '']).'": ';
  351. }
  352. break;
  353. }
  354. if ($cursor->hardRefTo) {
  355. $this->line .= $this->style('ref', '&'.($cursor->hardRefCount ? $cursor->hardRefTo : ''), ['count' => $cursor->hardRefCount]).' ';
  356. }
  357. }
  358. }
  359. /**
  360. * Decorates a value with some style.
  361. *
  362. * @param string $style The type of style being applied
  363. * @param string $value The value being styled
  364. * @param array $attr Optional context information
  365. *
  366. * @return string The value with style decoration
  367. */
  368. protected function style($style, $value, $attr = [])
  369. {
  370. if (null === $this->colors) {
  371. $this->colors = $this->supportsColors();
  372. }
  373. if (isset($attr['ellipsis'], $attr['ellipsis-type'])) {
  374. $prefix = substr($value, 0, -$attr['ellipsis']);
  375. if ('cli' === \PHP_SAPI && 'path' === $attr['ellipsis-type'] && isset($_SERVER[$pwd = '\\' === \DIRECTORY_SEPARATOR ? 'CD' : 'PWD']) && 0 === strpos($prefix, $_SERVER[$pwd])) {
  376. $prefix = '.'.substr($prefix, \strlen($_SERVER[$pwd]));
  377. }
  378. if (!empty($attr['ellipsis-tail'])) {
  379. $prefix .= substr($value, -$attr['ellipsis'], $attr['ellipsis-tail']);
  380. $value = substr($value, -$attr['ellipsis'] + $attr['ellipsis-tail']);
  381. } else {
  382. $value = substr($value, -$attr['ellipsis']);
  383. }
  384. return $this->style('default', $prefix).$this->style($style, $value);
  385. }
  386. $style = $this->styles[$style];
  387. $map = static::$controlCharsMap;
  388. $startCchr = $this->colors ? "\033[m\033[{$this->styles['default']}m" : '';
  389. $endCchr = $this->colors ? "\033[m\033[{$style}m" : '';
  390. $value = preg_replace_callback(static::$controlCharsRx, function ($c) use ($map, $startCchr, $endCchr) {
  391. $s = $startCchr;
  392. $c = $c[$i = 0];
  393. do {
  394. $s .= isset($map[$c[$i]]) ? $map[$c[$i]] : sprintf('\x%02X', \ord($c[$i]));
  395. } while (isset($c[++$i]));
  396. return $s.$endCchr;
  397. }, $value, -1, $cchrCount);
  398. if ($this->colors) {
  399. if ($cchrCount && "\033" === $value[0]) {
  400. $value = substr($value, \strlen($startCchr));
  401. } else {
  402. $value = "\033[{$style}m".$value;
  403. }
  404. if ($cchrCount && $endCchr === substr($value, -\strlen($endCchr))) {
  405. $value = substr($value, 0, -\strlen($endCchr));
  406. } else {
  407. $value .= "\033[{$this->styles['default']}m";
  408. }
  409. }
  410. return $value;
  411. }
  412. /**
  413. * @return bool Tells if the current output stream supports ANSI colors or not
  414. */
  415. protected function supportsColors()
  416. {
  417. if ($this->outputStream !== static::$defaultOutput) {
  418. return $this->hasColorSupport($this->outputStream);
  419. }
  420. if (null !== static::$defaultColors) {
  421. return static::$defaultColors;
  422. }
  423. if (isset($_SERVER['argv'][1])) {
  424. $colors = $_SERVER['argv'];
  425. $i = \count($colors);
  426. while (--$i > 0) {
  427. if (isset($colors[$i][5])) {
  428. switch ($colors[$i]) {
  429. case '--ansi':
  430. case '--color':
  431. case '--color=yes':
  432. case '--color=force':
  433. case '--color=always':
  434. return static::$defaultColors = true;
  435. case '--no-ansi':
  436. case '--color=no':
  437. case '--color=none':
  438. case '--color=never':
  439. return static::$defaultColors = false;
  440. }
  441. }
  442. }
  443. }
  444. $h = stream_get_meta_data($this->outputStream) + ['wrapper_type' => null];
  445. $h = 'Output' === $h['stream_type'] && 'PHP' === $h['wrapper_type'] ? fopen('php://stdout', 'wb') : $this->outputStream;
  446. return static::$defaultColors = $this->hasColorSupport($h);
  447. }
  448. /**
  449. * {@inheritdoc}
  450. */
  451. protected function dumpLine($depth, $endOfValue = false)
  452. {
  453. if ($this->colors) {
  454. $this->line = sprintf("\033[%sm%s\033[m", $this->styles['default'], $this->line);
  455. }
  456. parent::dumpLine($depth);
  457. }
  458. protected function endValue(Cursor $cursor)
  459. {
  460. if (Stub::ARRAY_INDEXED === $cursor->hashType || Stub::ARRAY_ASSOC === $cursor->hashType) {
  461. if (self::DUMP_TRAILING_COMMA & $this->flags && 0 < $cursor->depth) {
  462. $this->line .= ',';
  463. } elseif (self::DUMP_COMMA_SEPARATOR & $this->flags && 1 < $cursor->hashLength - $cursor->hashIndex) {
  464. $this->line .= ',';
  465. }
  466. }
  467. $this->dumpLine($cursor->depth, true);
  468. }
  469. /**
  470. * Returns true if the stream supports colorization.
  471. *
  472. * Reference: Composer\XdebugHandler\Process::supportsColor
  473. * https://github.com/composer/xdebug-handler
  474. *
  475. * @param mixed $stream A CLI output stream
  476. *
  477. * @return bool
  478. */
  479. private function hasColorSupport($stream)
  480. {
  481. if (!\is_resource($stream) || 'stream' !== get_resource_type($stream)) {
  482. return false;
  483. }
  484. if ('Hyper' === getenv('TERM_PROGRAM')) {
  485. return true;
  486. }
  487. if (\DIRECTORY_SEPARATOR === '\\') {
  488. return (\function_exists('sapi_windows_vt100_support')
  489. && @sapi_windows_vt100_support($stream))
  490. || false !== getenv('ANSICON')
  491. || 'ON' === getenv('ConEmuANSI')
  492. || 'xterm' === getenv('TERM');
  493. }
  494. if (\function_exists('stream_isatty')) {
  495. return @stream_isatty($stream);
  496. }
  497. if (\function_exists('posix_isatty')) {
  498. return @posix_isatty($stream);
  499. }
  500. $stat = @fstat($stream);
  501. // Check if formatted mode is S_IFCHR
  502. return $stat ? 0020000 === ($stat['mode'] & 0170000) : false;
  503. }
  504. /**
  505. * Returns true if the Windows terminal supports true color.
  506. *
  507. * Note that this does not check an output stream, but relies on environment
  508. * variables from known implementations, or a PHP and Windows version that
  509. * supports true color.
  510. *
  511. * @return bool
  512. */
  513. private function isWindowsTrueColor()
  514. {
  515. $result = 183 <= getenv('ANSICON_VER')
  516. || 'ON' === getenv('ConEmuANSI')
  517. || 'xterm' === getenv('TERM')
  518. || 'Hyper' === getenv('TERM_PROGRAM');
  519. if (!$result && \PHP_VERSION_ID >= 70200) {
  520. $version = sprintf(
  521. '%s.%s.%s',
  522. PHP_WINDOWS_VERSION_MAJOR,
  523. PHP_WINDOWS_VERSION_MINOR,
  524. PHP_WINDOWS_VERSION_BUILD
  525. );
  526. $result = $version >= '10.0.15063';
  527. }
  528. return $result;
  529. }
  530. }