pew-pew / http-factory
HTTP factory for decoding request and encoding responses with symfony integration
Installs: 1 209
Dependents: 0
Suggesters: 0
Security: 0
Stars: 3
Watchers: 1
Forks: 0
Open Issues: 0
Requires
- php: ^8.3
- symfony/http-foundation: ^5.4|^6.0|^7.0
Requires (Dev)
- friendsofphp/php-cs-fixer: ^3.49
- phpunit/phpunit: ^10.5
- rybakit/msgpack: ^0.9|^1.0
- symfony/config: ^5.4|^6.0|^7.0
- symfony/dependency-injection: ^5.4|^6.0|^7.0
- symfony/http-kernel: ^5.4|^6.0|^7.0
- symfony/var-dumper: ^5.4|^6.0|^7.0
- symfony/yaml: ^5.4|^6.0|^7.0
- vimeo/psalm: ^5.21
Suggests
- ext-json: Adds JSON decoder and encoder
- rybakit/msgpack: Adds MSGPACK decoder and encoder
- symfony/config: For Symfony Bundle support
- symfony/dependency-injection: For Symfony Bundle support
- symfony/http-kernel: For Symfony Bundle support
- symfony/yaml: Adds YAML decoder and encoder
This package is auto-updated.
Last update: 2024-11-23 12:29:18 UTC
README
HTTP Factory
A set of drivers for encoding HTTP responses and decoding HTTP requests.
Installation
PewPew HTTP Factory is available as Composer repository and can be installed using the following command in a root of your project:
$ composer require pew-pew/http-factory
More detailed installation instructions are here.
Usage
Decoder
// Symfony Request $request = new \Symfony\Component\HttpFoundation\Request(); // Requests Factory $requests = new \PewPew\HttpFactory\RequestDecoderFactory([ new \PewPew\HttpFactory\Driver\JsonDriver(), ]); $payload = $requests ->createDecoder($request) // Detect passed "content-type" header and // create decoder if available. ?->decode($request->getContent(true)); // Decode request body.
Encoder
// Symfony Request $request = new \Symfony\Component\HttpFoundation\Request(); // Responses Factory $responses = new \PewPew\HttpFactory\ResponseEncoderFactory([ new \PewPew\HttpFactory\Driver\JsonDriver(), ]); $response = $responses ->createEncoder($request) // Detect passed "accept" header and create // encoder if available. ?->encode(['some' => 'any'], 200); // Encode payload and create response.
Symfony Integration
Add the bundle to your bundles.php
file:
// bundles.php return [ // ... PewPew\HttpFactory\HttpFactoryBundle::class => ['all' => true], ];
Use ResponseEncoderFactoryInterface
and RequestDecoderFactoryInterface
in your services:
use PewPew\HttpFactory\ResponseEncoderFactoryInterface; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpFoundation\Request; final readonly class ExampleController { public function __construct( private ResponseEncoderFactoryInterface $responses, ) {} public function someAction(Request $request): Response { $encoder = $this->responses->createEncoder($request); if ($encoder === null) { throw new \Symfony\Component\HttpFoundation\Exception\BadRequestException( 'Unsupported "accept" request header', ); } return $encoder->encode([ 'status' => 'ok' ], Response::HTTP_OK); } }