Passed
Pull Request — master (#96)
by Sergei
03:01
created

ErrorException::getBacktrace()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
eloc 1
c 0
b 0
f 0
dl 0
loc 3
ccs 0
cts 2
cp 0
rs 10
cc 1
nc 1
nop 0
crap 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\ErrorHandler\Exception;
6
7
use Exception;
8
use ReflectionProperty;
9
use Yiisoft\FriendlyException\FriendlyExceptionInterface;
10
11
use function array_slice;
12
use function in_array;
13
use function function_exists;
14
15
/**
16
 * `ErrorException` represents a PHP error.
17
 *
18
 * @psalm-type DebugBacktraceType = list<array{args?:list<mixed>,class?:class-string,file?:string,function:string,line?:int,object?:object,type?:string}>
19
 */
20
class ErrorException extends \ErrorException implements FriendlyExceptionInterface
21
{
22
    private const ERROR_NAMES = [
23
        E_ERROR => 'PHP Fatal Error',
24
        E_WARNING => 'PHP Warning',
25
        E_PARSE => 'PHP Parse Error',
26
        E_NOTICE => 'PHP Notice',
27
        E_CORE_ERROR => 'PHP Core Error',
28
        E_CORE_WARNING => 'PHP Core Warning',
29
        E_COMPILE_ERROR => 'PHP Compile Error',
30
        E_COMPILE_WARNING => 'PHP Compile Warning',
31
        E_USER_ERROR => 'PHP User Error',
32
        E_USER_WARNING => 'PHP User Warning',
33
        E_USER_NOTICE => 'PHP User Notice',
34
        E_STRICT => 'PHP Strict Warning',
35
        E_RECOVERABLE_ERROR => 'PHP Recoverable Error',
36
        E_DEPRECATED => 'PHP Deprecated Warning',
37
        E_USER_DEPRECATED => 'PHP User Deprecated Warning',
38
    ];
39
40
    /**
41
     * @psalm-param DebugBacktraceType $backtrace
42
     */
43 3
    public function __construct(string $message = '', int $code = 0, int $severity = 1, string $filename = __FILE__, int $line = __LINE__, Exception $previous = null, private array $backtrace = []) {
44 3
        parent::__construct($message, $code, $severity, $filename, $line, $previous);
45 3
        $this->addXDebugTraceToFatalIfAvailable();
46
    }
47
48
    /**
49
     * Returns if error is one of fatal type.
50
     *
51
     * @param array $error error got from error_get_last()
52
     *
53
     * @return bool If error is one of fatal type.
54
     */
55 1
    public static function isFatalError(array $error): bool
56
    {
57 1
        return isset($error['type']) && in_array(
58 1
            $error['type'],
59 1
            [E_ERROR, E_PARSE, E_CORE_ERROR, E_CORE_WARNING, E_COMPILE_ERROR, E_COMPILE_WARNING],
60 1
            true,
61 1
        );
62
    }
63
64
    /**
65
     * @return string The user-friendly name of this exception.
66
     */
67 1
    public function getName(): string
68
    {
69 1
        return self::ERROR_NAMES[$this->getCode()] ?? 'Error';
70
    }
71
72 1
    public function getSolution(): ?string
73
    {
74 1
        return null;
75
    }
76
77
    /**
78
     * @psalm-return DebugBacktraceType
79
     */
80
    public function getBacktrace(): array
81
    {
82
        return $this->backtrace;
83
    }
84
85
    /**
86
     * Fatal errors normally do not provide any trace making it harder to debug. In case XDebug is installed, we
87
     * can get a trace using `xdebug_get_function_stack()`.
88
     */
89 3
    private function addXDebugTraceToFatalIfAvailable(): void
90
    {
91 3
        if ($this->isXdebugStackAvailable()) {
92
            /**
93
             * XDebug trace can't be modified and used directly with PHP 7
94
             *
95
             * @see https://github.com/yiisoft/yii2/pull/11723
96
             *
97
             * @psalm-var array<int,array>
98
             */
99
            $xDebugTrace = array_slice(array_reverse(xdebug_get_function_stack()), 1, -1);
100
            $trace = [];
101
102
            foreach ($xDebugTrace as $frame) {
103
                if (!isset($frame['function'])) {
104
                    $frame['function'] = 'unknown';
105
                }
106
107
                // XDebug < 2.1.1: https://bugs.xdebug.org/view.php?id=695
108
                if (!isset($frame['type']) || $frame['type'] === 'static') {
109
                    $frame['type'] = '::';
110
                } elseif ($frame['type'] === 'dynamic') {
111
                    $frame['type'] = '->';
112
                }
113
114
                // XDebug has a different key name
115
                if (isset($frame['params']) && !isset($frame['args'])) {
116
                    /** @var mixed */
117
                    $frame['args'] = $frame['params'];
118
                }
119
                $trace[] = $frame;
120
            }
121
122
            $ref = new ReflectionProperty(Exception::class, 'trace');
123
            $ref->setAccessible(true);
124
            $ref->setValue($this, $trace);
125
        }
126
    }
127
128
    /**
129
     * Ensures that Xdebug stack trace is available based on Xdebug version.
130
     * Idea taken from developer bishopb at https://github.com/rollbar/rollbar-php
131
     */
132 3
    private function isXdebugStackAvailable(): bool
133
    {
134 3
        if (!function_exists('\xdebug_get_function_stack')) {
135
            return false;
136
        }
137
138
        // check for Xdebug being installed to ensure origin of xdebug_get_function_stack()
139 3
        $version = phpversion('xdebug');
140
141 3
        if ($version === false) {
142
            return false;
143
        }
144
145
        // Xdebug 2 and prior
146 3
        if (version_compare($version, '3.0.0', '<')) {
147
            return true;
148
        }
149
150
        // Xdebug 3 and later, proper mode is required
151 3
        return str_contains(ini_get('xdebug.mode'), 'develop');
152
    }
153
}
154