summaryrefslogtreecommitdiff
path: root/vendor/open-telemetry/sdk/Common/Exception/StackTraceFormatter.php
blob: 675fc762689489d926fc04a938794765016ba331 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
<?php

declare(strict_types=1);

namespace OpenTelemetry\SDK\Common\Exception;

use function basename;
use function count;
use function get_class;
use function sprintf;
use function str_repeat;

use Throwable;

/**
 * @psalm-type Frame = array{
 *     function: string,
 *     class: ?class-string,
 *     file: ?string,
 *     line: ?int,
 * }
 * @psalm-type Frames = non-empty-list<Frame>
 */
final class StackTraceFormatter
{
    private function __construct()
    {
    }

    /**
     * Formats an exception in a java-like format.
     *
     * @param Throwable $e exception to format
     * @return string formatted exception
     *
     * @see https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/Throwable.html#printStackTrace()
     */
    public static function format(Throwable $e): string
    {
        $s = '';
        $seen = [];

        /** @var Frames|null $enclosing */
        $enclosing = null;
        do {
            if ($enclosing) {
                self::writeNewline($s);
                $s .= 'Caused by: ';
            }
            if (isset($seen[spl_object_id($e)])) {
                $s .= '[CIRCULAR REFERENCE: ';
                self::writeInlineHeader($s, $e);
                $s .= ']';

                break;
            }
            $seen[spl_object_id($e)] = $e;

            $frames = self::frames($e);
            self::writeInlineHeader($s, $e);
            self::writeFrames($s, $frames, $enclosing);

            $enclosing = $frames;
        } while ($e = $e->getPrevious());

        return $s;
    }

    /**
     * @phan-suppress-next-line PhanTypeMismatchDeclaredParam
     * @param Frames $frames
     * @phan-suppress-next-line PhanTypeMismatchDeclaredParam
     * @param Frames|null $enclosing
     */
    private static function writeFrames(string &$s, array $frames, ?array $enclosing): void
    {
        $n = count($frames);
        if ($enclosing) {
            for ($m = count($enclosing);
                 $n && $m && $frames[$n - 1] === $enclosing[$m - 1];
                 $n--, $m--) {
            }
        }
        for ($i = 0; $i < $n; $i++) {
            $frame = $frames[$i];
            self::writeNewline($s, 1);
            $s .= 'at ';
            if ($frame['class'] !== null) {
                $s .= self::formatName($frame['class']);
                $s .= '.';
            }
            $s .= self::formatName($frame['function']);
            $s .= '(';
            if ($frame['file'] !== null) {
                $s .= basename($frame['file']);
                if ($frame['line']) {
                    $s .= ':';
                    $s .= $frame['line'];
                }
            } else {
                $s .= 'Unknown Source';
            }
            $s .= ')';
        }
        if ($n !== count($frames)) {
            self::writeNewline($s, 1);
            $s .= sprintf('... %d more', count($frames) - $n);
        }
    }

    private static function writeInlineHeader(string &$s, Throwable $e): void
    {
        $s .= self::formatName(get_class($e));
        if ($e->getMessage() !== '') {
            $s .= ': ';
            $s .= $e->getMessage();
        }
    }

    private static function writeNewline(string &$s, int $indent = 0): void
    {
        $s .= "\n";
        $s .= str_repeat("\t", $indent);
    }

    /**
     * @return Frames
     *
     * @psalm-suppress PossiblyUndefinedArrayOffset
     */
    private static function frames(Throwable $e): array
    {
        $frames = [];
        $trace = $e->getTrace();
        $traceCount = count($trace);
        for ($i = 0; $i < $traceCount + 1; $i++) {
            $frames[] = [
                'function' => $trace[$i]['function'] ?? '{main}',
                'class' => $trace[$i]['class'] ?? null,
                'file' => $trace[$i - 1]['file'] ?? null,
                'line' => $trace[$i - 1]['line'] ?? null,
            ];
        }
        $frames[0]['file'] = $e->getFile();
        $frames[0]['line'] = $e->getLine();

        /** @var Frames $frames */
        return $frames;
    }

    private static function formatName(string $name): string
    {
        return strtr($name, ['\\' => '.']);
    }
}