ErrorToExceptionConverter::restoreErrorHandler()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 7
ccs 6
cts 6
cp 1
rs 10
c 0
b 0
f 0
cc 2
nc 2
nop 0
crap 2
1
<?php
2
/**
3
 * This file is part of the NeedleProject\Common package.
4
 *
5
 * For the full copyright and license information, please view the LICENSE
6
 * file that was distributed with this source code.
7
 */
8
namespace NeedleProject\Common\Util;
9
10
/**
11
 * Class ErrorToExceptionConverter
12
 *
13
 * @package NeedleProject\Common\Util
14
 * @author Adrian Tilita <[email protected]>
15
 * @copyright 2017 Adrian Tilita
16
 * @license https://opensource.org/licenses/MIT MIT Licence
17
 */
18
class ErrorToExceptionConverter
19
{
20
    /**
21
     * @const string  Exception class name to be thrown
22
     */
23
    const EXCEPTION_THROW_CLASS = \Exception::class;
24
25
    /**
26
     * States that the current object is the current error handler
27
     * @var bool
28
     */
29
    protected $isHandledLocal = false;
30
31
    /**
32
     * Converts errors to exceptions
33
     *
34
     * @param int|null $level The error level to be handled.
35
     *                        See http://php.net/manual/en/errorfunc.constants.php
36
     * @param string|null $exceptionClass
37
     */
38 3
    public function convertErrorsToExceptions($level = null, $exceptionClass = null)
39
    {
40 3
        $this->isHandledLocal = true;
41 3
        if (is_null($level)) {
42 1
            $level = E_ALL;
43 1
        }
44 3
        if (is_null($exceptionClass)) {
45 1
            $exceptionClass = static::EXCEPTION_THROW_CLASS;
46 1
        }
47 3
        set_error_handler(function ($errorNumber, $errorMessage, $errorFile, $errorLine) use ($exceptionClass) {
48 3
            throw new $exceptionClass(
49 3
                sprintf("%s in %s on line %s!", $errorMessage, $errorFile, $errorLine),
50
                $errorNumber
51 3
            );
52 3
        }, $level);
53 3
    }
54
55
    /**
56
     * Restore previous defined error handlers
57
     */
58 1
    public function restoreErrorHandler()
59
    {
60 1
        if (true === $this->isHandledLocal) {
61 1
            \restore_error_handler();
62 1
            $this->isHandledLocal = false;
63 1
        }
64 1
    }
65
}
66