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