prugala / symfony-request-dto
Convert Symfony request to DTO object
Fund package maintenance!
prugala
Installs: 33 561
Dependents: 0
Suggesters: 0
Security: 0
Stars: 56
Watchers: 3
Forks: 4
Open Issues: 2
Requires
- php: ^8.0
- doctrine/annotations: ^1.13 || ^2.0
- symfony/cache: ^5.4 || ^6.0
- symfony/dependency-injection: ^5.4 || ^6.0
- symfony/http-kernel: ^5.4 || ^6.0
- symfony/property-access: ^5.4 || ^6.0
- symfony/serializer: ^5.4 || ^6.0
- symfony/validator: ^5.4 || ^6.0
Requires (Dev)
- phpunit/phpunit: ^9
This package is auto-updated.
Last update: 2024-11-15 11:05:56 UTC
README
Map request on your DTO object with zero configuration.
Install
composer require prugala/symfony-request-dto
Support
- Content data
- Form-data
- Query parameters
- Uploaded files
- Headers
TODO
- Configurable normalizers and encoders
Usage
- Create a DTO that implements the interface
Prugala\RequestDto\Dto\RequestDtoInterface
- Use your DTO in a Controller e.g.:
<?php declare(strict_types=1); namespace App\Controller; use Symfony\Component\HttpFoundation\JsonResponse; use App\Dto\ExampleDto; class ExampleController { public function update(ExampleDto $dto): JsonResponse { return new JsonResponse($dto); } }
- Done, your JSON (other data are on TODO list) will be mapped on your object
Support for uploaded files
Bundle has support for uploaded files.
#[Assert\File(maxSize: 1000, mimeTypes: 'text/plain')] public ?UploadedFile $exampleFile = null;
Send request with form-data with field exampleFile
and you will have access to your file in object property.
Validation
You can use symfony/validator to validate request.
If you provide invalid data you will get response 400 with json object with violation list.
Example:
- Create DTO with constraint:
<?php declare(strict_types=1); namespace App\Dto; use Prugala\RequestDto\Dto\RequestDtoInterface; use Symfony\Component\Validator\Constraints as Assert; class ExampleDto implements RequestDtoInterface { public string $name; #[Assert\Range(min: 2, max: 10)] public int $position; }
- Call your action with JSON object:
{ "name": "test", "position": 1 }
- You get response 400 with JSON:
{ "errors": [ { "message": "This value should be between 2 and 10.", "code": "04b91c99-a946-4221-afc5-e65ebac401eb", "context": { "field": "position" } } ] }
If you want to change response format, overwrite method formatErrors
in listener Prugala\RequestDto\EventListener\RequestValidationExceptionListener
Testing
composer tests
Contributing
Please see CONTRIBUTING for details.
License
The MIT License (MIT). Please see License File for more information.