Failed Conditions
Push — master ( 63ec91...ac34b9 )
by Arnold
03:24
created

HandleUncaughtException::logUncaughtException()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 2

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 8
ccs 6
cts 6
cp 1
rs 9.4285
cc 2
eloc 4
nc 2
nop 1
crap 2
1
<?php
2
3
namespace Jasny\ErrorHandler;
4
5
/**
6
 * Trait for handling uncaught exceptions using PHP's exception handler
7
 */
8
trait HandleUncaughtException
9
{
10
    /**
11
     * @var callable|false
12
     */
13
    protected $chainedExceptionHandler;
14
15
16
    /**
17
     * Log the following exception classes (and subclasses)
18
     * @var array
19
     */
20
    protected $logExceptionClasses = [];
21
22
23
    /**
24
     * Wrapper method for `set_error_handler`
25
     * 
26
     * @param callable $callback
27
     * @param int      $error_types
28
     * @return callable|null
29
     */
30
    abstract protected function setErrorHandler($callback, $error_types = E_ALL);
31
32
    /**
33
     * Wrapper method for `set_exception_handler`
34
     * 
35
     * @param callable $callback
36
     * @return callable|null
37
     */
38
    abstract protected function setExceptionHandler($callback);
39
40
    /**
41
     * Log an error or exception
42
     * 
43
     * @param \Exception|\Error $error
44
     */
45
    abstract public function log($error);
0 ignored issues
show
Documentation introduced by
For interfaces and abstract methods it is generally a good practice to add a @return annotation even if it is just @return void or @return null, so that implementors know what to do in the overridden method.

For interface and abstract methods, it is impossible to infer the return type from the immediate code. In these cases, it is generally advisible to explicitly annotate these methods with a @return doc comment to communicate to implementors of these methods what they are expected to return.

Loading history...
46
47
48
    /**
49
     * Get the error handler that has been replaced.
50
     * 
51
     * @return callable|false|null
52
     */
53 2
    public function getChainedExceptionHandler()
54
    {
55 2
        return $this->chainedExceptionHandler;
56
    }
57
    
58
    /**
59
     * Get a list of Exception and other Throwable classes that will be logged
60
     * @return array
61
     */
62 4
    public function getLoggedExceptionClasses()
63
    {
64 4
        return $this->logExceptionClasses;
65
    }
66
    
67
    
68
    /**
69
     * Log these types of errors or exceptions
70
     * 
71
     * @param string $class  Exception class name
72
     */
73 18
    protected function logUncaughtException($class)
74
    {
75 18
        if (!in_array($class, $this->logExceptionClasses)) {
76 18
            $this->logExceptionClasses[] = $class;
77 9
        }
78
79 18
        $this->initExceptionHandler();
80 18
    }
81
82
    
83
    /**
84
     * Use the global error handler
85
     */
86 18
    protected function initExceptionHandler()
87
    {
88 18
        if (!isset($this->chainedExceptionHandler)) {
89 18
            $this->chainedExceptionHandler = $this->setExceptionHandler([$this, 'handleException']) ?: false;
90 9
        }
91 18
    }
92
    
93
    /**
94
     * Uncaught exception handler
95
     * @ignore
96
     * 
97
     * @param \Exception|\Error $exception
98
     */
99 18
    public function handleException($exception)
100
    {
101 18
        $this->setExceptionHandler(null);
0 ignored issues
show
Documentation introduced by
null is of type null, but the function expects a callable.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
102 18
        $this->setErrorHandler(null);
0 ignored issues
show
Documentation introduced by
null is of type null, but the function expects a callable.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
103
        
104 18
        $isInstanceOf = array_map(function($class) use ($exception) {
0 ignored issues
show
Coding Style introduced by
Expected 1 space after FUNCTION keyword; 0 found
Loading history...
105 12
            return is_a($exception, $class);
106 18
        }, $this->logExceptionClasses);
107
        
108 18
        if ($exception instanceof \Error || $exception instanceof \ErrorException) {
109 4
            $type = $exception instanceof \Error ? $exception->getCode() : $exception->getSeverity();
110 4
            $shouldLog = $this->logErrorTypes & $type;
0 ignored issues
show
Bug introduced by
The property logErrorTypes does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
111 2
        } else {
112 14
            $shouldLog = array_sum($isInstanceOf) > 0;
113
        }
114
        
115 18
        if ($shouldLog) {
116 12
            $this->log($exception);
117 6
        }
118
        
119 18
        $this->callOnFatalError($exception);
0 ignored issues
show
Bug introduced by
It seems like callOnFatalError() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
120
        
121 18
        if ($this->chainedExceptionHandler) {
122 6
            call_user_func($this->chainedExceptionHandler, $exception);
123 3
        }
124
        
125 18
        throw $exception; // This is now handled by the default exception and error handler
126
    }
127
}
128
129