digitalrevolution/symfony-request-validation

Automatic request validation for symfony

Installs: 55 479

Dependents: 0

Suggesters: 0

Security: 0

Stars: 10

Watchers: 3

Forks: 1

Open Issues: 3

Type:symfony-bundle

v2.4.0 2023-12-07 12:42 UTC

README

Minimum PHP Version Minimum Symfony Version Run tests

Symfony Request Validation

A request validation component for Symfony. Ease the validation of request properties without the need for an entire Symfony Form.

Installation

Include the library as dependency in your own project via:

composer require "digitalrevolution/symfony-request-validation"

Update /config/bundles.php:

return [
    ...
    DigitalRevolution\SymfonyRequestValidation\Bundle\RequestValidationBundle::class => ['all' => true],
];

Usage

  1. Create your own ExampleRequest class which extends the AbstractValidatedRequest class.
  2. Configure your own ValidationRules. See the Validation shorthand library for more information about the rules.
  3. Ensure your ExampleRequest class is registered as service in your Symfony project.
use DigitalRevolution\SymfonyRequestValidation\AbstractValidatedRequest;
use DigitalRevolution\SymfonyRequestValidation\ValidationRules;

class ExampleRequest extends AbstractValidatedRequest
{
    protected function getValidationRules(): ValidationRules
    {
        return new ValidationRules([
            'request' => [
                'productId'   => 'required|int|min:0',
                'productName' => 'required|string|between:50,255'
            ]
        ]);
    }

    public function getProductId(): int
    {
        return $this->request->request->getInt('productId');
    }
    
    public function getProductName(): string
    {
        return $this->request->request->getString('productName');
    }
}

All that remains is using your ExampleRequest class in your Controller and it will only be invoked when the request validation passes.

class ExampleController
{
    /**
     * @Route("/", name="my_example")
     */
    public function index(ExampleRequest $request): Response
    {
        return ...;
    }
}

Invalid request handling

By default if a request is invalid an InvalidRequestException will be thrown. If you prefer a different behaviour, overwrite the handleViolations method.

class ExampleRequest extends AbstractValidatedRequest
{
    ...
    
    protected function handleViolations(ConstraintViolationListInterface $violationList): void
    {
        $renderer = new ViolationListRenderer($violationList);
        $this->logger->error($renderer->render());
    }
}

Note: if no exceptions are thrown in the handleViolations, you'll always receive a request in your Controller. Use Request->isValid() to verify the request is valid.

About us

At 123inkt (Part of Digital Revolution B.V.), every day more than 50 development professionals are working on improving our internal ERP and our several shops. Do you want to join us? We are looking for developers.