Rest util library for PHP.
This library implement some useful util classes for resolving recurrent issues in Rest(ful) APIs (i.e: Error handling).
Rest utilitary library for PHP
Using Composer, just $ composer require tbbc/rest-util
package or:
{
"require": {
"tbbc/rest-util": "dev-master"
}
}
Converting Exception into Error object:
1. First you have to define an ExceptionMapping
, for the sake of the example,
we use PHP
, but a YamlLoader
is also available:
// Exception mapping configuration
$invalidArgumentExceptionMapping = new ExceptionMapping(array(
'exceptionClassName' => '\InvalidArgumentException',
'factory' => 'default',
'httpStatusCode' => 400,
'errorCode' => 400101,
'errorMessage' => null,
'errorExtendedMessage' => 'Extended message',
'errorMoreInfoUrl' => 'http://api.my.tld/doc/error/400101',
));
2. The ExceptionMapping
must be added to ExceptionMap
:
$exceptionMap = new ExceptionMap();
$exceptionMap->add($invalidArgumentExceptionMapping);
3. We plug the ErrorResolver
with an ErrorFactory, a DefaultErrorFactory
is bundled within the lib:
// Error resolver initialization
$errorResolver = new ErrorResolver($exceptionMap);
$defaultErrorFactory = new DefaultErrorFactory();
$errorResolver->registerFactory($defaultErrorFactory);
4. Resolve error!
$exception = new \InvalidArgumentException('This is an invalid argument exception');
$error = $errorResolver->resolve($exception);
5. The $error
variable is now assigned an ErrorInterface
object which implements a toArray()
method
to allow easy serialization method of your choice:
print_r($error->toArray());
/* will output
Array
(
[http_status_code] => 400
[code] => 400101
[message] => This is an invalid argument exception.
[extended_message] => Extended message
[more_info_url] => http://api.my.tld/doc/error/400101
)
*/
echo json_encode($error->toArray());
/* And voilà! You get a ready to use json normalized error response body
{
"http_status_code": 400,
"code": 400101,
"message": "This is an invalid argument exception.",
"extended_message": "Extended message",
"more_info_url": "http:\/\/api.my.tld\/doc\/error\/400101"
}
*/
For more concrete real life usage, take a look at our bundle for integrating the lib into a Symfony application: TbbcRestUtilBundle.
First make sure you have installed all the dependencies, run:
$ composer install --dev
then, run the test from within the root directory:
$ vendor/bin/phpunit
- Take a look at the list of issues.
- Fork
- Write a test (for either new feature or bug)
- Make a PR
- PHP 5.3+
- Boris Guéry - [email protected] - http://borisguery.com
- Benjamin Dulau - [email protected]
The Big Brains Company - Rest Util
is licensed under the MIT License - see the LICENSE file for details