Passed
Pull Request — master (#853)
by butschster
12:01 queued 05:19
created

ConsoleRenderer::render()   B

Complexity

Conditions 8
Paths 14

Size

Total Lines 47
Code Lines 26

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 29
CRAP Score 8.0023

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 26
c 1
b 0
f 0
dl 0
loc 47
ccs 29
cts 30
cp 0.9667
rs 8.4444
cc 8
nc 14
nop 3
crap 8.0023
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
        'black'      => Color::BLACK,
33
        'red'        => Color::RED,
34
        'yellow'     => Color::YELLOW,
35
        'reset'      => Color::RESET,
36
    ];
37
38
    private array $lines = [];
39
40
    private bool $colorsSupport;
41
42
    /**
43
     * @param bool|resource $stream
44
     */
45 7
    public function __construct(mixed $stream = null)
46
    {
47 7
        $stream ??= \defined('\STDOUT') ? \STDOUT : \fopen('php://stdout', 'wb');
48
49 7
        $this->colorsSupport = $this->isColorsSupported($stream);
50
    }
51
52
    /**
53
     * Disable or enable colorization support.
54
     */
55 6
    public function setColorsSupport(bool $enabled = true): void
56
    {
57 6
        $this->colorsSupport = $enabled;
58
    }
59
60 7
    public function render(
61
        \Throwable $exception,
62
        ?Verbosity $verbosity = null,
63
        string $format = null
64
    ): string {
65 7
        $verbosity ??= $this->defaultVerbosity;
66
67 7
        $exceptions = [$exception];
68 7
        while ($exception = $exception->getPrevious()) {
69 1
            $exceptions[] = $exception;
70
        }
71
72 7
        $exceptions = \array_reverse($exceptions);
73
74 7
        $result = [];
75 7
        $rootDir = \getcwd();
76
77 7
        foreach ($exceptions as $exception) {
78 7
            $row = $this->renderHeader(
79 7
                \sprintf("[%s]\n%s", $exception::class, $exception->getMessage()),
80 7
                $exception instanceof \Error ? 'bg:magenta,white' : 'bg:red,white'
81 7
            );
82
83 7
            $file = \str_starts_with($exception->getFile(), $rootDir)
84 7
                ? \substr($exception->getFile(), \strlen($rootDir) + 1)
85
                : $exception->getFile();
86
87 7
            $row .= $this->format(
88 7
                "<yellow>in</reset> <green>%s</reset><yellow>:</reset><white>%s</reset>\n",
89 7
                $file,
90 7
                $exception->getLine()
91 7
            );
92
93 7
            if ($verbosity->value >= Verbosity::DEBUG->value) {
94 2
                $row .= $this->renderTrace($exception, new Highlighter(
95 2
                    $this->colorsSupport ? new ConsoleStyle() : new PlainStyle()
96 2
                ));
97 5
            } elseif ($verbosity->value >= Verbosity::VERBOSE->value) {
98 1
                $row .= $this->renderTrace($exception);
99
            }
100
101 7
            $result[] = $row;
102
        }
103
104 7
        $this->lines = [];
105
106 7
        return \implode("\n", \array_reverse($result));
107
    }
108
109
    /**
110
     * Render title using outlining border.
111
     *
112
     * @param string $title Title.
113
     * @param string $style Formatting.
114
     */
115 7
    private function renderHeader(string $title, string $style, int $padding = 0): string
116
    {
117 7
        $result = '';
118
119 7
        $lines = \explode("\n", \str_replace("\r", '', $title));
120
121 7
        $length = 0;
122 7
        \array_walk($lines, static function ($v) use (&$length): void {
123 7
            $length = max($length, \mb_strlen($v));
124 7
        });
125
126 7
        $length += $padding;
127
128 7
        foreach ($lines as $line) {
129 7
            $result .= $this->format(
130 7
                "<{$style}>%s%s%s</reset>\n",
131 7
                \str_repeat('', $padding + 1),
132 7
                $line,
133 7
                \str_repeat('', $length - \mb_strlen($line) + 1)
134 7
            );
135
        }
136
137 7
        return $result;
138
    }
