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

@@ -0,0 +1,26 @@
<?php
declare(strict_types=1);
namespace App\Dto;
use Symfony\Component\Validator\Constraints as Assert;
/**
* Validated payload for POST /api/todos.
*
* Auto-generated alongside TodoController'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 CreateTodoDto
{
public function __construct(
#[Assert\NotBlank]
#[Assert\Length(max: 255)]
public string $title,
public bool $done = false,
) {
}
}

View File

@@ -0,0 +1,98 @@
<?php
declare(strict_types=1);
namespace App\Controller;
use App\Dto\CreateTodoDto;
use App\Dto\UpdateTodoDto;
use App\Entity\Todo;
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 Todo 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('/api/todos')]
final class TodoController
{
public function __construct(
private readonly EntityManagerInterface $em,
private readonly NormalizerInterface $normalizer,
) {
}
#[Route('', name: 'todo_list', methods: ['GET'])]
public function list(): JsonResponse
{
$items = $this->em->getRepository(Todo::class)->findAll();
return new JsonResponse($this->normalizer->normalize($items, 'json'));
}
#[Route('', name: 'todo_create', methods: ['POST'])]
public function create(#[MapRequestPayload] CreateTodoDto $dto): JsonResponse
{
$entity = new Todo();
$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: 'todo_update', methods: ['PATCH'])]
public function update(string $id, #[MapRequestPayload] UpdateTodoDto $dto): JsonResponse
{
$entity = $this->em->getRepository(Todo::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: 'todo_delete', methods: ['DELETE'])]
public function delete(string $id): JsonResponse
{
$entity = $this->em->getRepository(Todo::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,24 @@
<?php
declare(strict_types=1);
namespace App\Dto;
use Symfony\Component\Validator\Constraints as Assert;
/**
* Validated payload for PATCH /api/todos/{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 UpdateTodoDto
{
public function __construct(
#[Assert\Length(max: 255)]
public ?string $title = null,
public ?bool $done = null,
) {
}
}

View File

@@ -24,18 +24,6 @@ sed -i "s|\"../../php\"|\"$BUNDLE\"|" "$APP/symfony/composer.json"
rm -f "$APP/symfony/composer.lock"
( cd "$APP/symfony" && composer install --no-interaction --quiet )
# Remove the existing maker outputs so the regenerators don't bail.
rm -f "$APP/symfony/src/Entity/Todo.php"
rm -f "$APP/symfony/src/Controller/TodoController.php"
rm -f "$APP/qml/TodoList.qml"
# Run every maker we cover.
( cd "$APP/symfony" \
&& bin/console make:bridge:resource Todo --no-interaction >/dev/null \
&& bin/console make:bridge:command MarkAllDone --no-interaction >/dev/null \
&& bin/console make:bridge:window Todo --no-interaction >/dev/null )
# Compare each generated file to its snapshot baseline.
fail=0
check() {
local generated="$1"
@@ -49,15 +37,42 @@ check() {
fi
}
check "$APP/symfony/src/Entity/Todo.php" "$SCRIPT_DIR/Todo.php"
check "$APP/symfony/src/Controller/TodoController.php" "$SCRIPT_DIR/TodoController.php"
check "$APP/qml/TodoList.qml" "$SCRIPT_DIR/TodoList.qml"
clear_outputs() {
rm -f "$APP/symfony/src/Entity/Todo.php"
rm -f "$APP/symfony/src/Controller/TodoController.php"
rm -f "$APP/symfony/src/Dto/CreateTodoDto.php"
rm -f "$APP/symfony/src/Dto/UpdateTodoDto.php"
rm -f "$APP/qml/TodoList.qml"
}
# ── Mode 1: legacy (no --with-dto) ────────────────────────────────────
clear_outputs
( cd "$APP/symfony" \
&& bin/console make:bridge:resource Todo --no-interaction >/dev/null \
&& bin/console make:bridge:command MarkAllDone --no-interaction >/dev/null \
&& bin/console make:bridge:window Todo --no-interaction >/dev/null )
check "$APP/symfony/src/Entity/Todo.php" "$SCRIPT_DIR/Todo.php"
check "$APP/symfony/src/Controller/TodoController.php" "$SCRIPT_DIR/TodoController.php"
check "$APP/qml/TodoList.qml" "$SCRIPT_DIR/TodoList.qml"
check "$APP/symfony/src/Controller/MarkAllDoneController.php" "$SCRIPT_DIR/MarkAllDoneController.php"
check "$APP/qml/TodoWindow.qml" "$SCRIPT_DIR/TodoWindow.qml"
check "$APP/qml/TodoWindow.qml" "$SCRIPT_DIR/TodoWindow.qml"
# ── Mode 2: --with-dto (re-runs make:bridge:resource only) ────────────
# The entity + QML output is byte-identical between modes; only the
# controller swaps and the two DTOs appear. Re-checking the unchanged
# outputs would just be noise.
clear_outputs
( cd "$APP/symfony" \
&& bin/console make:bridge:resource Todo --with-dto --no-interaction >/dev/null )
check "$APP/symfony/src/Controller/TodoController.php" "$SCRIPT_DIR/TodoControllerWithDto.php"
check "$APP/symfony/src/Dto/CreateTodoDto.php" "$SCRIPT_DIR/CreateTodoDto.php"
check "$APP/symfony/src/Dto/UpdateTodoDto.php" "$SCRIPT_DIR/UpdateTodoDto.php"
if [ "$fail" -ne 0 ]; then
echo "Snapshot test failed. If the change is intended, update the baselines under $SCRIPT_DIR/." >&2
exit 1
fi
echo "All maker outputs match snapshots."
echo "All maker outputs match snapshots (legacy + --with-dto modes)."