菜谱项目

CliDumper.php 17KB

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