Skip to content

Map request on your DTO object with zero configuration.

License

Notifications You must be signed in to change notification settings

Aerendir/symfony-request-dto

 
 

Repository files navigation

github actions Latest Stable Version Total Downloads License PHP Version Require

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

  1. Create a DTO that implements the interface Prugala\RequestDto\Dto\RequestDtoInterface
  2. 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);
        }
    }
  3. 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:

  1. 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;
     }
  2. Call your action with JSON object:
    {
      "name": "test",
      "position": 1 
    }
  3. 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.

About

Map request on your DTO object with zero configuration.

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages

  • PHP 100.0%