This commit is contained in:
2025-03-17 11:27:07 +08:00
parent 7a7f432006
commit 5febeca83f
6805 changed files with 6 additions and 6 deletions

View File

@@ -0,0 +1,41 @@
# Default
all: deps-install
# DEPENDENCY MANAGEMENT
# Updates dependencies according to lock file
deps-install: composer.phar
./composer.phar --no-interaction install
# Updates dependencies according to json file
deps-update: composer.phar
./composer.phar self-update
./composer.phar --no-interaction update
# TESTS AND REPORTS
# Code standard check
cs-check: composer.lock
./vendor/bin/phpcs --standard=PSR1,PSR12 --encoding=UTF-8 --report=full --colors src tests
# Run tests
test: composer.lock
./vendor/bin/phpunit
# Run tests with clover coverage report
coverage: composer.lock
XDEBUG_MODE=coverage ./vendor/bin/phpunit --coverage-clover build/logs/clover.xml
./vendor/bin/php-coveralls -v
# INITIAL INSTALL
# Ensures composer is installed
composer.phar:
curl -sS https://getcomposer.org/installer | php
# Ensures composer is installed and dependencies loaded
composer.lock: composer.phar
./composer.phar --no-interaction install

View File

@@ -0,0 +1,147 @@
[![Build Status](https://github.com/sirn-se/phrity-util-errorhandler/actions/workflows/acceptance.yml/badge.svg)](https://github.com/sirn-se/phrity-util-errorhandler/actions)
[![Coverage Status](https://coveralls.io/repos/github/sirn-se/phrity-util-errorhandler/badge.svg?branch=main)](https://coveralls.io/github/sirn-se/phrity-util-errorhandler?branch=main)
# Error Handler utility
The PHP [error handling](https://www.php.net/manual/en/book.errorfunc.php) can be somewhat of a headache.
Typically an application uses a system level [error handler](https://www.php.net/manual/en/function.set-error-handler.php) and/or suppressing errors using the `@` prefix.
But those cases when your code need to act on triggered errors are more tricky.
This library provides two convenience methods to handle errors on code blocks, either by throwing exceptions or running callback code when an error occurs.
Current version supports PHP `^7.2|^8.0`.
## Installation
Install with [Composer](https://getcomposer.org/);
```
composer require phrity/util-errorhandler
```
## The Error Handler
The class provides two main methods; `with()` and `withAll()`.
The difference is that `with()` will act immediately on an error and abort further code execution, while `withAll()` will attempt to execute the entire code block before acting on errors that occurred.
### Throwing ErrorException
```php
use Phrity\Util\ErrorHandler;
$handler = new ErrorHandler();
$result = $handler->with(function () {
// Code to execute
return $success_result;
});
$result = $handler->withAll(function () {
// Code to execute
return $success_result;
});
```
The examples above will run the callback code, but if an error occurs it will throw an [ErrorException](https://www.php.net/manual/en/class.errorexception.php).
Error message and severity will be that of the triggering error.
* `with()` will throw immediately when occured
* `withAll()` will throw when code is complete; if more than one error occurred, the first will be thrown
### Throwing specified Throwable
```php
use Phrity\Util\ErrorHandler;
$handler = new ErrorHandler();
$result = $handler->with(function () {
// Code to execute
return $success_result;
}, new RuntimeException('A specified error'));
$result = $handler->withAll(function () {
// Code to execute
return $success_result;
}, new RuntimeException('A specified error'));
```
The examples above will run the callback code, but if an error occurs it will throw provided Throwable.
The thrown Throwable will have an [ErrorException](https://www.php.net/manual/en/class.errorexception.php) attached as `$previous`.
* `with()` will throw immediately when occured
* `withAll()` will throw when code is complete; if more than one error occurred, the first will be thrown
### Using callback
```php
use Phrity\Util\ErrorHandler;
$handler = new ErrorHandler();
$result = $handler->with(function () {
// Code to execute
return $success_result;
}, function (ErrorException $error) {
// Code to handle error
return $error_result;
});
$result = $handler->withAll(function () {
// Code to execute
return $success_result;
}, function (array $errors, $success_result) {
// Code to handle errors
return $error_result;
});
```
The examples above will run the callback code, but if an error occurs it will call the error callback as well.
* `with()` will run the error callback immediately when error occured; error callback expects an ErrorException instance
* `withAll()` will run the error callback when code is complete; error callback expects an array of ErrorException and the returned result of code callback
### Filtering error types
Both `with()` and `withAll()` accepts error level(s) as last parameter.
```php
use Phrity\Util\ErrorHandler;
$handler = new ErrorHandler();
$result = $handler->with(function () {
// Code to execute
return $success_result;
}, null, E_USER_ERROR);
$result = $handler->withAll(function () {
// Code to execute
return $success_result;
}, null, E_USER_ERROR & E_USER_WARNING);
```
Any value or combination of values accepted by [set_error_handler](https://www.php.net/manual/en/function.set-error-handler.php) is usable.
Default is `E_ALL`. [List of constants](https://www.php.net/manual/en/errorfunc.constants.php).
### The global error handler
The class also has global `set()` and `restore()` methods.
```php
use Phrity\Util\ErrorHandler;
$handler = new ErrorHandler();
$handler->set(); // Throws ErrorException on error
$handler->set(new RuntimeException('A specified error')); // Throws provided Throwable on error
$handler->set(function (ErrorException $error) {
// Code to handle errors
return $error_result;
}); // Runs callback on error
$handler->restore(); // Restores error handler
```
### Class synopsis
```php
Phrity\Util\ErrorHandler {
/* Methods */
public __construct()
public with(callable $callback, mixed $handling = null, int $levels = E_ALL) : mixed
public withAll(callable $callback, mixed $handling = null, int $levels = E_ALL) : mixed
public set($handling = null, int $levels = E_ALL) : mixed
public restore() : bool
}
```
## Versions
| Version | PHP | |
| --- | --- | --- |
| `1.1` | `^7.4\|^8.0` | Some improvements |
| `1.0` | `^7.2\|^8.0` | Initial version |

View File

@@ -0,0 +1,33 @@
{
"name": "phrity/util-errorhandler",
"type": "library",
"description": "Inline error handler; catch and resolve errors for code block.",
"homepage": "https://phrity.sirn.se/util-errorhandler",
"keywords": ["error", "warning"],
"license": "MIT",
"authors": [
{
"name": "Sören Jensen",
"email": "sirn@sirn.se",
"homepage": "https://phrity.sirn.se"
}
],
"autoload": {
"psr-4": {
"Phrity\\Util\\": "src/"
}
},
"autoload-dev": {
"psr-4": {
"Phrity\\Util\\Tests\\": "tests/"
}
},
"require": {
"php": "^7.4 | ^8.0"
},
"require-dev": {
"phpunit/phpunit": "^9.0 | ^10.0 | ^11.0",
"php-coveralls/php-coveralls": "^2.0",
"squizlabs/php_codesniffer": "^3.5"
}
}

View File

@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" colors="true" bootstrap="vendor/autoload.php" xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/11.0/phpunit.xsd">
<testsuites>
<testsuite name="Phrity Util/Accessor tests">
<directory>./tests/</directory>
</testsuite>
</testsuites>
<source>
<include>
<directory suffix=".php">./src/</directory>
</include>
</source>
</phpunit>

View File

@@ -0,0 +1,120 @@
<?php
/**
* File for ErrorHandler utility class.
* @package Phrity > Util > ErrorHandler
*/
namespace Phrity\Util;
use ErrorException;
use Throwable;
/**
* ErrorHandler utility class.
* Allows catching and resolving errors inline.
*/
class ErrorHandler
{
/* ----------------- Public methods ---------------------------------------------- */
/**
* Set error handler to run until removed.
* @param mixed $handling
* - If null, handler will throw ErrorException
* - If Throwable $t, throw $t with ErrorException attached as previous
* - If callable, will invoke callback with ErrorException as argument
* @param int $levels Error levels to catch, all errors by default
* @return mixed Previously registered error handler, if any
*/
public function set($handling = null, int $levels = E_ALL)
{
return set_error_handler($this->getHandler($handling), $levels);
}
/**
* Remove error handler.
* @return bool True if removed
*/
public function restore(): bool
{
return restore_error_handler();
}
/**
* Run code with error handling, breaks on first encountered error.
* @param callable $callback The code to run
* @param mixed $handling
* - If null, handler will throw ErrorException
* - If Throwable $t, throw $t with ErrorException attached as previous
* - If callable, will invoke callback with ErrorException as argument
* @param int $levels Error levels to catch, all errors by default
* @return mixed Return what $callback returns, or what $handling retuns on error
*/
public function with(callable $callback, $handling = null, int $levels = E_ALL)
{
$error = null;
$result = null;
try {
$this->set(null, $levels);
$result = $callback();
} catch (ErrorException $e) {
$error = $this->handle($handling, $e);
} finally {
$this->restore();
}
return $error ?: $result;
}
/**
* Run code with error handling, comletes code before handling errors
* @param callable $callback The code to run
* @param mixed $handling
* - If null, handler will throw ErrorException
* - If Throwable $t, throw $t with ErrorException attached as previous
* - If callable, will invoke callback with ErrorException as argument
* @param int $levels Error levels to catch, all errors by default
* @return mixed Return what $callback returns, or what $handling retuns on error
*/
public function withAll(callable $callback, $handling = null, int $levels = E_ALL)
{
$errors = [];
$this->set(function (ErrorException $e) use (&$errors) {
$errors[] = $e;
}, $levels);
$result = $callback();
$this->restore();
$error = empty($errors) ? null : $this->handle($handling, $errors, $result);
return $error ?: $result;
}
/* ----------------- Private helpers --------------------------------------------- */
// Get handler function
private function getHandler($handling)
{
return function ($severity, $message, $file, $line) use ($handling) {
$error = new ErrorException($message, 0, $severity, $file, $line);
$this->handle($handling, $error);
};
}
// Handle error according to $handlig type
private function handle($handling, $error, $result = null)
{
if (is_callable($handling)) {
return $handling($error, $result);
}
if (is_array($error)) {
$error = array_shift($error);
}
if ($handling instanceof Throwable) {
try {
throw $error;
} finally {
throw $handling;
}
}
throw $error;
}
}

View File

@@ -0,0 +1,303 @@
<?php
/**
* File for ErrorHandler function tests.
* @package Phrity > Util > ErrorHandler
*/
declare(strict_types=1);
namespace Phrity\Util;
use ErrorException;
use RuntimeException;
use Phrity\Util\ErrorHandler;
use PHPUnit\Framework\TestCase;
/**
* ErrorHandler test class.
*/
class ErrorHandlerTest extends TestCase
{
/**
* Set up for all tests
*/
public function setUp(): void
{
error_reporting(-1);
}
public function testSetNull(): void
{
$handler = new ErrorHandler();
$handler->set();
// Verify exception
try {
trigger_error('An error');
} catch (ErrorException $e) {
$this->assertEquals('An error', $e->getMessage());
$this->assertEquals(0, $e->getCode());
$this->assertEquals(E_USER_NOTICE, $e->getSeverity());
$this->assertNull($e->getPrevious());
}
// Restore handler
$this->assertTrue($handler->restore());
}
public function testSetThrowable(): void
{
$handler = new ErrorHandler();
$handler->set(new RuntimeException('A provided exception', 23));
// Verify exception
try {
trigger_error('An error');
} catch (RuntimeException $e) {
$this->assertEquals('A provided exception', $e->getMessage());
$this->assertEquals(23, $e->getCode());
$this->assertNotNull($e->getPrevious());
$prev = $e->getPrevious();
$this->assertEquals('An error', $prev->getMessage());
$this->assertEquals(0, $prev->getCode());
$this->assertEquals(E_USER_NOTICE, $prev->getSeverity());
$this->assertNull($prev->getPrevious());
}
// Restore handler
$this->assertTrue($handler->restore());
}
public function testSetCallback(): void
{
$handler = new ErrorHandler();
$result = null;
$handler->set(function ($error) use (&$result) {
$result = [
'message' => $error->getMessage(),
'code' => $error->getCode(),
'severity' => $error->getSeverity(),
];
});
// Verify exception
trigger_error('An error');
$this->assertEquals([
'message' => 'An error',
'code' => 0,
'severity' => E_USER_NOTICE,
], $result);
// Restore handler
$this->assertTrue($handler->restore());
}
public function testWithNull(): void
{
$handler = new ErrorHandler();
$check = false;
// No exception
$result = $handler->with(function () {
return 'Code success';
});
$this->assertEquals('Code success', $result);
// Verify exception
try {
$result = $handler->with(function () use (&$check) {
trigger_error('An error');
$check = true;
return 'Code success';
});
} catch (ErrorException $e) {
$this->assertEquals('An error', $e->getMessage());
$this->assertEquals(0, $e->getCode());
$this->assertEquals(E_USER_NOTICE, $e->getSeverity());
$this->assertNull($e->getPrevious());
}
$this->assertFalse($check);
// Verify that exception is thrown
$this->expectException('ErrorException');
$result = $handler->with(function () {
trigger_error('An error');
return 'Code success';
});
}
public function testWithThrowable(): void
{
$handler = new ErrorHandler();
$check = false;
// No exception
$result = $handler->with(function () {
return 'Code success';
});
$this->assertEquals('Code success', $result);
// Verify exception
try {
$result = $handler->with(function () use (&$check) {
trigger_error('An error');
$check = true;
return 'Code success';
}, new RuntimeException('A provided exception', 23));
} catch (RuntimeException $e) {
$this->assertEquals('A provided exception', $e->getMessage());
$this->assertEquals(23, $e->getCode());
$this->assertNotNull($e->getPrevious());
$prev = $e->getPrevious();
$this->assertEquals('An error', $prev->getMessage());
$this->assertEquals(0, $prev->getCode());
$this->assertEquals(E_USER_NOTICE, $prev->getSeverity());
$this->assertNull($prev->getPrevious());
}
$this->assertFalse($check);
// Verify that exception is thrown
$this->expectException('RuntimeException');
$result = $handler->with(function () {
trigger_error('An error');
return 'Code success';
}, new RuntimeException('A provided exception', 23));
}
public function testWithCallback(): void
{
$handler = new ErrorHandler();
$check = false;
// No error invoked
$result = $handler->with(function () {
return 'Code success';
}, function ($error) {
return $error;
});
$this->assertEquals('Code success', $result);
// An error is invoked
$result = $handler->with(function () use (&$check) {
trigger_error('An error');
$check = true;
return 'Code success';
}, function ($error) {
return $error;
});
$this->assertFalse($check);
$this->assertEquals('An error', $result->getMessage());
$this->assertEquals(0, $result->getCode());
$this->assertEquals(E_USER_NOTICE, $result->getSeverity());
$this->assertNull($result->getPrevious());
}
public function testWithAllNull(): void
{
$handler = new ErrorHandler();
$check = false;
// No error invoked
$result = $handler->withAll(function () {
return 'Code success';
});
$this->assertEquals('Code success', $result);
// Verify exception
try {
$result = $handler->withAll(function () use (&$check) {
trigger_error('An error');
$check = true;
return 'Code success';
});
} catch (ErrorException $e) {
$this->assertEquals('An error', $e->getMessage());
$this->assertEquals(0, $e->getCode());
$this->assertEquals(E_USER_NOTICE, $e->getSeverity());
$this->assertNull($e->getPrevious());
}
$this->assertTrue($check);
// Verify that exception is thrown
$this->expectException('ErrorException');
$result = $handler->withAll(function () {
trigger_error('An error');
return 'Code success';
});
}
public function testWithAllThrowable(): void
{
$handler = new ErrorHandler();
$check = false;
// No exception
$result = $handler->withAll(function () {
return 'Code success';
});
$this->assertEquals('Code success', $result);
// Verify exception
try {
$result = $handler->withAll(function () use (&$check) {
trigger_error('An error');
$check = true;
return 'Code success';
}, new RuntimeException('A provided exception', 23));
} catch (RuntimeException $e) {
$this->assertEquals('A provided exception', $e->getMessage());
$this->assertEquals(23, $e->getCode());
$this->assertNotNull($e->getPrevious());
$prev = $e->getPrevious();
$this->assertEquals('An error', $prev->getMessage());
$this->assertEquals(0, $prev->getCode());
$this->assertEquals(E_USER_NOTICE, $prev->getSeverity());
$this->assertNull($prev->getPrevious());
}
$this->assertTrue($check);
// Verify that exception is thrown
$this->expectException('RuntimeException');
$result = $handler->withAll(function () {
trigger_error('An error');
return 'Code success';
}, new RuntimeException('A provided exception', 23));
}
public function testWithAllCallback(): void
{
$handler = new ErrorHandler();
$check = false;
// No error invoked
$result = $handler->withAll(function () {
return 'Code success';
}, function ($error, $result) {
return $error;
});
$this->assertEquals('Code success', $result);
// An error is invoked
$result = $handler->withAll(function () use (&$check) {
trigger_error('An error');
trigger_error('Another error', E_USER_WARNING);
$check = true;
return 'Code success';
}, function ($errors, $result) {
return ['errors' => $errors, 'result' => $result];
});
$this->assertTrue($check);
$this->assertEquals('Code success', $result['result']);
$this->assertEquals('An error', $result['errors'][0]->getMessage());
$this->assertEquals(0, $result['errors'][0]->getCode());
$this->assertEquals(E_USER_NOTICE, $result['errors'][0]->getSeverity());
$this->assertNull($result['errors'][0]->getPrevious());
$this->assertEquals('Another error', $result['errors'][1]->getMessage());
$this->assertEquals(0, $result['errors'][1]->getCode());
$this->assertEquals(E_USER_WARNING, $result['errors'][1]->getSeverity());
$this->assertNull($result['errors'][1]->getPrevious());
}
}