v0.2.0 (4/N): make:bridge:resource --with-dto + symfony/validator

Closes the input-validation gap that was the audit's headline finding.
The legacy generated controller's `if (isset($data['title']))…` body
accepted any JSON: empty title slipped through, malformed JSON got
swallowed by `?? []`, wrong types were silently coerced via casts.

The --with-dto flag generates:
  - src/Dto/Create<Name>Dto.php — readonly DTO with #[Assert\NotBlank]
    on title and #[Assert\Length(max: 255)]
  - src/Dto/Update<Name>Dto.php — same DTO with all fields nullable
    so PATCH callers send only what changed
  - src/Controller/<Name>Controller.php — same shape as the legacy
    controller but actions dispatch via #[MapRequestPayload]

Validation failures (missing required field, wrong type, malformed
JSON, oversize string) become RFC 7807 application/problem+json
automatically — Symfony's RequestPayloadValueResolver does the work.
No `if-isset` boilerplate, no silent coercion.

Behaviour:
  - --with-dto is opt-in; legacy template still ships unchanged
  - audit suggests flipping to default-on once stable; that's a
    follow-up
  - maker fails loud (composer require hint) if symfony/validator
    isn't autoloadable
  - skeleton + example/todo composer.json pull symfony/validator so
    scaffolded apps work out of the box

Snapshot test exercises both modes (legacy + --with-dto). New
baselines TodoControllerWithDto.php / CreateTodoDto.php /
UpdateTodoDto.php under tests/snapshot/.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-05-03 20:10:52 +02:00
parent 0710d81783
commit 5498c3c91e
13 changed files with 737 additions and 29 deletions

View File

