| 1 |
<?php |
| 2 |
/* |
| 3 |
* This file is part of the ManageWP Worker plugin. |
| 4 |
* |
| 5 |
* (c) ManageWP LLC <contact@managewp.com> |
| 6 |
* |
| 7 |
* For the full copyright and license information, please view the LICENSE |
| 8 |
* file that was distributed with this source code. |
| 9 |
*/ |
| 10 |
|
| 11 |
class MWP_Debug_ErrorCatcher |
| 12 |
{ |
| 13 |
private $errorMessage; |
| 14 |
|
| 15 |
private $registered; |
| 16 |
|
| 17 |
public function handleError($code, $message, $file = '', $line = 0, $context = array()) |
| 18 |
{ |
| 19 |
if (is_string($this->registered) && !($message = preg_replace('{^'.$this->registered.'\(.*?\): }i', '', $message))) { |
| 20 |
return; |
| 21 |
} |
| 22 |
|
| 23 |
$this->errorMessage = $message; |
| 24 |
} |
| 25 |
|
| 26 |
public function getErrorMessage() |
| 27 |
{ |
| 28 |
return $this->errorMessage; |
| 29 |
} |
| 30 |
|
| 31 |
public function yieldErrorMessage($unRegister = false) |
| 32 |
{ |
| 33 |
$message = $this->errorMessage; |
| 34 |
$this->errorMessage = null; |
| 35 |
|
| 36 |
if ($unRegister) { |
| 37 |
$this->unRegister(); |
| 38 |
} |
| 39 |
|
| 40 |
return $message; |
| 41 |
} |
| 42 |
|
| 43 |
/** |
| 44 |
* Set the $capture parameter to "true" to capture any error message; or to a function name |
| 45 |
* to capture only error messages for that function. It will rely on PHP's standard error |
| 46 |
* reporting which always starts with the name of the function that generated the error. |
| 47 |
* |
| 48 |
* @param bool|string $capture |
| 49 |
*/ |
| 50 |
public function register($capture = true) |
| 51 |
{ |
| 52 |
if ($this->registered) { |
| 53 |
throw new LogicException('The error catcher is already registered.'); |
| 54 |
} |
| 55 |
|
| 56 |
if ($capture !== true && (!is_string($capture) || empty($capture))) { |
| 57 |
throw new InvalidArgumentException('The "capture" must be boolean true or a non-empty string.'); |
| 58 |
} |
| 59 |
|
| 60 |
$this->registered = $capture; |
| 61 |
$this->errorMessage = null; |
| 62 |
set_error_handler(array($this, 'handleError')); |
| 63 |
} |
| 64 |
|
| 65 |
public function unRegister() |
| 66 |
{ |
| 67 |
if (!$this->registered) { |
| 68 |
throw new LogicException('The error catcher is not registered.'); |
| 69 |
} |
| 70 |
|
| 71 |
$this->registered = false; |
| 72 |
restore_error_handler(); |
| 73 |
} |
| 74 |
|
| 75 |
public function __destruct() |
| 76 |
{ |
| 77 |
if ($this->registered) { |
| 78 |
$this->unRegister(); |
| 79 |
} |
| 80 |
} |
| 81 |
} |
| 82 |
|