dkx/slim-body-mapper

This package is abandoned and no longer maintained. No replacement package was suggested.

Map request body into DTO's

1.1.0 2019-06-18 12:34 UTC

This package is auto-updated.

Last update: 2024-01-18 23:14:10 UTC


README

Map request body into DTO's

Installation

$ composer require dkx/slim-body-mapper

Usage

Imagine that you could define incoming HTTP request data as a DTO, let it validate automatically with symfony/validation and inject into the route handler like this:

<?php

use DKX\SlimBodyMapper\MappedHttpRequestBody;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Symfony\Component\Validator\Constraints as Assert;

class UserDTO implements MappedHttpRequestBody
{

    /**
     * @var string
     * @Assert\Type("string")
     * @Assert\NotBlank
     * @Assert\Email
     */
    public $email;
    
    /**
     * @var string
     * @Assert\Type("string")
     * @Assert\NotBlank 
     */
    public $password;

}

final class CreateUserController
{

    public function __invoke(ServerRequestInterface $request, ResponseInterface $response, array $args, UserDTO $user): ResponseInterface
    {
        // todo: save $user to DB
        return $response;
    }

}

Well that's exactly what this library is doing.

Configuration:

<?php

use DKX\SlimBodyMapper\BodyMapper;
use DKX\SlimInjectableRoutes\InjectableRoutes;
use Slim\Container;

$c = new Container();
$c['foundHandler'] = function() {
    $routes = new InjectableRoutes;
    $bodyMapper = new BodyMapper;
    $routes->provideInjectableSetup($bodyMapper->getInjectableSetup());
    
    return $routes;
};

If you want to know what we did there look at the documentation for dkx/slim-injectable-routes.

Validation

The validation is not enabled by default. To change that create the ValidatorInterface object and set it to BodyMapper.

<?php

$validator = createValidatorSamehow();
$bodyMapper = new BodyMapper;
$bodyMapper->setValidator($validator);

Custom key name

<?php

use DKX\SlimBodyMapper\Annotations as Mapping;
use DKX\SlimBodyMapper\MappedHttpRequestBody;

class UserDTO implements MappedHttpRequestBody
{

    /**
     * @Mapping\Path("user_name")
     * @var string
     */
    public $userName;

}

File upload

Base64 encoded files can be automatically transformed into DKX\SlimBodyMapper\UploadedFile which is extending the Slim\Http\UploadedFile.

It adds the possibility to validate such files with symfony/validation.

<?php

use DKX\SlimBodyMapper\Annotations as Mapping;
use DKX\SlimBodyMapper\MappedHttpRequestBody;

class UserDTO implements MappedHttpRequestBody
{

    /**
     * @Mapping\UploadedFile
     * @var \DKX\SlimBodyMapper\UploadedFile
     */
    public $avatar;

}