CliDumper.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478
  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)
  51. {
  52. parent::__construct($output, $charset);
  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 = array();
  103. switch ($type) {
  104. case 'integer':
  105. $style = 'num';
  106. break;
  107. case 'double':
  108. $style = 'num';
  109. switch (true) {
  110. case INF === $value: $value = 'INF'; break;
  111. case -INF === $value: $value = '-INF'; break;
  112. case is_nan($value): $value = 'NAN'; break;
  113. default:
  114. $value = (string) $value;
  115. if (false === strpos($value, $this->decimalPoint)) {
  116. $value .= $this->decimalPoint.'0';
  117. }
  118. break;
  119. }
  120. break;
  121. case 'NULL':
  122. $value = 'null';
  123. break;
  124. case 'boolean':
  125. $value = $value ? 'true' : 'false';
  126. break;
  127. default:
  128. $attr['value'] = isset($value[0]) && !preg_match('//u', $value) ? $this->utf8Encode($value) : $value;
  129. $value = isset($type[0]) && !preg_match('//u', $type) ? $this->utf8Encode($type) : $type;
  130. break;
  131. }
  132. $this->line .= $this->style($style, $value, $attr);
  133. $this->dumpLine($cursor->depth, true);
  134. }
  135. /**
  136. * {@inheritdoc}
  137. */
  138. public function dumpString(Cursor $cursor, $str, $bin, $cut)
  139. {
  140. $this->dumpKey($cursor);
  141. if ($bin) {
  142. $str = $this->utf8Encode($str);
  143. }
  144. if ('' === $str) {
  145. $this->line .= '""';
  146. $this->dumpLine($cursor->depth, true);
  147. } else {
  148. $attr = array(
  149. 'length' => 0 <= $cut ? mb_strlen($str, 'UTF-8') + $cut : 0,
  150. 'binary' => $bin,
  151. );
  152. $str = explode("\n", $str);
  153. if (isset($str[1]) && !isset($str[2]) && !isset($str[1][0])) {
  154. unset($str[1]);
  155. $str[0] .= "\n";
  156. }
  157. $m = count($str) - 1;
  158. $i = $lineCut = 0;
  159. if ($bin) {
  160. $this->line .= 'b';
  161. }
  162. if ($m) {
  163. $this->line .= '"""';
  164. $this->dumpLine($cursor->depth);
  165. } else {
  166. $this->line .= '"';
  167. }
  168. foreach ($str as $str) {
  169. if ($i < $m) {
  170. $str .= "\n";
  171. }
  172. if (0 < $this->maxStringWidth && $this->maxStringWidth < $len = mb_strlen($str, 'UTF-8')) {
  173. $str = mb_substr($str, 0, $this->maxStringWidth, 'UTF-8');
  174. $lineCut = $len - $this->maxStringWidth;
  175. }
  176. if ($m && 0 < $cursor->depth) {
  177. $this->line .= $this->indentPad;
  178. }
  179. if ('' !== $str) {
  180. $this->line .= $this->style('str', $str, $attr);
  181. }
  182. if ($i++ == $m) {
  183. if ($m) {
  184. if ('' !== $str) {
  185. $this->dumpLine($cursor->depth);
  186. if (0 < $cursor->depth) {
  187. $this->line .= $this->indentPad;
  188. }
  189. }
  190. $this->line .= '"""';
  191. } else {
  192. $this->line .= '"';
  193. }
  194. if ($cut < 0) {
  195. $this->line .= '…';
  196. $lineCut = 0;
  197. } elseif ($cut) {
  198. $lineCut += $cut;
  199. }
  200. }
  201. if ($lineCut) {
  202. $this->line .= '…'.$lineCut;
  203. $lineCut = 0;
  204. }
  205. $this->dumpLine($cursor->depth, $i > $m);
  206. }
  207. }
  208. }
  209. /**
  210. * {@inheritdoc}
  211. */
  212. public function enterHash(Cursor $cursor, $type, $class, $hasChild)
  213. {
  214. $this->dumpKey($cursor);
  215. if (!preg_match('//u', $class)) {
  216. $class = $this->utf8Encode($class);
  217. }
  218. if (Cursor::HASH_OBJECT === $type) {
  219. $prefix = $class && 'stdClass' !== $class ? $this->style('note', $class).' {' : '{';
  220. } elseif (Cursor::HASH_RESOURCE === $type) {
  221. $prefix = $this->style('note', $class.' resource').($hasChild ? ' {' : ' ');
  222. } else {
  223. $prefix = $class ? $this->style('note', 'array:'.$class).' [' : '[';
  224. }
  225. if ($cursor->softRefCount || 0 < $cursor->softRefHandle) {
  226. $prefix .= $this->style('ref', (Cursor::HASH_RESOURCE === $type ? '@' : '#').(0 < $cursor->softRefHandle ? $cursor->softRefHandle : $cursor->softRefTo), array('count' => $cursor->softRefCount));
  227. } elseif ($cursor->hardRefTo && !$cursor->refIndex && $class) {
  228. $prefix .= $this->style('ref', '&'.$cursor->hardRefTo, array('count' => $cursor->hardRefCount));
  229. } elseif (!$hasChild && Cursor::HASH_RESOURCE === $type) {
  230. $prefix = substr($prefix, 0, -1);
  231. }
  232. $this->line .= $prefix;
  233. if ($hasChild) {
  234. $this->dumpLine($cursor->depth);
  235. }
  236. }
  237. /**
  238. * {@inheritdoc}
  239. */
  240. public function leaveHash(Cursor $cursor, $type, $class, $hasChild, $cut)
  241. {
  242. $this->dumpEllipsis($cursor, $hasChild, $cut);
  243. $this->line .= Cursor::HASH_OBJECT === $type ? '}' : (Cursor::HASH_RESOURCE !== $type ? ']' : ($hasChild ? '}' : ''));
  244. $this->dumpLine($cursor->depth, true);
  245. }
  246. /**
  247. * Dumps an ellipsis for cut children.
  248. *
  249. * @param Cursor $cursor The Cursor position in the dump
  250. * @param bool $hasChild When the dump of the hash has child item
  251. * @param int $cut The number of items the hash has been cut by
  252. */
  253. protected function dumpEllipsis(Cursor $cursor, $hasChild, $cut)
  254. {
  255. if ($cut) {
  256. $this->line .= ' …';
  257. if (0 < $cut) {
  258. $this->line .= $cut;
  259. }
  260. if ($hasChild) {
  261. $this->dumpLine($cursor->depth + 1);
  262. }
  263. }
  264. }
  265. /**
  266. * Dumps a key in a hash structure.
  267. *
  268. * @param Cursor $cursor The Cursor position in the dump
  269. */
  270. protected function dumpKey(Cursor $cursor)
  271. {
  272. if (null !== $key = $cursor->hashKey) {
  273. if ($cursor->hashKeyIsBinary) {
  274. $key = $this->utf8Encode($key);
  275. }
  276. $attr = array('binary' => $cursor->hashKeyIsBinary);
  277. $bin = $cursor->hashKeyIsBinary ? 'b' : '';
  278. $style = 'key';
  279. switch ($cursor->hashType) {
  280. default:
  281. case Cursor::HASH_INDEXED:
  282. $style = 'index';
  283. // no break
  284. case Cursor::HASH_ASSOC:
  285. if (is_int($key)) {
  286. $this->line .= $this->style($style, $key).' => ';
  287. } else {
  288. $this->line .= $bin.'"'.$this->style($style, $key).'" => ';
  289. }
  290. break;
  291. case Cursor::HASH_RESOURCE:
  292. $key = "\0~\0".$key;
  293. // no break
  294. case Cursor::HASH_OBJECT:
  295. if (!isset($key[0]) || "\0" !== $key[0]) {
  296. $this->line .= '+'.$bin.$this->style('public', $key).': ';
  297. } elseif (0 < strpos($key, "\0", 1)) {
  298. $key = explode("\0", substr($key, 1), 2);
  299. switch ($key[0]) {
  300. case '+': // User inserted keys
  301. $attr['dynamic'] = true;
  302. $this->line .= '+'.$bin.'"'.$this->style('public', $key[1], $attr).'": ';
  303. break 2;
  304. case '~':
  305. $style = 'meta';
  306. break;
  307. case '*':
  308. $style = 'protected';
  309. $bin = '#'.$bin;
  310. break;
  311. default:
  312. $attr['class'] = $key[0];
  313. $style = 'private';
  314. $bin = '-'.$bin;
  315. break;
  316. }
  317. $this->line .= $bin.$this->style($style, $key[1], $attr).': ';
  318. } else {
  319. // This case should not happen
  320. $this->line .= '-'.$bin.'"'.$this->style('private', $key, array('class' => '')).'": ';
  321. }
  322. break;
  323. }
  324. if ($cursor->hardRefTo) {
  325. $this->line .= $this->style('ref', '&'.($cursor->hardRefCount ? $cursor->hardRefTo : ''), array('count' => $cursor->hardRefCount)).' ';
  326. }
  327. }
  328. }
  329. /**
  330. * Decorates a value with some style.
  331. *
  332. * @param string $style The type of style being applied
  333. * @param string $value The value being styled
  334. * @param array $attr Optional context information
  335. *
  336. * @return string The value with style decoration
  337. */
  338. protected function style($style, $value, $attr = array())
  339. {
  340. if (null === $this->colors) {
  341. $this->colors = $this->supportsColors();
  342. }
  343. $style = $this->styles[$style];
  344. $map = static::$controlCharsMap;
  345. $startCchr = $this->colors ? "\033[m\033[{$this->styles['default']}m" : '';
  346. $endCchr = $this->colors ? "\033[m\033[{$style}m" : '';
  347. $value = preg_replace_callback(static::$controlCharsRx, function ($c) use ($map, $startCchr, $endCchr) {
  348. $s = $startCchr;
  349. $c = $c[$i = 0];
  350. do {
  351. $s .= isset($map[$c[$i]]) ? $map[$c[$i]] : sprintf('\x%02X', ord($c[$i]));
  352. } while (isset($c[++$i]));
  353. return $s.$endCchr;
  354. }, $value, -1, $cchrCount);
  355. if ($this->colors) {
  356. if ($cchrCount && "\033" === $value[0]) {
  357. $value = substr($value, strlen($startCchr));
  358. } else {
  359. $value = "\033[{$style}m".$value;
  360. }
  361. if ($cchrCount && $endCchr === substr($value, -strlen($endCchr))) {
  362. $value = substr($value, 0, -strlen($endCchr));
  363. } else {
  364. $value .= "\033[{$this->styles['default']}m";
  365. }
  366. }
  367. return $value;
  368. }
  369. /**
  370. * @return bool Tells if the current output stream supports ANSI colors or not
  371. */
  372. protected function supportsColors()
  373. {
  374. if ($this->outputStream !== static::$defaultOutput) {
  375. return @(is_resource($this->outputStream) && function_exists('posix_isatty') && posix_isatty($this->outputStream));
  376. }
  377. if (null !== static::$defaultColors) {
  378. return static::$defaultColors;
  379. }
  380. if (isset($_SERVER['argv'][1])) {
  381. $colors = $_SERVER['argv'];
  382. $i = count($colors);
  383. while (--$i > 0) {
  384. if (isset($colors[$i][5])) {
  385. switch ($colors[$i]) {
  386. case '--ansi':
  387. case '--color':
  388. case '--color=yes':
  389. case '--color=force':
  390. case '--color=always':
  391. return static::$defaultColors = true;
  392. case '--no-ansi':
  393. case '--color=no':
  394. case '--color=none':
  395. case '--color=never':
  396. return static::$defaultColors = false;
  397. }
  398. }
  399. }
  400. }
  401. if ('\\' === DIRECTORY_SEPARATOR) {
  402. static::$defaultColors = @(
  403. function_exists('sapi_windows_vt100_support') && sapi_windows_vt100_support($this->outputStream)
  404. || '10.0.10586' === PHP_WINDOWS_VERSION_MAJOR.'.'.PHP_WINDOWS_VERSION_MINOR.'.'.PHP_WINDOWS_VERSION_BUILD
  405. || false !== getenv('ANSICON')
  406. || 'ON' === getenv('ConEmuANSI')
  407. || 'xterm' === getenv('TERM')
  408. );
  409. } elseif (function_exists('posix_isatty')) {
  410. $h = stream_get_meta_data($this->outputStream) + array('wrapper_type' => null);
  411. $h = 'Output' === $h['stream_type'] && 'PHP' === $h['wrapper_type'] ? fopen('php://stdout', 'wb') : $this->outputStream;
  412. static::$defaultColors = @posix_isatty($h);
  413. } else {
  414. static::$defaultColors = false;
  415. }
  416. return static::$defaultColors;
  417. }
  418. /**
  419. * {@inheritdoc}
  420. */
  421. protected function dumpLine($depth, $endOfValue = false)
  422. {
  423. if ($this->colors) {
  424. $this->line = sprintf("\033[%sm%s\033[m", $this->styles['default'], $this->line);
  425. }
  426. parent::dumpLine($depth);
  427. }
  428. }