blob: c1539ee050d5608c6f9e4a4cb8b682f22f00d026 [file] [log] [blame]
Matthias Andreas Benkard7b2a3a12021-08-16 10:57:25 +02001<?php
2
3/*
4 * This file is part of the Symfony package.
5 *
6 * (c) Fabien Potencier <fabien@symfony.com>
7 *
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
10 */
11
12namespace Symfony\Component\VarDumper\Dumper;
13
14use Symfony\Component\VarDumper\Cloner\Cursor;
15use Symfony\Component\VarDumper\Cloner\Stub;
16
17/**
18 * CliDumper dumps variables for command line output.
19 *
20 * @author Nicolas Grekas <p@tchwork.com>
21 */
22class CliDumper extends AbstractDumper
23{
24 public static $defaultColors;
25 public static $defaultOutput = 'php://stdout';
26
27 protected $colors;
28 protected $maxStringWidth = 0;
29 protected $styles = [
30 // See http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
31 'default' => '0;38;5;208',
32 'num' => '1;38;5;38',
33 'const' => '1;38;5;208',
34 'str' => '1;38;5;113',
35 'note' => '38;5;38',
36 'ref' => '38;5;247',
37 'public' => '',
38 'protected' => '',
39 'private' => '',
40 'meta' => '38;5;170',
41 'key' => '38;5;113',
42 'index' => '38;5;38',
43 ];
44
45 protected static $controlCharsRx = '/[\x00-\x1F\x7F]+/';
46 protected static $controlCharsMap = [
47 "\t" => '\t',
48 "\n" => '\n',
49 "\v" => '\v',
50 "\f" => '\f',
51 "\r" => '\r',
52 "\033" => '\e',
53 ];
54
55 protected $collapseNextHash = false;
56 protected $expandNextHash = false;
57
58 private $displayOptions = [
59 'fileLinkFormat' => null,
60 ];
61
62 private $handlesHrefGracefully;
63
64 /**
65 * {@inheritdoc}
66 */
67 public function __construct($output = null, string $charset = null, int $flags = 0)
68 {
69 parent::__construct($output, $charset, $flags);
70
71 if ('\\' === \DIRECTORY_SEPARATOR && !$this->isWindowsTrueColor()) {
72 // Use only the base 16 xterm colors when using ANSICON or standard Windows 10 CLI
73 $this->setStyles([
74 'default' => '31',
75 'num' => '1;34',
76 'const' => '1;31',
77 'str' => '1;32',
78 'note' => '34',
79 'ref' => '1;30',
80 'meta' => '35',
81 'key' => '32',
82 'index' => '34',
83 ]);
84 }
85
86 $this->displayOptions['fileLinkFormat'] = ini_get('xdebug.file_link_format') ?: get_cfg_var('xdebug.file_link_format') ?: 'file://%f#L%l';
87 }
88
89 /**
90 * Enables/disables colored output.
91 */
92 public function setColors(bool $colors)
93 {
94 $this->colors = $colors;
95 }
96
97 /**
98 * Sets the maximum number of characters per line for dumped strings.
99 */
100 public function setMaxStringWidth(int $maxStringWidth)
101 {
102 $this->maxStringWidth = $maxStringWidth;
103 }
104
105 /**
106 * Configures styles.
107 *
108 * @param array $styles A map of style names to style definitions
109 */
110 public function setStyles(array $styles)
111 {
112 $this->styles = $styles + $this->styles;
113 }
114
115 /**
116 * Configures display options.
117 *
118 * @param array $displayOptions A map of display options to customize the behavior
119 */
120 public function setDisplayOptions(array $displayOptions)
121 {
122 $this->displayOptions = $displayOptions + $this->displayOptions;
123 }
124
125 /**
126 * {@inheritdoc}
127 */
128 public function dumpScalar(Cursor $cursor, string $type, $value)
129 {
130 $this->dumpKey($cursor);
131
132 $style = 'const';
133 $attr = $cursor->attr;
134
135 switch ($type) {
136 case 'default':
137 $style = 'default';
138 break;
139
140 case 'integer':
141 $style = 'num';
142 break;
143
144 case 'double':
145 $style = 'num';
146
147 switch (true) {
148 case \INF === $value: $value = 'INF'; break;
149 case -\INF === $value: $value = '-INF'; break;
150 case is_nan($value): $value = 'NAN'; break;
151 default:
152 $value = (string) $value;
153 if (!str_contains($value, $this->decimalPoint)) {
154 $value .= $this->decimalPoint.'0';
155 }
156 break;
157 }
158 break;
159
160 case 'NULL':
161 $value = 'null';
162 break;
163
164 case 'boolean':
165 $value = $value ? 'true' : 'false';
166 break;
167
168 default:
169 $attr += ['value' => $this->utf8Encode($value)];
170 $value = $this->utf8Encode($type);
171 break;
172 }
173
174 $this->line .= $this->style($style, $value, $attr);
175
176 $this->endValue($cursor);
177 }
178
179 /**
180 * {@inheritdoc}
181 */
182 public function dumpString(Cursor $cursor, string $str, bool $bin, int $cut)
183 {
184 $this->dumpKey($cursor);
185 $attr = $cursor->attr;
186
187 if ($bin) {
188 $str = $this->utf8Encode($str);
189 }
190 if ('' === $str) {
191 $this->line .= '""';
192 $this->endValue($cursor);
193 } else {
194 $attr += [
195 'length' => 0 <= $cut ? mb_strlen($str, 'UTF-8') + $cut : 0,
196 'binary' => $bin,
197 ];
198 $str = $bin && false !== strpos($str, "\0") ? [$str] : explode("\n", $str);
199 if (isset($str[1]) && !isset($str[2]) && !isset($str[1][0])) {
200 unset($str[1]);
201 $str[0] .= "\n";
202 }
203 $m = \count($str) - 1;
204 $i = $lineCut = 0;
205
206 if (self::DUMP_STRING_LENGTH & $this->flags) {
207 $this->line .= '('.$attr['length'].') ';
208 }
209 if ($bin) {
210 $this->line .= 'b';
211 }
212
213 if ($m) {
214 $this->line .= '"""';
215 $this->dumpLine($cursor->depth);
216 } else {
217 $this->line .= '"';
218 }
219
220 foreach ($str as $str) {
221 if ($i < $m) {
222 $str .= "\n";
223 }
224 if (0 < $this->maxStringWidth && $this->maxStringWidth < $len = mb_strlen($str, 'UTF-8')) {
225 $str = mb_substr($str, 0, $this->maxStringWidth, 'UTF-8');
226 $lineCut = $len - $this->maxStringWidth;
227 }
228 if ($m && 0 < $cursor->depth) {
229 $this->line .= $this->indentPad;
230 }
231 if ('' !== $str) {
232 $this->line .= $this->style('str', $str, $attr);
233 }
234 if ($i++ == $m) {
235 if ($m) {
236 if ('' !== $str) {
237 $this->dumpLine($cursor->depth);
238 if (0 < $cursor->depth) {
239 $this->line .= $this->indentPad;
240 }
241 }
242 $this->line .= '"""';
243 } else {
244 $this->line .= '"';
245 }
246 if ($cut < 0) {
247 $this->line .= '…';
248 $lineCut = 0;
249 } elseif ($cut) {
250 $lineCut += $cut;
251 }
252 }
253 if ($lineCut) {
254 $this->line .= '…'.$lineCut;
255 $lineCut = 0;
256 }
257
258 if ($i > $m) {
259 $this->endValue($cursor);
260 } else {
261 $this->dumpLine($cursor->depth);
262 }
263 }
264 }
265 }
266
267 /**
268 * {@inheritdoc}
269 */
270 public function enterHash(Cursor $cursor, int $type, $class, bool $hasChild)
271 {
272 if (null === $this->colors) {
273 $this->colors = $this->supportsColors();
274 }
275
276 $this->dumpKey($cursor);
277 $attr = $cursor->attr;
278
279 if ($this->collapseNextHash) {
280 $cursor->skipChildren = true;
281 $this->collapseNextHash = $hasChild = false;
282 }
283
284 $class = $this->utf8Encode($class);
285 if (Cursor::HASH_OBJECT === $type) {
286 $prefix = $class && 'stdClass' !== $class ? $this->style('note', $class, $attr).(empty($attr['cut_hash']) ? ' {' : '') : '{';
287 } elseif (Cursor::HASH_RESOURCE === $type) {
288 $prefix = $this->style('note', $class.' resource', $attr).($hasChild ? ' {' : ' ');
289 } else {
290 $prefix = $class && !(self::DUMP_LIGHT_ARRAY & $this->flags) ? $this->style('note', 'array:'.$class).' [' : '[';
291 }
292
293 if (($cursor->softRefCount || 0 < $cursor->softRefHandle) && empty($attr['cut_hash'])) {
294 $prefix .= $this->style('ref', (Cursor::HASH_RESOURCE === $type ? '@' : '#').(0 < $cursor->softRefHandle ? $cursor->softRefHandle : $cursor->softRefTo), ['count' => $cursor->softRefCount]);
295 } elseif ($cursor->hardRefTo && !$cursor->refIndex && $class) {
296 $prefix .= $this->style('ref', '&'.$cursor->hardRefTo, ['count' => $cursor->hardRefCount]);
297 } elseif (!$hasChild && Cursor::HASH_RESOURCE === $type) {
298 $prefix = substr($prefix, 0, -1);
299 }
300
301 $this->line .= $prefix;
302
303 if ($hasChild) {
304 $this->dumpLine($cursor->depth);
305 }
306 }
307
308 /**
309 * {@inheritdoc}
310 */
311 public function leaveHash(Cursor $cursor, int $type, $class, bool $hasChild, int $cut)
312 {
313 if (empty($cursor->attr['cut_hash'])) {
314 $this->dumpEllipsis($cursor, $hasChild, $cut);
315 $this->line .= Cursor::HASH_OBJECT === $type ? '}' : (Cursor::HASH_RESOURCE !== $type ? ']' : ($hasChild ? '}' : ''));
316 }
317
318 $this->endValue($cursor);
319 }
320
321 /**
322 * Dumps an ellipsis for cut children.
323 *
324 * @param bool $hasChild When the dump of the hash has child item
325 * @param int $cut The number of items the hash has been cut by
326 */
327 protected function dumpEllipsis(Cursor $cursor, bool $hasChild, int $cut)
328 {
329 if ($cut) {
330 $this->line .= ' …';
331 if (0 < $cut) {
332 $this->line .= $cut;
333 }
334 if ($hasChild) {
335 $this->dumpLine($cursor->depth + 1);
336 }
337 }
338 }
339
340 /**
341 * Dumps a key in a hash structure.
342 */
343 protected function dumpKey(Cursor $cursor)
344 {
345 if (null !== $key = $cursor->hashKey) {
346 if ($cursor->hashKeyIsBinary) {
347 $key = $this->utf8Encode($key);
348 }
349 $attr = ['binary' => $cursor->hashKeyIsBinary];
350 $bin = $cursor->hashKeyIsBinary ? 'b' : '';
351 $style = 'key';
352 switch ($cursor->hashType) {
353 default:
354 case Cursor::HASH_INDEXED:
355 if (self::DUMP_LIGHT_ARRAY & $this->flags) {
356 break;
357 }
358 $style = 'index';
359 // no break
360 case Cursor::HASH_ASSOC:
361 if (\is_int($key)) {
362 $this->line .= $this->style($style, $key).' => ';
363 } else {
364 $this->line .= $bin.'"'.$this->style($style, $key).'" => ';
365 }
366 break;
367
368 case Cursor::HASH_RESOURCE:
369 $key = "\0~\0".$key;
370 // no break
371 case Cursor::HASH_OBJECT:
372 if (!isset($key[0]) || "\0" !== $key[0]) {
373 $this->line .= '+'.$bin.$this->style('public', $key).': ';
374 } elseif (0 < strpos($key, "\0", 1)) {
375 $key = explode("\0", substr($key, 1), 2);
376
377 switch ($key[0][0]) {
378 case '+': // User inserted keys
379 $attr['dynamic'] = true;
380 $this->line .= '+'.$bin.'"'.$this->style('public', $key[1], $attr).'": ';
381 break 2;
382 case '~':
383 $style = 'meta';
384 if (isset($key[0][1])) {
385 parse_str(substr($key[0], 1), $attr);
386 $attr += ['binary' => $cursor->hashKeyIsBinary];
387 }
388 break;
389 case '*':
390 $style = 'protected';
391 $bin = '#'.$bin;
392 break;
393 default:
394 $attr['class'] = $key[0];
395 $style = 'private';
396 $bin = '-'.$bin;
397 break;
398 }
399
400 if (isset($attr['collapse'])) {
401 if ($attr['collapse']) {
402 $this->collapseNextHash = true;
403 } else {
404 $this->expandNextHash = true;
405 }
406 }
407
408 $this->line .= $bin.$this->style($style, $key[1], $attr).($attr['separator'] ?? ': ');
409 } else {
410 // This case should not happen
411 $this->line .= '-'.$bin.'"'.$this->style('private', $key, ['class' => '']).'": ';
412 }
413 break;
414 }
415
416 if ($cursor->hardRefTo) {
417 $this->line .= $this->style('ref', '&'.($cursor->hardRefCount ? $cursor->hardRefTo : ''), ['count' => $cursor->hardRefCount]).' ';
418 }
419 }
420 }
421
422 /**
423 * Decorates a value with some style.
424 *
425 * @param string $style The type of style being applied
426 * @param string $value The value being styled
427 * @param array $attr Optional context information
428 *
429 * @return string The value with style decoration
430 */
431 protected function style(string $style, string $value, array $attr = [])
432 {
433 if (null === $this->colors) {
434 $this->colors = $this->supportsColors();
435 }
436
437 if (null === $this->handlesHrefGracefully) {
438 $this->handlesHrefGracefully = 'JetBrains-JediTerm' !== getenv('TERMINAL_EMULATOR')
439 && (!getenv('KONSOLE_VERSION') || (int) getenv('KONSOLE_VERSION') > 201100);
440 }
441
442 if (isset($attr['ellipsis'], $attr['ellipsis-type'])) {
443 $prefix = substr($value, 0, -$attr['ellipsis']);
444 if ('cli' === \PHP_SAPI && 'path' === $attr['ellipsis-type'] && isset($_SERVER[$pwd = '\\' === \DIRECTORY_SEPARATOR ? 'CD' : 'PWD']) && str_starts_with($prefix, $_SERVER[$pwd])) {
445 $prefix = '.'.substr($prefix, \strlen($_SERVER[$pwd]));
446 }
447 if (!empty($attr['ellipsis-tail'])) {
448 $prefix .= substr($value, -$attr['ellipsis'], $attr['ellipsis-tail']);
449 $value = substr($value, -$attr['ellipsis'] + $attr['ellipsis-tail']);
450 } else {
451 $value = substr($value, -$attr['ellipsis']);
452 }
453
454 $value = $this->style('default', $prefix).$this->style($style, $value);
455
456 goto href;
457 }
458
459 $map = static::$controlCharsMap;
460 $startCchr = $this->colors ? "\033[m\033[{$this->styles['default']}m" : '';
461 $endCchr = $this->colors ? "\033[m\033[{$this->styles[$style]}m" : '';
462 $value = preg_replace_callback(static::$controlCharsRx, function ($c) use ($map, $startCchr, $endCchr) {
463 $s = $startCchr;
464 $c = $c[$i = 0];
465 do {
466 $s .= $map[$c[$i]] ?? sprintf('\x%02X', \ord($c[$i]));
467 } while (isset($c[++$i]));
468
469 return $s.$endCchr;
470 }, $value, -1, $cchrCount);
471
472 if ($this->colors) {
473 if ($cchrCount && "\033" === $value[0]) {
474 $value = substr($value, \strlen($startCchr));
475 } else {
476 $value = "\033[{$this->styles[$style]}m".$value;
477 }
478 if ($cchrCount && str_ends_with($value, $endCchr)) {
479 $value = substr($value, 0, -\strlen($endCchr));
480 } else {
481 $value .= "\033[{$this->styles['default']}m";
482 }
483 }
484
485 href:
486 if ($this->colors && $this->handlesHrefGracefully) {
487 if (isset($attr['file']) && $href = $this->getSourceLink($attr['file'], $attr['line'] ?? 0)) {
488 if ('note' === $style) {
489 $value .= "\033]8;;{$href}\033\\^\033]8;;\033\\";
490 } else {
491 $attr['href'] = $href;
492 }
493 }
494 if (isset($attr['href'])) {
495 $value = "\033]8;;{$attr['href']}\033\\{$value}\033]8;;\033\\";
496 }
497 } elseif ($attr['if_links'] ?? false) {
498 return '';
499 }
500
501 return $value;
502 }
503
504 /**
505 * @return bool Tells if the current output stream supports ANSI colors or not
506 */
507 protected function supportsColors()
508 {
509 if ($this->outputStream !== static::$defaultOutput) {
510 return $this->hasColorSupport($this->outputStream);
511 }
512 if (null !== static::$defaultColors) {
513 return static::$defaultColors;
514 }
515 if (isset($_SERVER['argv'][1])) {
516 $colors = $_SERVER['argv'];
517 $i = \count($colors);
518 while (--$i > 0) {
519 if (isset($colors[$i][5])) {
520 switch ($colors[$i]) {
521 case '--ansi':
522 case '--color':
523 case '--color=yes':
524 case '--color=force':
525 case '--color=always':
526 case '--colors=always':
527 return static::$defaultColors = true;
528
529 case '--no-ansi':
530 case '--color=no':
531 case '--color=none':
532 case '--color=never':
533 case '--colors=never':
534 return static::$defaultColors = false;
535 }
536 }
537 }
538 }
539
540 $h = stream_get_meta_data($this->outputStream) + ['wrapper_type' => null];
541 $h = 'Output' === $h['stream_type'] && 'PHP' === $h['wrapper_type'] ? fopen('php://stdout', 'w') : $this->outputStream;
542
543 return static::$defaultColors = $this->hasColorSupport($h);
544 }
545
546 /**
547 * {@inheritdoc}
548 */
549 protected function dumpLine(int $depth, bool $endOfValue = false)
550 {
551 if ($this->colors) {
552 $this->line = sprintf("\033[%sm%s\033[m", $this->styles['default'], $this->line);
553 }
554 parent::dumpLine($depth);
555 }
556
557 protected function endValue(Cursor $cursor)
558 {
559 if (-1 === $cursor->hashType) {
560 return;
561 }
562
563 if (Stub::ARRAY_INDEXED === $cursor->hashType || Stub::ARRAY_ASSOC === $cursor->hashType) {
564 if (self::DUMP_TRAILING_COMMA & $this->flags && 0 < $cursor->depth) {
565 $this->line .= ',';
566 } elseif (self::DUMP_COMMA_SEPARATOR & $this->flags && 1 < $cursor->hashLength - $cursor->hashIndex) {
567 $this->line .= ',';
568 }
569 }
570
571 $this->dumpLine($cursor->depth, true);
572 }
573
574 /**
575 * Returns true if the stream supports colorization.
576 *
577 * Reference: Composer\XdebugHandler\Process::supportsColor
578 * https://github.com/composer/xdebug-handler
579 *
580 * @param mixed $stream A CLI output stream
581 */
582 private function hasColorSupport($stream): bool
583 {
584 if (!\is_resource($stream) || 'stream' !== get_resource_type($stream)) {
585 return false;
586 }
587
588 // Follow https://no-color.org/
589 if (isset($_SERVER['NO_COLOR']) || false !== getenv('NO_COLOR')) {
590 return false;
591 }
592
593 if ('Hyper' === getenv('TERM_PROGRAM')) {
594 return true;
595 }
596
597 if (\DIRECTORY_SEPARATOR === '\\') {
598 return (\function_exists('sapi_windows_vt100_support')
599 && @sapi_windows_vt100_support($stream))
600 || false !== getenv('ANSICON')
601 || 'ON' === getenv('ConEmuANSI')
602 || 'xterm' === getenv('TERM');
603 }
604
605 return stream_isatty($stream);
606 }
607
608 /**
609 * Returns true if the Windows terminal supports true color.
610 *
611 * Note that this does not check an output stream, but relies on environment
612 * variables from known implementations, or a PHP and Windows version that
613 * supports true color.
614 */
615 private function isWindowsTrueColor(): bool
616 {
617 $result = 183 <= getenv('ANSICON_VER')
618 || 'ON' === getenv('ConEmuANSI')
619 || 'xterm' === getenv('TERM')
620 || 'Hyper' === getenv('TERM_PROGRAM');
621
622 if (!$result) {
623 $version = sprintf(
624 '%s.%s.%s',
625 PHP_WINDOWS_VERSION_MAJOR,
626 PHP_WINDOWS_VERSION_MINOR,
627 PHP_WINDOWS_VERSION_BUILD
628 );
629 $result = $version >= '10.0.15063';
630 }
631
632 return $result;
633 }
634
635 private function getSourceLink(string $file, int $line)
636 {
637 if ($fmt = $this->displayOptions['fileLinkFormat']) {
638 return \is_string($fmt) ? strtr($fmt, ['%f' => $file, '%l' => $line]) : ($fmt->format($file, $line) ?: 'file://'.$file.'#L'.$line);
639 }
640
641 return false;
642 }
643}