@@ -24,6 +24,7 @@ use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
use Symfony\Component\Uid\Uuid;
use Symfony\Component\Validator\Constraints\NotBlank;
/**
* `make:bridge:resource <Name>` — generates the three files needed to
@@ -71,11 +72,21 @@ final class BridgeResourceMaker extends AbstractMaker
InputOption::VALUE_NONE,
'Use auto-incrementing int IDs instead of the default UUIDv7.',
)
->addOption(
'with-dto',
null,
InputOption::VALUE_NONE,
'Generate Create<Name>Dto + Update<Name>Dto alongside the controller and dispatch via #[MapRequestPayload]. Requires symfony/validator.',
)
->setHelp(
"The maker creates three files:\n\n"
"The maker creates three files (or five with --with-dto):\n\n"
." • <info>src/Entity/Todo.php</info> — Doctrine entity tagged with #[BridgeResource]\n"
." • <info>src/Controller/TodoController.php</info> — CRUD on /api/todos\n"
." • <info>{qml_path}/TodoList.qml</info> — starter ReactiveListModel snippet\n\n"
."With <info>--with-dto</info> the controller dispatches via #[MapRequestPayload]\n"
."against generated Create/Update DTOs (validated, no if-isset stubs):\n\n"
." • <info>src/Dto/CreateTodoDto.php</info> — POST payload with #[Assert\\NotBlank] etc.\n"
." • <info>src/Dto/UpdateTodoDto.php</info> — PATCH payload (all fields nullable)\n\n"
."After the maker, run <info>bin/console make:migration</info> and apply it.\n"
);
}
@@ -95,6 +106,13 @@ final class BridgeResourceMaker extends AbstractMaker
{
$rawName = (string) $input->getArgument('name');
$useUuid = !(bool) $input->getOption('int-id');
$useDto = (bool) $input->getOption('with-dto');
if ($useDto && !class_exists(NotBlank::class)) {
$io->error('--with-dto requires symfony/validator. Run: composer require symfony/validator');
return;
}
$singular = ucfirst(Str::asCamelCase($rawName));
$pluralCamel = Str::singularCamelCaseToPluralCamelCase($singular);
@@ -128,9 +146,34 @@ final class BridgeResourceMaker extends AbstractMaker
__DIR__.'/templates/Entity.tpl.php',
$vars,
);
if ($useDto) {
$createDto = $generator->createClassNameDetails(
'Create'.$singular,
'Dto\\',
'Dto',
);
$updateDto = $generator->createClassNameDetails(
'Update'.$singular,
'Dto\\',
'Dto',
);
$generator->generateFile(
'src/Dto/'.$createDto->getShortName().'.php',
__DIR__.'/templates/CreateDto.tpl.php',
$vars,
);
$generator->generateFile(
'src/Dto/'.$updateDto->getShortName().'.php',
__DIR__.'/templates/UpdateDto.tpl.php',
$vars,
);
}
$controllerTemplate = $useDto ? 'ControllerWithDto.tpl.php' : 'Controller.tpl.php';
$generator->generateFile(
'src/Controller/'.$controllerFqcn->getShortName().'.php',
__DIR__.'/templates/Controller.tpl.php',
__DIR__.'/templates/'.$controllerTemplate,
$vars,
);

View File

@@ -0,0 +1,95 @@
<?= "<?php\n" ?>
declare(strict_types=1);
namespace App\Controller;
use App\Dto\Create<?= $entity_short ?>Dto;
use App\Dto\Update<?= $entity_short ?>Dto;
use <?= $entity_fqcn ?>;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Attribute\MapRequestPayload;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
/**
* Auto-generated CRUD controller for the <?= $singular ?> bridge resource (DTO-shaped).
* Edit freely — re-running make:bridge:resource won't overwrite this file.
*
* Validated input via #[MapRequestPayload]: malformed JSON, missing
* required fields, or constraint violations produce RFC 7807
* problem+json automatically (Symfony's RequestPayloadValueResolver).
*/
#[Route('<?= $route ?>')]
final class <?= $entity_short ?>Controller
{
public function __construct(
private readonly EntityManagerInterface $em,
private readonly NormalizerInterface $normalizer,
) {
}
#[Route('', name: '<?= $resource ?>_list', methods: ['GET'])]
public function list(): JsonResponse
{
$items = $this->em->getRepository(<?= $entity_short ?>::class)->findAll();
return new JsonResponse($this->normalizer->normalize($items, 'json'));
}
#[Route('', name: '<?= $resource ?>_create', methods: ['POST'])]
public function create(#[MapRequestPayload] Create<?= $entity_short ?>Dto $dto): JsonResponse
{
$entity = new <?= $entity_short ?>();
$entity->setTitle($dto->title);
$entity->setDone($dto->done);
$this->em->persist($entity);
$this->em->flush();
return new JsonResponse(
$this->normalizer->normalize($entity, 'json'),
Response::HTTP_CREATED,
);
}
#[Route('/{id}', name: '<?= $resource ?>_update', methods: ['PATCH'])]
public function update(string $id, #[MapRequestPayload] Update<?= $entity_short ?>Dto $dto): JsonResponse
{
$entity = $this->em->getRepository(<?= $entity_short ?>::class)->find($id);
if (null === $entity) {
return new JsonResponse(
['title' => 'Not Found', 'status' => 404],
Response::HTTP_NOT_FOUND,
['Content-Type' => 'application/problem+json'],
);
}
if (null !== $dto->title) {
$entity->setTitle($dto->title);
}
if (null !== $dto->done) {
$entity->setDone($dto->done);
}
$this->em->flush();
return new JsonResponse($this->normalizer->normalize($entity, 'json'));
}
#[Route('/{id}', name: '<?= $resource ?>_delete', methods: ['DELETE'])]
public function delete(string $id): JsonResponse
{
$entity = $this->em->getRepository(<?= $entity_short ?>::class)->find($id);
if (null === $entity) {
return new JsonResponse(null, Response::HTTP_NO_CONTENT);
}
$this->em->remove($entity);
$this->em->flush();
return new JsonResponse(null, Response::HTTP_NO_CONTENT);
}
}

View File

@@ -0,0 +1,26 @@
<?= "<?php\n" ?>
declare(strict_types=1);
namespace App\Dto;
use Symfony\Component\Validator\Constraints as Assert;
/**
* Validated payload for POST <?= $route ?>.
*
* Auto-generated alongside <?= $entity_short ?>Controller's create() action.
* #[MapRequestPayload] in the controller turns malformed JSON or any
* Assert violation here into an RFC 7807 problem+json response — no
* controller-level if-isset boilerplate, no silent type coercion.
*/
final readonly class Create<?= $entity_short ?>Dto
{
public function __construct(
#[Assert\NotBlank]
#[Assert\Length(max: 255)]
public string $title,
public bool $done = false,
) {
}
}

View File

@@ -0,0 +1,24 @@
<?= "<?php\n" ?>
declare(strict_types=1);
namespace App\Dto;
use Symfony\Component\Validator\Constraints as Assert;
/**
* Validated payload for PATCH <?= $route ?>/{id}.
*
* All fields are nullable so PATCH callers can send only the fields
* they want to change. The controller checks each for null and
* skips the corresponding entity setter.
*/
final readonly class Update<?= $entity_short ?>Dto
{
public function __construct(
#[Assert\Length(max: 255)]
public ?string $title = null,
public ?bool $done = null,
) {
}
}