Passed
Push — develop ( 9ae090...ce9409 )
by Schlaefer
42s
created

ErrorLog::__construct()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
dl 0
loc 6
ccs 0
cts 6
cp 0
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 3
nc 2
nop 1
crap 6
1
<?php
2
/**
3
 * @link http://philecms.github.io/
4
 * @license http://opensource.org/licenses/MIT
5
 * @package Phile\Plugin\Phile\ErrorHandler
6
 */
7
8
namespace Phile\Plugin\Phile\ErrorHandler;
9
10
use Phile\ServiceLocator\ErrorHandlerInterface;
11
12
/**
13
 * Error handler logging to files
14
 */
15
class ErrorLog implements ErrorHandlerInterface
16
{
17
    /**
18
     * Constructor
19
     *
20
     * @param string|null $logfile path to error.log-file; null: PHP default error log
21
     */
22
    public function __construct(?string $logfile = null)
23
    {
24
        if ($logfile) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $logfile of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
25
            ini_set('error_log', $logfile);
26
        }
27
    }
28
29
    public function handleError(int $errno, string $errstr, ?string $errfile, ?int $errline)
30
    {
31
        $this->log($errno, $errstr, $errfile, $errline);
32
    }
33
34
    public function handleException(\Throwable $exception)
35
    {
36
        $code = (int)$exception->getCode();
37
        $message = $exception->getMessage();
38
        $file = $exception->getFile();
39
        $line = $exception->getLine();
40
        $this->log($code, $message, $file, $line);
41
        header($_SERVER['SERVER_PROTOCOL'] . ' 500 Internal Server Error', true, 500);
42
        exit;
43
    }
44
45
    public function handleShutdown()
46
    {
47
        $error = error_get_last();
48
        if ($error === null) {
49
            return;
50
        }
51
        $this->log($error['type'], $error['message'], $error['file'], $error['line']);
52
    }
53
54
    protected function log(int $code, string $message, ?string $file, ?string $line): void
55
    {
56
        error_log("[{$code}] {$message} in {$file} on line {$line}");
57
    }
58
}
59