akrabat / rka-content-type-renderer
Render an array to a JSON/XML/HTML PSR-7 Response based on a PSR-7 Request's Accept header.
Installs: 324 945
Dependents: 2
Suggesters: 0
Security: 0
Stars: 41
Watchers: 6
Forks: 10
Open Issues: 2
Requires
- php: ^7.3 || ^8.0
- psr/http-message: ^1.0
- willdurand/negotiation: ^3.0
Requires (Dev)
- crell/api-problem: ^3.2
- laminas/laminas-diactoros: ^2.8
- nocarrier/hal: ^0.9.12
- phpunit/phpunit: ^8.0
- squizlabs/php_codesniffer: ^3.5
Suggests
- crell/api-problem: For creating Api-Problem (RFC7801) data that can be rendered using ApiProblemRenderer
- nocarrier/hal: For creating HAL documents that can be rendered using HalRenderer
README
Render an array (or HAL object) to a JSON/XML/HTML PSR-7 Response based on a PSR-7 Request's Accept header.
Installation
composer require akrabat/rka-content-type-renderer
Usage
// given: // $request instanceof Psr\Http\Message\RequestInterface // $response instanceof Psr\Http\Message\ResponseInterface $data = [ 'items' => [ [ 'name' => 'Alex', 'is_admin' => true, ], [ 'name' => 'Robin', 'is_admin' => false, ], ], ]; $renderer = new RKA\ContentTypeRenderer\Renderer(); $response = $renderer->render($request, $response, $data); return $response->withStatus(200);
The constructor takes a parameter, $pretty
that defaults to true
. Set to false
to disable pretty printing.
HalRenderer
This component also supports nocarrier/hal objects with the HalRenderer
:
$hal = new Nocarrier\Hal( '/foo', [ 'items' => [ [ 'name' => 'Alex', 'is_admin' => true, ], [ 'name' => 'Robin', 'is_admin' => false, ], ], ] ); $renderer = new RKA\ContentTypeRenderer\HalRenderer(); $response = $renderer->render($request, $response, $hal); return $response->withStatus(200);
ApiRenderer
This component also supports crell/ApiProblem objects with the ApiProblemRenderer
:
$problem = new Crell\ApiProblem("Something unexpected happened"); $renderer = new RKA\ContentTypeRenderer\ApiProblemRenderer(); $response = $renderer->render($request, $response, $problem); return $response->withStatus(500);
Arrays of objects
If you have an array of objects, then the renderer will still work as long as the objects implement PHP's JsonSerializable interface.
Testing
- Code style:
$ phpcs
- Unit tests:
$ phpunit
- Code coverage:
$ phpunit --coverage-html ./build