vi-tech/dto-bundle

DTO resolver for symfony projects

3.0.1 2022-02-01 11:51 UTC

This package is auto-updated.

Last update: 2022-09-29 13:11:21 UTC


README

Package for an automatic request to predefined structures conversion in symfony applications.

Build Status Coverage Status

Installation

$ composer require vi-tech/dto-bundle

Declare bundle in configuration:

// config/bundles.php
return [
    \ViTech\DataObjectBundle\DataObjectBundle::class => ['all' => true],
];

Usage

<?php

use Symfony\Component\HttpFoundation\Response;
use ViTech\DataObjectBundle\Object\AbstractObject;

class RegistrationDto extends AbstractObject
{
    /** @var string */
    public $login;
    
    /** @var string */
    public $password;
}

class RegistrationController
{
    public function __invoke(RegistrationDto $registration): Response
    {
        // Register new user using $registration
        // $registration->login contains Request::$request->get('login'). Same for password.

        return new Response();
    }
}

Data in RegistrationDto $registration matches Request::$request properties.
If request contains properties that are not declared in DTO they will be omitted.
On property type mismatch Symfony\Component\HttpKernel\Exception\BadRequestHttpException will be thrown.

It is a common approach to validate DTO within application.
The simplest way to do that is to declare constraints annotations for the same DTO and use symfony validator.

<?php

use Symfony\Component\HttpFoundation\Response;
use ViTech\DataObjectBundle\Object\AbstractObject;
use Symfony\Component\Validator\Validator\ValidatorInterface;

class RegistrationDto extends AbstractObject
{
    /**
     * @Assert\NotBlank()
     * @Assert\UniqueLogin()
     *
     * @var string
     */
    public $login;
    
    /**
     * @Assert\NotBlank()
     * @Assert\PasswordRules()
     *
     * @var string
     */
    public $password;
}

class RegistrationController
{
    /** @var ValidatorInterface */
    private $validator;

    public function __invoke(RegistrationDto $registration): Response
    {
        $violations = $this->validator->validate($registration);
        if (count($violations)) {
            // Handle constraints violations
        }

        // register new user using $registration

        return new Response();
    }
}