Lines 100.00% 26 / 26
Methods 100.00% 2 / 2
Classes 100.00% 1 / 1
Covered by tests of size
Name Lines Methods CRAP
 errorHandler 100.00% 8 / 8 100.00% 1 / 1 6
 exceptionHandler 100.00% 18 / 18 100.00% 1 / 1 3
31class Error
32{
33    /**
34     * Error handler to convert all errors to PHP exceptions by
35     * throwing a PHP ErrorException. Deprecation notices are only
36     * logged, so they never crash the application.
37     *
38     * @throws ErrorException
39     */
40    public static function errorHandler(int $level, string $message, string $filename, int $line): void
41    {
42        if (error_reporting() === 0) {
43            return;
44        }
45
46        if ($level === E_DEPRECATED || $level === E_USER_DEPRECATED) {
47            if (ini_get('log_errors')) {
48                error_log(sprintf('phpMyFAQ Deprecation: %s in %s on line %d', $message, $filename, $line));
49            }
50
51            return;
52        }
53
54        $filename = Environment::isDebugMode() ? $filename : basename($filename);
55        throw new ErrorException($message, 0, $level, $filename, $line);
56    }
57
58    /**
59     * Exception handler.
60     */
61    public static function exceptionHandler(\Throwable $exception): void
62    {
63        $code = $exception->getCode();
64        if ($code !== 404) {
65            $code = 500;
66        }
67
68        http_response_code($code);
69
70        echo '<h1>phpMyFAQ Fatal error</h1>';
71        echo "<p>Uncaught exception: '" . $exception::class . "'</p>";
72        echo "<p>Message: '" . Strings::htmlentities($exception->getMessage()) . "'</p>";
73        echo '<p>Stack trace:<pre>' . $exception->getTraceAsString() . '</pre></p>';
74        echo "<p>Thrown in '" . $exception->getFile() . "' on line " . $exception->getLine() . '</p>';
75        if (ini_get('log_errors')) {
76            error_log(sprintf(
77                "phpMyFAQ %s: %s in %s on line %d\nStack trace:\n%s",
78                $exception::class,
79                $exception->getMessage(),
80                $exception->getFile(),
81                $exception->getLine(),
82                $exception->getTraceAsString(),
83            ));
84        }
85    }
86}