Lines
89.47%
17 / 19
Functions and Methods
50.00%
2 / 4
Classes and Traits
0.00%
0 / 1
| Name | Lines | Functions and Methods | CRAP | Classes and Traits | ||||||
|---|---|---|---|---|---|---|---|---|---|---|
| PhpErrorHandler | 89.47% | 17 / 19 | 50.00% | 2 / 4 | 13.20 | 0.00% | 0 / 1 | |||
| register | 66.66% | 2 / 3 | 0.00% | 0 / 1 | 2.15 | |||||
| isTestEnvironment | 100.00% | 2 / 2 | 100.00% | 1 / 1 | 2 | |||||
| handle | 90.00% | 9 / 10 | 0.00% | 0 / 1 | 4.02 | |||||
| severityToLogLevel | 100.00% | 4 / 4 | 100.00% | 1 / 1 | 5 | |||||
| 1 | <?php | |
| 2 | ||
| 3 | declare(strict_types=1); | |
| 4 | ||
| 5 | namespace BO\Slim\Helper; | |
| 6 | ||
| 7 | use Monolog\Logger; | |
| 8 | use Psr\Log\LoggerInterface; | |
| 9 | ||
| 10 | final class PhpErrorHandler | |
| 11 | { | |
| 12 | public static function register(): void | |
| 13 | { | |
| 14 | if (self::isTestEnvironment()) { | |
| 15 | return; | |
| 16 | } | |
| 17 | ||
| 18 | set_error_handler([self::class, 'handle']); | |
| 19 | } | |
| 20 | ||
| 21 | public static function isTestEnvironment(): bool | |
| 22 | { | |
| 23 | return defined('PHPUNIT_COMPOSER_INSTALL') | |
| 24 | || getenv('PHPUNIT_COMPOSER_INSTALL') !== false; | |
| 25 | } | |
| 26 | ||
| 27 | public static function handle(int $severity, string $message, string $file, int $line): bool | |
| 28 | { | |
| 29 | if (!(error_reporting() & $severity)) { | |
| 30 | return false; | |
| 31 | } | |
| 32 | ||
| 33 | if (!isset(\App::$log) || !\App::$log instanceof LoggerInterface) { | |
| 34 | return false; | |
| 35 | } | |
| 36 | ||
| 37 | \App::$log->log(self::severityToLogLevel($severity), $message, [ | |
| 38 | 'php_errno' => $severity, | |
| 39 | 'file' => $file, | |
| 40 | 'line' => $line, | |
| 41 | ]); | |
| 42 | ||
| 43 | return true; | |
| 44 | } | |
| 45 | ||
| 46 | public static function severityToLogLevel(int $severity): int | |
| 47 | { | |
| 48 | return match ($severity) { | |
| 49 | E_ERROR, E_CORE_ERROR, E_COMPILE_ERROR, E_PARSE, E_USER_ERROR => Logger::ERROR, | |
| 50 | E_WARNING, E_CORE_WARNING, E_COMPILE_WARNING, E_USER_WARNING => Logger::WARNING, | |
| 51 | E_NOTICE, E_USER_NOTICE, E_DEPRECATED, E_USER_DEPRECATED => Logger::NOTICE, | |
| 52 | default => Logger::WARNING, | |
| 53 | }; | |
| 54 | } | |
| 55 | } |