Passed
Push — master ( 3eb4db...99d5ff )
by Kirill
03:12
created

ConsoleHandler::renderTrace()   B

Complexity

Conditions 8
Paths 10

Size

Total Lines 50
Code Lines 33

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 33
c 1
b 0
f 0
dl 0
loc 50
rs 8.1475
cc 8
nc 10
nop 2
1
<?php
2
3
/**
4
 * Spiral Framework.
5
 *
6
 * @license   MIT
7
 * @author    Anton Titov (Wolfy-J)
8
 */
9
10
declare(strict_types=1);
11
12
namespace Spiral\Exceptions;
13
14
use Codedungeon\PHPCliColors\Color;
15
use Spiral\Debug\System;
16
use Spiral\Exceptions\Style\ConsoleStyle;
17
use Spiral\Exceptions\Style\PlainStyle;
18
19
/**
20
 * Verbosity levels:
21
 *
22
 * 1) BASIC   - only message header and line number
23
 * 2) VERBOSE - stack information
24
 * 3) DEBUG   - stack and source information.
25
 */
26
class ConsoleHandler extends AbstractHandler
27
{
28
    // Lines to show around targeted line.
29
    public const SHOW_LINES = 2;
30
31
    protected const COLORS = [
32
        'bg:red'     => Color::BG_RED,
33
        'bg:cyan'    => Color::BG_CYAN,
34
        'bg:magenta' => Color::BG_MAGENTA,
35
        'bg:white'   => Color::BG_WHITE,
36
        'white'      => Color::LIGHT_WHITE,
37
        'green'      => Color::GREEN,
38
        'black'      => Color::BLACK,
39
        'red'        => Color::RED,
40
        'yellow'     => Color::YELLOW,
41
        'reset'      => Color::RESET,
42
    ];
43
44
    /** @var StyleInterface */
45
    private $colorsSupport;
46
47
    /**
48
     * @param bool|resource $stream
49
     */
50
    public function __construct($stream = STDOUT)
51
    {
52
        $this->colorsSupport = System::isColorsSupported($stream);
0 ignored issues
show
Documentation Bug introduced by
It seems like Spiral\Debug\System::isColorsSupported($stream) of type boolean is incompatible with the declared type Spiral\Exceptions\StyleInterface of property $colorsSupport.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
53
    }
54
55
    /**
56
     * Disable or enable colorization support.
57
     *
58
     * @param bool $enabled
59
     */
60
    public function setColorsSupport(bool $enabled = true): void
61
    {
62
        $this->colorsSupport = $enabled;
0 ignored issues
show
Documentation Bug introduced by
It seems like $enabled of type boolean is incompatible with the declared type Spiral\Exceptions\StyleInterface of property $colorsSupport.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
63
    }
64
65
    /**
66
     * @inheritdoc
67
     */
68
    public function renderException(\Throwable $e, int $verbosity = self::VERBOSITY_BASIC): string
69
    {
70
        $result = '';
71
72
        if ($e instanceof \Error) {
73
            $result .= $this->renderHeader('[' . get_class($e) . "]\n" . $e->getMessage(), 'bg:magenta,white');
74
        } else {
75
            $result .= $this->renderHeader('[' . get_class($e) . "]\n" . $e->getMessage(), 'bg:red,white');
76
        }
77
78
        $result .= $this->format(
79
            "<yellow>in</reset> <green>%s</reset><yellow>:</reset><white>%s</reset>\n",
80
            $e->getFile(),
81
            $e->getLine()
82
        );
83
84
        if ($verbosity >= self::VERBOSITY_DEBUG) {
85
            $result .= $this->renderTrace($e, new Highlighter(
86
                $this->colorsSupport ? new ConsoleStyle() : new PlainStyle()
87
            ));
88
        } elseif ($verbosity >= self::VERBOSITY_VERBOSE) {
89
            $result .= $this->renderTrace($e);
90
        }
91
92
        return $result;
93
    }
94
95
    /**
96
     * Render title using outlining border.
97
     *
98
     * @param string $title Title.
99
     * @param string $style Formatting.
100
     * @param int    $padding
101
     * @return string
102
     */
103
    private function renderHeader(string $title, string $style, int $padding = 0): string
104
    {
105
        $result = '';
106
107
        $lines = explode("\n", str_replace("\r", '', $title));
108
109
        $length = 0;
110
        array_walk($lines, function ($v) use (&$length): void {
111
            $length = max($length, mb_strlen($v));
112
        });
113
114
        $length += $padding;
115
116
        foreach ($lines as $line) {
117
            $result .= $this->format(
118
                "<{$style}>%s%s%s</reset>\n",
119
                str_repeat(' ', $padding + 1),
120
                $line,
121
                str_repeat(' ', $length - mb_strlen($line) + 1)
122
            );
123
        }
124
125
        return $result;
126
    }
127
128
    /**
129
     * Render exception call stack.
130
     *
131
     * @param \Throwable       $e
132
     * @param Highlighter|null $h
133
     * @return string
134
     */
135
    private function renderTrace(\Throwable $e, Highlighter $h = null): string
136
    {
137
        $stacktrace = $this->getStacktrace($e);
138
        if (empty($stacktrace)) {
139
            return '';
140
        }
141
142
        $result = $this->format("\n<red>Exception Trace:</reset>\n");
143
144
        foreach ($stacktrace as $trace) {
145
            if (isset($trace['type']) && isset($trace['class'])) {
146
                $line = $this->format(
147
                    ' <white>%s%s%s()</reset>',
148
                    $trace['class'],
149
                    $trace['type'],
150
                    $trace['function']
151
                );
152
            } else {
153
                $line = $this->format(
154
                    ' <white>%s()</reset>',
155
                    $trace['function']
156
                );
157
            }
158
159
            if (isset($trace['file'])) {
160
                $line .= $this->format(
161
                    ' <yellow>at</reset> <green>%s</reset><yellow>:</reset><white>%s</reset>',
162
                    $trace['file'],
163
                    $trace['line']
164
                );
165
            } else {
166
                $line .= $this->format(
167
                    ' <yellow>at</reset> <green>%s</reset><yellow>:</reset><white>%s</reset>',
168
                    'n/a',
169
                    'n/a'
170
                );
171
            }
172
173
            $result .= $line . "\n";
174
175
            if (!empty($h) && !empty($trace['file'])) {
176
                $result .= $h->highlightLines(
177
                    file_get_contents($trace['file']),
178
                    $trace['line'],
179
                    static::SHOW_LINES
180
                ) . "\n";
181
            }
182
        }
183
184
        return $result;
185
    }
186
187
    /**
188
     * Format string and apply color formatting (if enabled).
189
     *
190
     * @param string $format
191
     * @param mixed  ...$args
192
     * @return string
193
     */
194
    private function format(string $format, ...$args): string
195
    {
196
        if (!$this->colorsSupport) {
197
            $format = preg_replace('/<[^>]+>/', '', $format);
198
        } else {
199
            $format = preg_replace_callback('/(<([^>]+)>)/', function ($partial) {
200
                $style = '';
201
                foreach (explode(',', trim($partial[2], '/')) as $color) {
202
                    if (isset(self::COLORS[$color])) {
203
                        $style .= self::COLORS[$color];
204
                    }
205
                }
206
207
                return $style;
208
            }, $format);
209
        }
210
211
        return sprintf($format, ...$args);
212
    }
213
}
214