Skip to content

1.1.0

Choose a tag to compare

@Ne-Lexa Ne-Lexa released this 27 May 15:18
· 35 commits to master since this release

Added interface \Nelexa\RequestDtoBundle\Dto\ConstructRequestObjectInterface for consturct DTO from request

Example:

use Nelexa\RequestDtoBundle\Dto\ConstructRequestObjectInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Validator\ConstraintViolationListInterface;

class ExampleDTO implements ConstructRequestObjectInterface
{
    /** @Assert\Range(min=1) */
    private int $page;

    /**
     * @Assert\NotBlank
     * @Assert\Regex("~^\d{10,13}$~", message="Invalid phone number")
     */
    private string $phone;

    public function __construct(Request $request)
    {
        $this->page = $request->request->getInt('p', 1);

        // sanitize phone number
        $phone = (string) $request->request->get('phone');
        $phone = preg_replace('~\D~', '', $phone);
        $this->phone = (string) $phone;
    }

    public function getPage(): int
    {
        return $this->page;
    }

    public function getPhone(): string
    {
        return $this->phone;
    }
}

class AppController extends AbstractController
{
    public function exampleAction(
        ExampleDTO $dto,
        ConstraintViolationListInterface $errors
    ): Response {
        $data = [
            'page' => $dto->getPage(),
            'phone' => $dto->getPhone(),
            'errors' => $errors,
        ];

        return $this->json($data, $errors->count() === 0 ? 200 : 400);
    }
}