DKX/SlimBodyMapper
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
{
public $email;
public $password;
}
final class CreateUserController
{
public function __invoke(ServerRequestInterface $request, ResponseInterface $response, array $args, UserDTO $user): ResponseInterface
{
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
{
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
{
public $avatar;
}