Passed
Push — master ( c83e8d...09b513 )
by butschster
07:01
created

ConsoleRenderer   A

Complexity

Total Complexity 37

Size/Duplication

Total Lines 242
Duplicated Lines 0 %

Test Coverage

Coverage 97.3%

Importance

Changes 3
Bugs 0 Features 0
Metric Value
wmc 37
eloc 126
dl 0
loc 242
ccs 108
cts 111
cp 0.973
rs 9.44
c 3
b 0
f 0

7 Methods

Rating   Name   Duplication   Size   Complexity  
A setColorsSupport() 0 3 1
B isColorsSupported() 0 17 8
A renderHeader() 0 23 2
A __construct() 0 5 2
B render() 0 53 9
A format() 0 18 4
B renderTrace() 0 64 11
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Spiral\Exceptions\Renderer;
6
7
use Codedungeon\PHPCliColors\Color;
8
use Spiral\Exceptions\Style\ConsoleStyle;
9
use Spiral\Exceptions\Style\PlainStyle;
10
use Spiral\Exceptions\Verbosity;
11
12
/**
13
 * Verbosity levels:
14
 *
15
 * 1) {@see Verbosity::BASIC} - only message header and line number
16
 * 2) {@see Verbosity::VERBOSE} - stack information
17
 * 3) {@see Verbosity::DEBUG} - stack and source information.
18
 */
