Giter VIP home page Giter VIP logo

request-validation-bundle's Introduction

API Request Validation Bundle

Build Status codecov

This is a simple library for easier and cleaner handling requests. You can simply define incoming payload and validation rules with it. Also you can simply cast incoming data for example to int value.

Installation

composer require mkoprek/request-validation-bundle

Usage

You need to create class which is extending AbstractRequest, then:

  • Create field you want to get from request as a class properties
  • Add validation rules as a Symfony Constraints to getValidationRules() method
  • Add casting variables to other types or object (ex. Uuid)

Request:

<?php
declare(strict_types=1);

use MKoprek\RequestValidation\Request\AbstractRequest;
use Symfony\Component\Uid\Uuid;
use Symfony\Component\Validator\Constraints as Assert;

class UserCreateRequest extends AbstractRequest
{
    protected string $id;
    protected ?string $name;

    public function getId(): Uuid
    {
        return Uuid::fromString($this->id);
    }
    
    public function getName(): ?string
    {
        return $this->name;
    }

    /**
     * @return array<Assert\Collection>
     */
    public function getValidationRules(): array
    {
        return [
            new Assert\Collection([
                'id' => new Assert\Required([
                    new Assert\NotNull(),
                    new Assert\NotBlank(),
                    new Assert\Uuid(),
                ]),
                'name' => new Assert\Required([
                    new Assert\NotNull(),
                    new Assert\NotBlank(),
                    new Assert\Type('string'),
                ]),
            ]),
        ];
    }
}

Controller:

<?php
declare(strict_types=1);

use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;

#[Route('/api')]
class UserCreateController
{
    #[Route('/users', name: 'users.create', methods: 'POST')]
    public function post(UserCreateRequest $request): JsonResponse
    {
        $id = $request->getId();
        $name = $request->getName();

        $this->commandBus->handle(
            CreateUserCommand($request->getId(), $request->getName())
        );

        return new JsonResponse(['id' => $id->toRfc4122()], Response::HTTP_CREATED);
    }
}

Validation

Validation is done automatically before request is parsed by controller. If there will be any validation error ApiValidationException is thrown. If you want to return JSON with errors just add this to your services.yaml. It will handle ALL exceptions.

  MKoprek\RequestValidation\Response\ResponseSubscriber:
    tags:
      - { name: kernel.event_subscriber, event: kernel.exception }

Example response with validation errors:

{
    "status": 422,
    "message": "Request validation error",
    "details": [
        {
            "field": "[id]",
            "error": "This field is missing."
        },
        {
            "field": "[name]",
            "error": "This field is missing."
        },
        {
            "field": "[name2]",
            "error": "This field was not expected."
        }
    ]

Example with some other exception.

{
"status": 500,
"message": "Attempted to call an undefined method named 'notExists' of class 'UserCreateRequest'."
}

License

MIT

Author Information

Created by Maciej Koprek (mkoprek) 2021

request-validation-bundle's People

Contributors

mkoprek avatar dominx99 avatar

Watchers

James Cloos avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.