Subversion-Projekte lars-tiefland.laravel_shop

Revision

Zur aktuellen Revision | Details | Letzte Änderung | Log anzeigen | RSS feed

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