CliDumper.php 15 KB

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