Subversion-Projekte lars-tiefland.laravel_shop

Revision

Revision 148 | Details | Vergleich mit vorheriger | 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 .= '""';
991 lars 187
            if ($cut) {
188
                $this->line .= '…'.$cut;
189
            }
148 lars 190
            $this->endValue($cursor);
191
        } else {
192
            $attr += [
193
                'length' => 0 <= $cut ? mb_strlen($str, 'UTF-8') + $cut : 0,
194
                'binary' => $bin,
195
            ];
196
            $str = $bin && str_contains($str, "\0") ? [$str] : explode("\n", $str);
197
            if (isset($str[1]) && !isset($str[2]) && !isset($str[1][0])) {
198
                unset($str[1]);
199
                $str[0] .= "\n";
200
            }
201
            $m = \count($str) - 1;
202
            $i = $lineCut = 0;
203
 
204
            if (self::DUMP_STRING_LENGTH & $this->flags) {
205
                $this->line .= '('.$attr['length'].') ';
206
            }
207
            if ($bin) {
208
                $this->line .= 'b';
209
            }
210
 
211
            if ($m) {
212
                $this->line .= '"""';
213
                $this->dumpLine($cursor->depth);
214
            } else {
215
                $this->line .= '"';
216
            }
217
 
218
            foreach ($str as $str) {
219
                if ($i < $m) {
220
                    $str .= "\n";
221
                }
222
                if (0 < $this->maxStringWidth && $this->maxStringWidth < $len = mb_strlen($str, 'UTF-8')) {
223
                    $str = mb_substr($str, 0, $this->maxStringWidth, 'UTF-8');
224
                    $lineCut = $len - $this->maxStringWidth;
225
                }
226
                if ($m && 0 < $cursor->depth) {
227
                    $this->line .= $this->indentPad;
228
                }
229
                if ('' !== $str) {
230
                    $this->line .= $this->style('str', $str, $attr);
231
                }
232
                if ($i++ == $m) {
233
                    if ($m) {
234
                        if ('' !== $str) {
235
                            $this->dumpLine($cursor->depth);
236
                            if (0 < $cursor->depth) {
237
                                $this->line .= $this->indentPad;
238
                            }
239
                        }
240
                        $this->line .= '"""';
241
                    } else {
242
                        $this->line .= '"';
243
                    }
244
                    if ($cut < 0) {
245
                        $this->line .= '…';
246
                        $lineCut = 0;
247
                    } elseif ($cut) {
248
                        $lineCut += $cut;
249
                    }
250
                }
251
                if ($lineCut) {
252
                    $this->line .= '…'.$lineCut;
253
                    $lineCut = 0;
254
                }
255
 
256
                if ($i > $m) {
257
                    $this->endValue($cursor);
258
                } else {
259
                    $this->dumpLine($cursor->depth);
260
                }
261
            }
262
        }
263
    }
264
 
265
    public function enterHash(Cursor $cursor, int $type, string|int|null $class, bool $hasChild)
266
    {
267
        $this->colors ??= $this->supportsColors();
268
 
269
        $this->dumpKey($cursor);
270
        $attr = $cursor->attr;
271
 
272
        if ($this->collapseNextHash) {
273
            $cursor->skipChildren = true;
274
            $this->collapseNextHash = $hasChild = false;
275
        }
276
 
277
        $class = $this->utf8Encode($class);
278
        if (Cursor::HASH_OBJECT === $type) {
279
            $prefix = $class && 'stdClass' !== $class ? $this->style('note', $class, $attr).(empty($attr['cut_hash']) ? ' {' : '') : '{';
280
        } elseif (Cursor::HASH_RESOURCE === $type) {
281
            $prefix = $this->style('note', $class.' resource', $attr).($hasChild ? ' {' : ' ');
282
        } else {
283
            $prefix = $class && !(self::DUMP_LIGHT_ARRAY & $this->flags) ? $this->style('note', 'array:'.$class).' [' : '[';
284
        }
285
 
286
        if (($cursor->softRefCount || 0 < $cursor->softRefHandle) && empty($attr['cut_hash'])) {
287
            $prefix .= $this->style('ref', (Cursor::HASH_RESOURCE === $type ? '@' : '#').(0 < $cursor->softRefHandle ? $cursor->softRefHandle : $cursor->softRefTo), ['count' => $cursor->softRefCount]);
288
        } elseif ($cursor->hardRefTo && !$cursor->refIndex && $class) {
289
            $prefix .= $this->style('ref', '&'.$cursor->hardRefTo, ['count' => $cursor->hardRefCount]);
290
        } elseif (!$hasChild && Cursor::HASH_RESOURCE === $type) {
291
            $prefix = substr($prefix, 0, -1);
292
        }
293
 
294
        $this->line .= $prefix;
295
 
296
        if ($hasChild) {
297
            $this->dumpLine($cursor->depth);
298
        }
299
    }
