Passed
Push — master ( c1ff08...0c4511 )
by Aleksei
06:40 queued 19s
created

ConsoleRenderer   A

Complexity

Total Complexity 38

Size/Duplication

Total Lines 241
Duplicated Lines 0 %

Test Coverage

Coverage 98.2%

Importance

Changes 0
Metric Value
wmc 38
eloc 126
c 0
b 0
f 0
dl 0
loc 241
ccs 109
cts 111
cp 0.982
rs 9.36

7 Methods

Rating   Name   Duplication   Size   Complexity  
A setColorsSupport() 0 3 1
A renderHeader() 0 23 2
B render() 0 53 9
A __construct() 0 5 2
A format() 0 18 4
B isColorsSupported() 0 17 8
C renderTrace() 0 63 12
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|null $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 = isset($trace['file']) ? (string) $trace['file'] : null;
164 3
            $classColor = 'while';
165
166 3
            if ($file !== null) {
167 3
                \str_starts_with($file, $rootDir) and $file = \substr($file, \strlen($rootDir) + 1);
168 3
                $classColor = \str_starts_with($file, 'vendor/') ? 'gray' : 'white';
169
            }
170
171 3
            if (isset($trace['type'], $trace['class'])) {
172 3
                $line = $this->format(
173 3
                    "<$classColor>%s.</reset> <white>%s%s%s()</reset>",
174 3
                    \str_pad((string)((int)$i + 1), $pad, ' ', \STR_PAD_LEFT),
175 3
                    $trace['class'],
176 3
                    $trace['type'],
177 3
                    $trace['function']
178 3
                );
179
            } else {
180 3
                $line = $this->format(
181 3
                    ' <white>%s()</reset>',
182 3
                    $trace['function']
183 3
                );
184
            }
185 3
            if ($file !== null) {
186 3
                $line .= $this->format(
187 3
                    ' <yellow>at</reset> <green>%s</reset><yellow>:</reset><white>%s</reset>',
188 3
                    $file,
189 3
                    $trace['line']
190 3
                );
191
            }
192
193 3
            if (\in_array($line, $this->lines, true)) {
194 1
                continue;
195
            }
196
197 3
            $this->lines[] = $line;
198
199 3
            $result .= $line . "\n";
200
201 3
            if ($h !== null && !empty($trace['file'])) {
202 2
                $str = @\file_get_contents($trace['file']);
203 2
                $result .= $h->highlightLines(
204 2
                    $str,
0 ignored issues
show
Bug introduced by
It seems like $str can also be of type false; however, parameter $source of Spiral\Exceptions\Render...ghter::highlightLines() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

204
                    /** @scrutinizer ignore-type */ $str,
Loading history...
205 2
                    $trace['line'],
206 2
                    static::SHOW_LINES
207 2
                ) . "\n";
208 2
                unset($str);
209
            }
210
        }
211
212 3
        return $result;
213
    }
214
215
    /**
216
     * Format string and apply color formatting (if enabled).
217
     */
218 7
    private function format(string $format, mixed ...$args): string
219
    {
220 7
        if (!$this->colorsSupport) {
221 1
            $format = \preg_replace('/<[^>]+>/', '', $format);
222
        } else {
223 6
            $format = \preg_replace_callback('/(<([^>]+)>)/', static function ($partial) {
224 6
                $style = '';
225 6
                foreach (\explode(',', \trim($partial[2], '/')) as $color) {
226 6
                    if (isset(self::COLORS[$color])) {
227 6
                        $style .= self::COLORS[$color];
228
                    }
229
                }
230
231 6
                return $style;
232 6
            }, $format);
233
        }
234
235 7
        return \sprintf($format, ...$args);
236
    }
237
238
    /**
239
     * Returns true if the STDOUT supports colorization.
240
     * @codeCoverageIgnore
241
     * @link https://github.com/symfony/Console/blob/master/Output/StreamOutput.php#L94
242
     */
243
    private function isColorsSupported(mixed $stream = STDOUT): bool
244
    {
245
        if ('Hyper' === \getenv('TERM_PROGRAM')) {
246
            return true;
247
        }
248
249
        try {
250
            if (\DIRECTORY_SEPARATOR === '\\') {
251
                return (\function_exists('sapi_windows_vt100_support') && @\sapi_windows_vt100_support($stream))
252
                    || \getenv('ANSICON') !== false
253
                    || \getenv('ConEmuANSI') === 'ON'
254
                    || \getenv('TERM') === 'xterm';
255
            }
256
257
            return @\stream_isatty($stream);
258
        } catch (\Throwable) {
259
            return false;
260
        }
261
    }
262
}
263