CliDumper.php 21 KB

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