300
 
301
    public function leaveHash(Cursor $cursor, int $type, string|int|null $class, bool $hasChild, int $cut)
302
    {
303
        if (empty($cursor->attr['cut_hash'])) {
304
            $this->dumpEllipsis($cursor, $hasChild, $cut);
305
            $this->line .= Cursor::HASH_OBJECT === $type ? '}' : (Cursor::HASH_RESOURCE !== $type ? ']' : ($hasChild ? '}' : ''));
306
        }
307
 
308
        $this->endValue($cursor);
309
    }
310
 
311
    /**
312
     * Dumps an ellipsis for cut children.
313
     *
314
     * @param bool $hasChild When the dump of the hash has child item
315
     * @param int  $cut      The number of items the hash has been cut by
316
     */
317
    protected function dumpEllipsis(Cursor $cursor, bool $hasChild, int $cut)
318
    {
319
        if ($cut) {
320
            $this->line .= ' …';
321
            if (0 < $cut) {
322
                $this->line .= $cut;
323
            }
324
            if ($hasChild) {
325
                $this->dumpLine($cursor->depth + 1);
326
            }
327
        }
328
    }
329
 
330
    /**
331
     * Dumps a key in a hash structure.
332
     */
333
    protected function dumpKey(Cursor $cursor)
334
    {
335
        if (null !== $key = $cursor->hashKey) {
336
            if ($cursor->hashKeyIsBinary) {
337
                $key = $this->utf8Encode($key);
338
            }
339
            $attr = ['binary' => $cursor->hashKeyIsBinary];
340
            $bin = $cursor->hashKeyIsBinary ? 'b' : '';
341
            $style = 'key';
342
            switch ($cursor->hashType) {
343
                default:
344
                case Cursor::HASH_INDEXED:
345
                    if (self::DUMP_LIGHT_ARRAY & $this->flags) {
346
                        break;
347
                    }
348
                    $style = 'index';
349
                    // no break
350
                case Cursor::HASH_ASSOC:
351
                    if (\is_int($key)) {
352
                        $this->line .= $this->style($style, $key).' => ';
353
                    } else {
354
                        $this->line .= $bin.'"'.$this->style($style, $key).'" => ';
355
                    }
356
                    break;
357
 
358
                case Cursor::HASH_RESOURCE:
359
                    $key = "\0~\0".$key;
360
                    // no break
361
                case Cursor::HASH_OBJECT:
362
                    if (!isset($key[0]) || "\0" !== $key[0]) {
363
                        $this->line .= '+'.$bin.$this->style('public', $key).': ';
364
                    } elseif (0 < strpos($key, "\0", 1)) {
365
                        $key = explode("\0", substr($key, 1), 2);
366
 
367
                        switch ($key[0][0]) {
368
                            case '+': // User inserted keys
369
                                $attr['dynamic'] = true;
370
                                $this->line .= '+'.$bin.'"'.$this->style('public', $key[1], $attr).'": ';
371
                                break 2;
372
                            case '~':
373
                                $style = 'meta';
374
                                if (isset($key[0][1])) {
375
                                    parse_str(substr($key[0], 1), $attr);
376
                                    $attr += ['binary' => $cursor->hashKeyIsBinary];
377
                                }
378
                                break;
379
                            case '*':
380
                                $style = 'protected';
381
                                $bin = '#'.$bin;
382
                                break;
383
                            default:
384
                                $attr['class'] = $key[0];
385
                                $style = 'private';
386
                                $bin = '-'.$bin;
387
                                break;
388
                        }
389
 
390
                        if (isset($attr['collapse'])) {
391
                            if ($attr['collapse']) {
392
                                $this->collapseNextHash = true;
393
                            } else {
394
                                $this->expandNextHash = true;
395
                            }
396
                        }
397
 
398
                        $this->line .= $bin.$this->style($style, $key[1], $attr).($attr['separator'] ?? ': ');
399
                    } else {
400
                        // This case should not happen
401
                        $this->line .= '-'.$bin.'"'.$this->style('private', $key, ['class' => '']).'": ';
402
                    }
403
                    break;
404
            }
405
 
406
            if ($cursor->hardRefTo) {
407
                $this->line .= $this->style('ref', '&'.($cursor->hardRefCount ? $cursor->hardRefTo : ''), ['count' => $cursor->hardRefCount]).' ';
408
            }
409
        }
410
    }
