Passed
Push — master ( 7aea1d...46b0e0 )
by Alexander
02:23
created

ErrorHandler::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 3
c 1
b 0
f 0
dl 0
loc 8
ccs 4
cts 4
cp 1
rs 10
cc 1
nc 1
nop 3
crap 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\ErrorHandler;
6
7
use Psr\EventDispatcher\EventDispatcherInterface;
8
use Psr\Http\Message\ServerRequestInterface;
9
use Psr\Log\LoggerInterface;
10
use Throwable;
11
use Yiisoft\ErrorHandler\Event\ApplicationError;
12
use Yiisoft\ErrorHandler\Exception\ErrorException;
13
use Yiisoft\ErrorHandler\Renderer\PlainTextRenderer;
14
use Yiisoft\Http\Status;
15
16
use function error_get_last;
17
use function error_reporting;
18
use function function_exists;
19
use function ini_set;
20
use function http_response_code;
21
use function register_shutdown_function;
22
use function restore_error_handler;
23
use function restore_exception_handler;
24
use function set_error_handler;
25
use function set_exception_handler;
26
use function str_repeat;
27
28
/**
29
 * ErrorHandler handles out of memory errors, fatals, warnings, notices and exceptions.
30
 */
31
final class ErrorHandler
32
{
33
    /**
34
     * @var int The size of the reserved memory. A portion of memory is pre-allocated so that
35
     * when an out-of-memory issue occurs, the error handler is able to handle the error with
36
     * the help of this reserved memory. If you set this value to be 0, no memory will be reserved.
37
     * Defaults to 256KB.
38
     */
39
    private int $memoryReserveSize = 262_144;
0 ignored issues
show
Bug introduced by
The constant Yiisoft\ErrorHandler\262_144 was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
40
    private string $memoryReserve = '';
41
    private bool $debug = false;
42
    private ?string $workingDirectory = null;
43
44
    private LoggerInterface $logger;
45
    private ThrowableRendererInterface $defaultRenderer;
46
    private ?EventDispatcherInterface $eventDispatcher;
47
48 17
    public function __construct(
49
        LoggerInterface $logger,
50
        ThrowableRendererInterface $defaultRenderer,
51
        EventDispatcherInterface $eventDispatcher = null
52
    ) {
53 17
        $this->logger = $logger;
54 17
        $this->defaultRenderer = $defaultRenderer;
55 17
        $this->eventDispatcher = $eventDispatcher;
56
    }
57
58
    /**
59
     * Handles throwable and returns error data.
60
     *
61
     * @param Throwable $t
62
     * @param ThrowableRendererInterface|null $renderer
63
     * @param ServerRequestInterface|null $request
64
     *
65
     * @return ErrorData
66
     */
67 12
    public function handle(
68
        Throwable $t,
69
        ThrowableRendererInterface $renderer = null,
70
        ServerRequestInterface $request = null
71
    ): ErrorData {
72 12
        if ($renderer === null) {
73 5
            $renderer = $this->defaultRenderer;
74
        }
75
76
        try {
77 12
            $this->logger->error((string) (new PlainTextRenderer())->renderVerbose($t, $request), ['throwable' => $t]);
78 12
            return $this->debug ? $renderer->renderVerbose($t, $request) : $renderer->render($t, $request);
79 4
        } catch (Throwable $t) {
80 4
            return new ErrorData((string) $t);
81
        }
82
    }
83
84
    /**
85
     * Enables and disables debug mode.
86
     *
87
     * Ensure that is is disabled in production environment since debug mode exposes sensitive details.
88
     *
89
     * @param bool $enable Enable/disable debugging mode.
90
     */
91 2
    public function debug(bool $enable = true): void
92
    {
93 2
        $this->debug = $enable;
94
    }
95
96
    /**
97
     * Sets the size of the reserved memory.
98
     *
99
     * @param int $size The size of the reserved memory.
100
     *
101
     * @see $memoryReserveSize
102
     */
103 6
    public function memoryReserveSize(int $size): void
104
    {
105 6
        $this->memoryReserveSize = $size;
106
    }
107
108
    /**
109
     * Register this error handler.
110
     */
111 2
    public function register(): void
112
    {
113
        // Disables the display of error.
114 2
        if (function_exists('ini_set')) {
115 2
            ini_set('display_errors', '0');
116
        }
117
118
        // Handles throwable, echo output and exit.
119 2
        set_exception_handler(function (Throwable $t): void {
120
            $this->renderThrowableAndTerminate($t);
121
        });
122
123
        // Handles PHP execution errors such as warnings and notices.
124 2
        set_error_handler(static function (int $severity, string $message, string $file, int $line): bool {
125 2
            if (!(error_reporting() & $severity)) {
126
                // This error code is not included in error_reporting.
127
                return true;
128
            }
129
130 2
            throw new ErrorException($message, $severity, $severity, $file, $line);
131
        });
132
133 2
        if ($this->memoryReserveSize > 0) {
134
            $this->memoryReserve = str_repeat('x', $this->memoryReserveSize);
135
        }
136
137
        // Handles fatal error.
138 2
        register_shutdown_function(function (): void {
139
            $this->memoryReserve = '';
140
            $e = error_get_last();
141
142
            if ($e !== null && ErrorException::isFatalError($e)) {
143
                $error = new ErrorException($e['message'], $e['type'], $e['type'], $e['file'], $e['line']);
144
                $this->renderThrowableAndTerminate($error);
145
            }
146
        });
147
148 2
        if (!(PHP_SAPI === 'cli' || PHP_SAPI === 'phpdbg')) {
149
            $this->workingDirectory = getcwd();
150
        }
151
    }
152
153
    /**
154
     * Unregisters this error handler by restoring the PHP error and exception handlers.
155
     */
156 1
    public function unregister(): void
157
    {
158 1
        restore_error_handler();
159 1
        restore_exception_handler();
160
    }
161
162
    /**
163
     * Renders the throwable and terminates the script.
164
     *
165
     * @param Throwable $t
166
     */
167
    private function renderThrowableAndTerminate(Throwable $t): void
168
    {
169
        if (!empty($this->workingDirectory)) {
170
            chdir($this->workingDirectory);
171
        }
172
        // disable error capturing to avoid recursive errors while handling exceptions
173
        $this->unregister();
174
        // set preventive HTTP status code to 500 in case error handling somehow fails and headers are sent
175
        http_response_code(Status::INTERNAL_SERVER_ERROR);
176
177
        echo $this->handle($t);
178
        if ($this->eventDispatcher !== null) {
179
            $this->eventDispatcher->dispatch(new ApplicationError($t));
180
        }
181
        register_shutdown_function(static function (): void {
182
            exit(1);
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
183
        });
184
    }
185
}
186