Passed
Pull Request — master (#96)
by Alexander
11:07 queued 08:33
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 3
    public function __construct(
39
        string $message = '',
40
        int $code = 0,
41
        int $severity = 1,
42
        string $filename = __FILE__,
43
        int $line = __LINE__,
44
        private array $backtrace = [],
45
        Exception $previous = null
46
    ) {
47 3
        parent::__construct($message, $code, $severity, $filename, $line, $previous);
48 3
        $this->addXDebugTraceToFatalIfAvailable();
49
    }
50
51
    /**
52
     * Returns if error is one of fatal type.
53
     *
54
     * @param array $error error got from error_get_last()
55
     *
56
     * @return bool If error is one of fatal type.
57
     */
58 1
    public static function isFatalError(array $error): bool
59
    {
60 1
        return isset($error['type']) && in_array(
61 1
            $error['type'],
62 1
            [E_ERROR, E_PARSE, E_CORE_ERROR, E_CORE_WARNING, E_COMPILE_ERROR, E_COMPILE_WARNING],
63 1
            true,
64 1
        );
65
    }
66
67
    /**
68
     * @return string The user-friendly name of this exception.
69
     */
70 1
    public function getName(): string
71
    {
72 1
        return self::ERROR_NAMES[$this->getCode()] ?? 'Error';
73
    }
74
75 1
    public function getSolution(): ?string
76
    {
77 1
        return null;
78
    }
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