CliDumper.php 16 KB

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