19
class ConsoleRenderer extends AbstractRenderer
20
{
21
    // Lines to show around targeted line.
22
    public const SHOW_LINES = 2;
23
    protected const FORMATS = ['console', 'cli'];
24
25
    protected const COLORS = [
26
        'bg:red' => Color::BG_RED,
27
        'bg:cyan' => Color::BG_CYAN,
28
        'bg:magenta' => Color::BG_MAGENTA,
29
        'bg:white' => Color::BG_WHITE,
30
        'white' => Color::LIGHT_WHITE,
31
        'green' => Color::GREEN,
32
        'gray' => Color::GRAY,
33
        'black' => Color::BLACK,
34
        'red' => Color::RED,
35
        'yellow' => Color::YELLOW,
36
        'reset' => Color::RESET,
37
    ];
38
39
    private array $lines = [];
40
41
    private bool $colorsSupport;
42
43
    /**
44
     * @param bool|resource $stream
45
     */
46 7
    public function __construct(mixed $stream = null)
47
    {
48 7
        $stream ??= \defined('\STDOUT') ? \STDOUT : \fopen('php://stdout', 'wb');
49
50 7
        $this->colorsSupport = $this->isColorsSupported($stream);
51
    }
52
53
    /**
54
     * Disable or enable colorization support.
55
     */
56 6
    public function setColorsSupport(bool $enabled = true): void
57
    {
58 6
        $this->colorsSupport = $enabled;
59
    }
60
61 7
    public function render(
62
        \Throwable $exception,
63
        ?Verbosity $verbosity = null,
64
        string $format = null
65
    ): string {
66 7
        $verbosity ??= $this->defaultVerbosity;
67
68 7
        $exceptions = [$exception];
69 7
        $currentE = $exception;
70
71 7
        while ($exception = $exception->getPrevious()) {
72 1
            $exceptions[] = $exception;
73
        }
74
75 7
        $exceptions = \array_reverse($exceptions);
76
77 7
        $result = [];
78 7
        $rootDir = \getcwd();
79
80 7
        foreach ($exceptions as $exception) {
81 7
            $prefix = $currentE === $exception ? '' : 'Previous: ';
82 7
            $row = $this->renderHeader(
83 7
                \sprintf("%s[%s]\n%s", $prefix, $exception::class, $exception->getMessage()),
84 7
                $exception instanceof \Error ? 'bg:magenta,white' : 'bg:red,white'
85 7
            );
86
87 7
            $file = \str_starts_with($exception->getFile(), $rootDir)
88 7
                ? \substr($exception->getFile(), \strlen($rootDir) + 1)
89
                : $exception->getFile();
90
91 7
            $row .= $this->format(
92 7
                "<yellow>in</reset> <green>%s</reset><yellow>:</reset><white>%s</reset>\n",
93 7
                $file,
94 7
                $exception->getLine()
95 7
            );
96
97 7
            if ($verbosity->value >= Verbosity::DEBUG->value) {
98 2
                $row .= $this->renderTrace(
99 2
                    $exception,
100 2
                    new Highlighter(
101 2
                        $this->colorsSupport ? new ConsoleStyle() : new PlainStyle()
102 2
                    )
103 2
                );
104 5
            } elseif ($verbosity->value >= Verbosity::VERBOSE->value) {
105 1
                $row .= $this->renderTrace($exception);
106
            }
107
108 7
            $result[] = $row;
109
        }
110
111 7
        $this->lines = [];
112
113 7
        return \implode("\n", \array_reverse($result));
114
    }
115
116
    /**
117
     * Render title using outlining border.
118
     *
119
     * @param string $title Title.
120
     * @param string $style Formatting.
121
     */
122 7
    private function renderHeader(string $title, string $style, int $padding = 0): string
123
    {
124 7
        $result = '';
125
126 7
        $lines = \explode("\n", \str_replace("\r", '', $title));
127
128 7
        $length = 0;
129 7
        \array_walk($lines, static function ($v) use (&$length): void {
130 7
            $length = max($length, \mb_strlen($v));
131 7
        });
132
133 7
        $length += $padding;
134
135 7
        foreach ($lines as $line) {
136 7
            $result .= $this->format(
137 7
                "<{$style}>%s%s%s</reset>\n",
138 7
                \str_repeat('', $padding + 1),
139 7
                $line,
140 7
                \str_repeat('', $length - \mb_strlen($line) + 1)
141 7
            );
142
        }
143
144 7
        return $result;
145
    }
146
147
    /**
148
     * Render exception call stack.
149
     */
150 3
    private function renderTrace(\Throwable $e, Highlighter $h = null): string
151
    {
152 3
        $stacktrace = $this->getStacktrace($e);
153 3
        if (empty($stacktrace)) {
154
            return '';
155
        }
156
157 3
        $result = "\n";
158 3
        $rootDir = \getcwd();
159
160 3
        $pad = \strlen((string)\count($stacktrace));
161
162 3
        foreach ($stacktrace as $i => $trace) {
163 3
            $file = null;
164 3
            $classColor = 'while';
165
166 3
            if (isset($trace['file'])) {
167 3
                $file = \str_starts_with($trace['file'], $rootDir)
168 3
                    ? \substr($trace['file'], \strlen($rootDir) + 1)
169
                    : $trace['file'];
170
171 3
                $classColor = \str_starts_with($file, 'vendor/') ? 'gray' : 'white';
172
            }
173
174 3
            if (isset($trace['type'], $trace['class'])) {
175 3
                $line = $this->format(
176 3
                    "<$classColor>%s.</reset> <white>%s%s%s()</reset>",
177 3
                    \str_pad((string)((int)$i + 1), $pad, ' ', \STR_PAD_LEFT),
178 3
                    $trace['class'],
179 3
                    $trace['type'],
180 3
                    $trace['function']
181 3
                );
182
            } else {
183 3
                $line = $this->format(
184 3
                    ' <white>%s()</reset>',
185 3
                    $trace['function']
186 3
                );
187
            }
188 3
            if ($file !== null) {
189 3
                $line .= $this->format(
190 3
                    ' <yellow>at</reset> <green>%s</reset><yellow>:</reset><white>%s</reset>',
191 3
                    $file,
192 3
                    $trace['line']
193 3
                );
194
            }
195
196 3
            if (\in_array($line, $this->lines, true)) {
197 1
                continue;
198
            }
199
200 3
            $this->lines[] = $line;
201
202 3
            $result .= $line . "\n";
203
204 3
            if ($h !== null && !empty($trace['file'])) {
205 2
                $result .= $h->highlightLines(
206 2
                    \file_get_contents($trace['file']),
207 2
                    $trace['line'],
208 2
                    static::SHOW_LINES
209 2
                ) . "\n";
210
            }
211
        }
212
213 3
        return $result;
214
    }
215
216
    /**
217
     * Format string and apply color formatting (if enabled).
218
     */
219 7
    private function format(string $format, mixed ...$args): string
220
    {
221 7
        if (!$this->colorsSupport) {
222 1
            $format = \preg_replace('/<[^>]+>/', '', $format);
223
        } else {
224 6
            $format = \preg_replace_callback('/(<([^>]+)>)/', static function ($partial) {
225 6
                $style = '';
226 6
                foreach (\explode(',', \trim($partial[2], '/')) as $color) {
227 6
                    if (isset(self::COLORS[$color])) {
228 6
                        $style .= self::COLORS[$color];
229
                    }
230
                }
231
232 6
                return $style;
233 6
            }, $format);
234
        }
235
236 7
        return \sprintf($format, ...$args);
237
    }
238
239
    /**
240
     * Returns true if the STDOUT supports colorization.
241
     * @codeCoverageIgnore
242
     * @link https://github.com/symfony/Console/blob/master/Output/StreamOutput.php#L94
243
     */
244
    private function isColorsSupported(mixed $stream = STDOUT): bool
245
    {
246
        if ('Hyper' === \getenv('TERM_PROGRAM')) {
247
            return true;
248
        }
249
250
        try {
251
            if (\DIRECTORY_SEPARATOR === '\\') {
252
                return (\function_exists('sapi_windows_vt100_support') && @\sapi_windows_vt100_support($stream))
253
                    || \getenv('ANSICON') !== false
254
                    || \getenv('ConEmuANSI') === 'ON'
255
                    || \getenv('TERM') === 'xterm';
256
            }
257
258
            return @\stream_isatty($stream);
259
        } catch (\Throwable) {
260
            return false;
261
        }
262
    }
263
}
264