CliDumper.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489
  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->dumpLine($cursor->depth, true);
  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->dumpLine($cursor->depth, true);
  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. $this->dumpLine($cursor->depth, $i > $m);
  213. }
  214. }
  215. }
  216. /**
  217. * {@inheritdoc}
  218. */
  219. public function enterHash(Cursor $cursor, $type, $class, $hasChild)
  220. {
  221. $this->dumpKey($cursor);
  222. $class = $this->utf8Encode($class);
  223. if (Cursor::HASH_OBJECT === $type) {
  224. $prefix = $class && 'stdClass' !== $class ? $this->style('note', $class).' {' : '{';
  225. } elseif (Cursor::HASH_RESOURCE === $type) {
  226. $prefix = $this->style('note', $class.' resource').($hasChild ? ' {' : ' ');
  227. } else {
  228. $prefix = $class && !(self::DUMP_LIGHT_ARRAY & $this->flags) ? $this->style('note', 'array:'.$class).' [' : '[';
  229. }
  230. if ($cursor->softRefCount || 0 < $cursor->softRefHandle) {
  231. $prefix .= $this->style('ref', (Cursor::HASH_RESOURCE === $type ? '@' : '#').(0 < $cursor->softRefHandle ? $cursor->softRefHandle : $cursor->softRefTo), array('count' => $cursor->softRefCount));
  232. } elseif ($cursor->hardRefTo && !$cursor->refIndex && $class) {
  233. $prefix .= $this->style('ref', '&'.$cursor->hardRefTo, array('count' => $cursor->hardRefCount));
  234. } elseif (!$hasChild && Cursor::HASH_RESOURCE === $type) {
  235. $prefix = substr($prefix, 0, -1);
  236. }
  237. $this->line .= $prefix;
  238. if ($hasChild) {
  239. $this->dumpLine($cursor->depth);
  240. }
  241. }
  242. /**
  243. * {@inheritdoc}
  244. */
  245. public function leaveHash(Cursor $cursor, $type, $class, $hasChild, $cut)
  246. {
  247. $this->dumpEllipsis($cursor, $hasChild, $cut);
  248. $this->line .= Cursor::HASH_OBJECT === $type ? '}' : (Cursor::HASH_RESOURCE !== $type ? ']' : ($hasChild ? '}' : ''));
  249. $this->dumpLine($cursor->depth, true);
  250. }
  251. /**
  252. * Dumps an ellipsis for cut children.
  253. *
  254. * @param Cursor $cursor The Cursor position in the dump
  255. * @param bool $hasChild When the dump of the hash has child item
  256. * @param int $cut The number of items the hash has been cut by
  257. */
  258. protected function dumpEllipsis(Cursor $cursor, $hasChild, $cut)
  259. {
  260. if ($cut) {
  261. $this->line .= ' …';
  262. if (0 < $cut) {
  263. $this->line .= $cut;
  264. }
  265. if ($hasChild) {
  266. $this->dumpLine($cursor->depth + 1);
  267. }
  268. }
  269. }
  270. /**
  271. * Dumps a key in a hash structure.
  272. *
  273. * @param Cursor $cursor The Cursor position in the dump
  274. */
  275. protected function dumpKey(Cursor $cursor)
  276. {
  277. if (null !== $key = $cursor->hashKey) {
  278. if ($cursor->hashKeyIsBinary) {
  279. $key = $this->utf8Encode($key);
  280. }
  281. $attr = array('binary' => $cursor->hashKeyIsBinary);
  282. $bin = $cursor->hashKeyIsBinary ? 'b' : '';
  283. $style = 'key';
  284. switch ($cursor->hashType) {
  285. default:
  286. case Cursor::HASH_INDEXED:
  287. if (self::DUMP_LIGHT_ARRAY & $this->flags) {
  288. break;
  289. }
  290. $style = 'index';
  291. case Cursor::HASH_ASSOC:
  292. if (is_int($key)) {
  293. $this->line .= $this->style($style, $key).' => ';
  294. } else {
  295. $this->line .= $bin.'"'.$this->style($style, $key).'" => ';
  296. }
  297. break;
  298. case Cursor::HASH_RESOURCE:
  299. $key = "\0~\0".$key;
  300. // No break;
  301. case Cursor::HASH_OBJECT:
  302. if (!isset($key[0]) || "\0" !== $key[0]) {
  303. $this->line .= '+'.$bin.$this->style('public', $key).': ';
  304. } elseif (0 < strpos($key, "\0", 1)) {
  305. $key = explode("\0", substr($key, 1), 2);
  306. switch ($key[0][0]) {
  307. case '+': // User inserted keys
  308. $attr['dynamic'] = true;
  309. $this->line .= '+'.$bin.'"'.$this->style('public', $key[1], $attr).'": ';
  310. break 2;
  311. case '~':
  312. $style = 'meta';
  313. if (isset($key[0][1])) {
  314. parse_str(substr($key[0], 1), $attr);
  315. $attr += array('binary' => $cursor->hashKeyIsBinary);
  316. }
  317. break;
  318. case '*':
  319. $style = 'protected';
  320. $bin = '#'.$bin;
  321. break;
  322. default:
  323. $attr['class'] = $key[0];
  324. $style = 'private';
  325. $bin = '-'.$bin;
  326. break;
  327. }
  328. $this->line .= $bin.$this->style($style, $key[1], $attr).': ';
  329. } else {
  330. // This case should not happen
  331. $this->line .= '-'.$bin.'"'.$this->style('private', $key, array('class' => '')).'": ';
  332. }
  333. break;
  334. }
  335. if ($cursor->hardRefTo) {
  336. $this->line .= $this->style('ref', '&'.($cursor->hardRefCount ? $cursor->hardRefTo : ''), array('count' => $cursor->hardRefCount)).' ';
  337. }
  338. }
  339. }
  340. /**
  341. * Decorates a value with some style.
  342. *
  343. * @param string $style The type of style being applied
  344. * @param string $value The value being styled
  345. * @param array $attr Optional context information
  346. *
  347. * @return string The value with style decoration
  348. */
  349. protected function style($style, $value, $attr = array())
  350. {
  351. if (null === $this->colors) {
  352. $this->colors = $this->supportsColors();
  353. }
  354. $style = $this->styles[$style];
  355. $map = static::$controlCharsMap;
  356. $startCchr = $this->colors ? "\033[m\033[{$this->styles['default']}m" : '';
  357. $endCchr = $this->colors ? "\033[m\033[{$style}m" : '';
  358. $value = preg_replace_callback(static::$controlCharsRx, function ($c) use ($map, $startCchr, $endCchr) {
  359. $s = $startCchr;
  360. $c = $c[$i = 0];
  361. do {
  362. $s .= isset($map[$c[$i]]) ? $map[$c[$i]] : sprintf('\x%02X', ord($c[$i]));
  363. } while (isset($c[++$i]));
  364. return $s.$endCchr;
  365. }, $value, -1, $cchrCount);
  366. if ($this->colors) {
  367. if ($cchrCount && "\033" === $value[0]) {
  368. $value = substr($value, strlen($startCchr));
  369. } else {
  370. $value = "\033[{$style}m".$value;
  371. }
  372. if ($cchrCount && $endCchr === substr($value, -strlen($endCchr))) {
  373. $value = substr($value, 0, -strlen($endCchr));
  374. } else {
  375. $value .= "\033[{$this->styles['default']}m";
  376. }
  377. }
  378. return $value;
  379. }
  380. /**
  381. * @return bool Tells if the current output stream supports ANSI colors or not
  382. */
  383. protected function supportsColors()
  384. {
  385. if ($this->outputStream !== static::$defaultOutput) {
  386. return @(is_resource($this->outputStream) && function_exists('posix_isatty') && posix_isatty($this->outputStream));
  387. }
  388. if (null !== static::$defaultColors) {
  389. return static::$defaultColors;
  390. }
  391. if (isset($_SERVER['argv'][1])) {
  392. $colors = $_SERVER['argv'];
  393. $i = count($colors);
  394. while (--$i > 0) {
  395. if (isset($colors[$i][5])) {
  396. switch ($colors[$i]) {
  397. case '--ansi':
  398. case '--color':
  399. case '--color=yes':
  400. case '--color=force':
  401. case '--color=always':
  402. return static::$defaultColors = true;
  403. case '--no-ansi':
  404. case '--color=no':
  405. case '--color=none':
  406. case '--color=never':
  407. return static::$defaultColors = false;
  408. }
  409. }
  410. }
  411. }
  412. if ('\\' === DIRECTORY_SEPARATOR) {
  413. static::$defaultColors = @(
  414. '10.0.10586' === PHP_WINDOWS_VERSION_MAJOR.'.'.PHP_WINDOWS_VERSION_MINOR.'.'.PHP_WINDOWS_VERSION_BUILD
  415. || false !== getenv('ANSICON')
  416. || 'ON' === getenv('ConEmuANSI')
  417. || 'xterm' === getenv('TERM')
  418. );
  419. } elseif (function_exists('posix_isatty')) {
  420. $h = stream_get_meta_data($this->outputStream) + array('wrapper_type' => null);
  421. $h = 'Output' === $h['stream_type'] && 'PHP' === $h['wrapper_type'] ? fopen('php://stdout', 'wb') : $this->outputStream;
  422. static::$defaultColors = @posix_isatty($h);
  423. } else {
  424. static::$defaultColors = false;
  425. }
  426. return static::$defaultColors;
  427. }
  428. /**
  429. * {@inheritdoc}
  430. */
  431. protected function dumpLine($depth, $endOfValue = false)
  432. {
  433. if ($this->colors) {
  434. $this->line = sprintf("\033[%sm%s\033[m", $this->styles['default'], $this->line);
  435. }
  436. parent::dumpLine($depth);
  437. }
  438. }