PHP code example of tbbc / rest-util

1. Go to this page and download the library: Download tbbc/rest-util library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

tbbc / rest-util example snippets


// 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',
));


$exceptionMap = new ExceptionMap();
$exceptionMap->add($invalidArgumentExceptionMapping);

// Error resolver initialization
$errorResolver       = new ErrorResolver($exceptionMap);
$defaultErrorFactory = new DefaultErrorFactory();
$errorResolver->registerFactory($defaultErrorFactory);

$exception = new \InvalidArgumentException('This is an invalid argument exception');
$error     = $errorResolver->resolve($exception);

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"
}
*/