139
140
    /**
141
     * Render exception call stack.
142
     */
143 3
    private function renderTrace(\Throwable $e, Highlighter $h = null): string
144
    {
145 3
        $stacktrace = $this->getStacktrace($e);
146 3
        if (empty($stacktrace)) {
147
            return '';
148
        }
149
150 3
        $result = "\n";
151 3
        $rootDir = \getcwd();
152
153 3
        $pad = \strlen((string)\count($stacktrace));
154
155 3
        foreach ($stacktrace as $i => $trace) {
156 3
            if (isset($trace['type'], $trace['class'])) {
157 3
                $line = $this->format(
158 3
                    ' <white>%s. %s%s%s()</reset>',
159 3
                    \str_pad((string)((int) $i + 1), $pad, ' ', \STR_PAD_LEFT),
160 3
                    $trace['class'],
161 3
                    $trace['type'],
162 3
                    $trace['function']
163 3
                );
164
            } else {
165 3
                $line = $this->format(
166 3
                    ' <white>%s()</reset>',
167 3
                    $trace['function']
168 3
                );
169
            }
170
171 3
            if (isset($trace['file'])) {
172 3
                $file = \str_starts_with($trace['file'], $rootDir)
173 3
                    ? \substr($trace['file'], \strlen($rootDir) + 1)
174
                    : $trace['file'];
175
176 3
                $line .= $this->format(
177 3
                    ' <yellow>at</reset> <green>%s</reset><yellow>:</reset><white>%s</reset>',
178 3
                    $file,
179 3
                    $trace['line']
180 3
                );
181
            }
182
183 3
            if (\in_array($line, $this->lines, true)) {
184 1
                continue;
185
            }
186
187 3
            $this->lines[] = $line;
188
189 3
            $result .= $line . "\n";
190
191 3
            if ($h !== null && !empty($trace['file'])) {
192 2
                $result .= $h->highlightLines(
193 2
                    \file_get_contents($trace['file']),
194 2
                    $trace['line'],
195 2
                    static::SHOW_LINES
196 2
                ) . "\n";
197
            }
198
        }
199
200 3
        return $result;
201
    }
202
203
    /**
204
     * Format string and apply color formatting (if enabled).
205
     */
206 7
    private function format(string $format, mixed ...$args): string
207
    {
208 7
        if (!$this->colorsSupport) {
209 1
            $format = \preg_replace('/<[^>]+>/', '', $format);
210
        } else {
211 6
            $format = \preg_replace_callback('/(<([^>]+)>)/', static function ($partial) {
212 6
                $style = '';
213 6
                foreach (\explode(',', \trim($partial[2], '/')) as $color) {
214 6
                    if (isset(self::COLORS[$color])) {
215 6
                        $style .= self::COLORS[$color];
216
                    }
217
                }
218
219 6
                return $style;
220 6
            }, $format);
221
        }
222
223 7
        return \sprintf($format, ...$args);
224
    }
225
226
    /**
227
     * Returns true if the STDOUT supports colorization.
228
     * @codeCoverageIgnore
229
     * @link https://github.com/symfony/Console/blob/master/Output/StreamOutput.php#L94
230
     */
231
    private function isColorsSupported(mixed $stream = STDOUT): bool
232
    {
233
        if ('Hyper' === \getenv('TERM_PROGRAM')) {
234
            return true;
235
        }
236
237
        try {
238
            if (\DIRECTORY_SEPARATOR === '\\') {
239
                return (\function_exists('sapi_windows_vt100_support') && @\sapi_windows_vt100_support($stream))
240
                    || \getenv('ANSICON') !== false
241
                    || \getenv('ConEmuANSI') === 'ON'
242
                    || \getenv('TERM') === 'xterm';
243
            }
244
245
            return @\stream_isatty($stream);
246
        } catch (\Throwable) {
247
            return false;
248
        }
249
    }
250
}
251