411
 
412
    /**
413
     * Decorates a value with some style.
414
     *
415
     * @param string $style The type of style being applied
416
     * @param string $value The value being styled
417
     * @param array  $attr  Optional context information
418
     */
419
    protected function style(string $style, string $value, array $attr = []): string
420
    {
421
        $this->colors ??= $this->supportsColors();
422
 
423
        $this->handlesHrefGracefully ??= 'JetBrains-JediTerm' !== getenv('TERMINAL_EMULATOR')
991 lars 424
            && (!getenv('KONSOLE_VERSION') || (int) getenv('KONSOLE_VERSION') > 201100)
425
            && !isset($_SERVER['IDEA_INITIAL_DIRECTORY']);
148 lars 426
 
427
        if (isset($attr['ellipsis'], $attr['ellipsis-type'])) {
428
            $prefix = substr($value, 0, -$attr['ellipsis']);
429
            if ('cli' === \PHP_SAPI && 'path' === $attr['ellipsis-type'] && isset($_SERVER[$pwd = '\\' === \DIRECTORY_SEPARATOR ? 'CD' : 'PWD']) && str_starts_with($prefix, $_SERVER[$pwd])) {
430
                $prefix = '.'.substr($prefix, \strlen($_SERVER[$pwd]));
431
            }
432
            if (!empty($attr['ellipsis-tail'])) {
433
                $prefix .= substr($value, -$attr['ellipsis'], $attr['ellipsis-tail']);
434
                $value = substr($value, -$attr['ellipsis'] + $attr['ellipsis-tail']);
435
            } else {
436
                $value = substr($value, -$attr['ellipsis']);
437
            }
438
 
439
            $value = $this->style('default', $prefix).$this->style($style, $value);
440
 
441
            goto href;
442
        }
443
 
444
        $map = static::$controlCharsMap;
445
        $startCchr = $this->colors ? "\033[m\033[{$this->styles['default']}m" : '';
446
        $endCchr = $this->colors ? "\033[m\033[{$this->styles[$style]}m" : '';
447
        $value = preg_replace_callback(static::$controlCharsRx, function ($c) use ($map, $startCchr, $endCchr) {
448
            $s = $startCchr;
449
            $c = $c[$i = 0];
450
            do {
451
                $s .= $map[$c[$i]] ?? sprintf('\x%02X', \ord($c[$i]));
452
            } while (isset($c[++$i]));
453
 
454
            return $s.$endCchr;
455
        }, $value, -1, $cchrCount);
456
 
457
        if ($this->colors) {
458
            if ($cchrCount && "\033" === $value[0]) {
459
                $value = substr($value, \strlen($startCchr));
460
            } else {
461
                $value = "\033[{$this->styles[$style]}m".$value;
462
            }
463
            if ($cchrCount && str_ends_with($value, $endCchr)) {
464
                $value = substr($value, 0, -\strlen($endCchr));
465
            } else {
466
                $value .= "\033[{$this->styles['default']}m";
467
            }
468
        }
469
 
470
        href:
471
        if ($this->colors && $this->handlesHrefGracefully) {
472
            if (isset($attr['file']) && $href = $this->getSourceLink($attr['file'], $attr['line'] ?? 0)) {
473
                if ('note' === $style) {
474
                    $value .= "\033]8;;{$href}\033\\^\033]8;;\033\\";
475
                } else {
476
                    $attr['href'] = $href;
477
                }
478
            }
479
            if (isset($attr['href'])) {
480
                $value = "\033]8;;{$attr['href']}\033\\{$value}\033]8;;\033\\";
481
            }
482
        } elseif ($attr['if_links'] ?? false) {
483
            return '';
484
        }
485
 
486
        return $value;
487
    }
488
 
489
    protected function supportsColors(): bool
