CliDumper.php 21 KB

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