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
Requires
- php: ^7.2
- dkx/method-injector: ^0.0.1
- dkx/slim-injectable-routes: ^0.0.1
- doctrine/annotations: ^1.6
- psr/http-message: ^1.0
- roave/better-reflection: ^3.2
- symfony/validator: ^4.2
Requires (Dev)
- doctrine/cache: ^1.8
- mockery/mockery: dev-master
- phpstan/extension-installer: ^1.0
- phpstan/phpstan: ^0.11.8
- phpstan/phpstan-mockery: ^0.11.1
- phpstan/phpstan-phpunit: ^0.11.2
- phpstan/phpstan-strict-rules: ^0.11.1
- phpunit/phpunit: ^8.0
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;
}