490
    {
491
        if ($this->outputStream !== static::$defaultOutput) {
492
            return $this->hasColorSupport($this->outputStream);
493
        }
494
        if (null !== static::$defaultColors) {
495
            return static::$defaultColors;
496
        }
497
        if (isset($_SERVER['argv'][1])) {
498
            $colors = $_SERVER['argv'];
499
            $i = \count($colors);
500
            while (--$i > 0) {
501
                if (isset($colors[$i][5])) {
502
                    switch ($colors[$i]) {
503
                        case '--ansi':
504
                        case '--color':
505
                        case '--color=yes':
506
                        case '--color=force':
507
                        case '--color=always':
508
                        case '--colors=always':
509
                            return static::$defaultColors = true;
510
 
511
                        case '--no-ansi':
512
                        case '--color=no':
513
                        case '--color=none':
514
                        case '--color=never':
515
                        case '--colors=never':
516
                            return static::$defaultColors = false;
517
                    }
518
                }
519
            }
520
        }
521
 
522
        $h = stream_get_meta_data($this->outputStream) + ['wrapper_type' => null];
523
        $h = 'Output' === $h['stream_type'] && 'PHP' === $h['wrapper_type'] ? fopen('php://stdout', 'w') : $this->outputStream;
524
 
525
        return static::$defaultColors = $this->hasColorSupport($h);
526
    }
527
 
528
    protected function dumpLine(int $depth, bool $endOfValue = false)
529
    {
530
        if ($this->colors) {
531
            $this->line = sprintf("\033[%sm%s\033[m", $this->styles['default'], $this->line);
532
        }
533
        parent::dumpLine($depth);
534
    }
535
 
536
    protected function endValue(Cursor $cursor)
537
    {
538
        if (-1 === $cursor->hashType) {
539
            return;
540
        }
541
 
542
        if (Stub::ARRAY_INDEXED === $cursor->hashType || Stub::ARRAY_ASSOC === $cursor->hashType) {
543
            if (self::DUMP_TRAILING_COMMA & $this->flags && 0 < $cursor->depth) {
544
                $this->line .= ',';
545
            } elseif (self::DUMP_COMMA_SEPARATOR & $this->flags && 1 < $cursor->hashLength - $cursor->hashIndex) {
546
                $this->line .= ',';
547
            }
548
        }
549
 
550
        $this->dumpLine($cursor->depth, true);
551
    }
552
 
553
    /**
554
     * Returns true if the stream supports colorization.
555
     *
556
     * Reference: Composer\XdebugHandler\Process::supportsColor
557
     * https://github.com/composer/xdebug-handler
558
     */
559
    private function hasColorSupport(mixed $stream): bool
560
    {
561
        if (!\is_resource($stream) || 'stream' !== get_resource_type($stream)) {
562
            return false;
563
        }
564
 
565
        // Follow https://no-color.org/
566
        if (isset($_SERVER['NO_COLOR']) || false !== getenv('NO_COLOR')) {
567
            return false;
568
        }
569
 
570
        if ('Hyper' === getenv('TERM_PROGRAM')) {
571
            return true;
572
        }
573
 
574
        if (\DIRECTORY_SEPARATOR === '\\') {
575
            return (\function_exists('sapi_windows_vt100_support')
576
                && @sapi_windows_vt100_support($stream))
577
                || false !== getenv('ANSICON')
578
                || 'ON' === getenv('ConEmuANSI')
579
                || 'xterm' === getenv('TERM');
580
        }
581
 
582
        return stream_isatty($stream);
583
    }
584
 
585
    /**
586
     * Returns true if the Windows terminal supports true color.
587
     *
588
     * Note that this does not check an output stream, but relies on environment
589
     * variables from known implementations, or a PHP and Windows version that
590
     * supports true color.
591
     */
592
    private function isWindowsTrueColor(): bool
593
    {
594
        $result = 183 <= getenv('ANSICON_VER')
595
            || 'ON' === getenv('ConEmuANSI')
596
            || 'xterm' === getenv('TERM')
597
            || 'Hyper' === getenv('TERM_PROGRAM');
598
 
599
        if (!$result) {
600
            $version = sprintf(
601
                '%s.%s.%s',
602
                PHP_WINDOWS_VERSION_MAJOR,
603
                PHP_WINDOWS_VERSION_MINOR,
604
                PHP_WINDOWS_VERSION_BUILD
605
            );
606
            $result = $version >= '10.0.15063';
607
        }
608
 
609
        return $result;
610
    }
611
 
612
    private function getSourceLink(string $file, int $line)
613
    {
614
        if ($fmt = $this->displayOptions['fileLinkFormat']) {
615
            return \is_string($fmt) ? strtr($fmt, ['%f' => $file, '%l' => $line]) : ($fmt->format($file, $line) ?: 'file://'.$file.'#L'.$line);
616
        }
617
 
618
        return false;
619
    }
620
}