Phase 2 sub-commit 4: make:bridge:resource maker
Some checks failed
CI / Quality (push) Failing after 1m55s

Bundle picks up symfony/maker-bundle as require-dev. New BridgeResourceMaker
under PhpQml\Bridge\Maker generates three files for a named resource:

  - src/Entity/<Name>.php  — Doctrine entity with #[BridgeResource]
                             and a UUIDv7 id by default. --int-id flips
                             to auto-incrementing int IDs.
  - src/Controller/<Name>Controller.php — CRUD on /api/{plural} (list,
                             create, update, delete) with serializer-
                             normalised JSON responses.
  - {qml_path}/<Name>List.qml — starter ListView wrapped around a
                             ReactiveListModel bound to the right topic
                             and source URL.

The Doctrine subscriber from sub-commit 2 picks the entity up
automatically — no per-resource listener generated. The QML snippet
target defaults to '../qml/' (relative to the Symfony project root)
and is overridable via the maker's $qmlPath constructor arg.

Templates live under src/Maker/templates/ as .tpl.php files using
short-echo and alternative-syntax control structures by convention.
PHPStan and php-cs-fixer skip them — the maker's Generator binds the
template variables at render time.

Skeleton picks up MakerBundle as a `dev` bundle and require-dev'd
symfony/maker-bundle, so `bin/console make:bridge:resource Todo`
works out-of-the-box.

Verified: maker runs end-to-end against `Todo` and emits readable,
syntactically valid output. composer quality (16 tests, 45 assertions,
PHPStan clean, cs-fixer clean) stays green.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-05-02 02:45:42 +02:00
parent 030502ca38
commit 4a42de702b
10 changed files with 603 additions and 5 deletions

View File

@@ -1,7 +1,10 @@
<?php
$finder = (new PhpCsFixer\Finder())
->in([__DIR__ . '/src', __DIR__ . '/tests']);
->in([__DIR__ . '/src', __DIR__ . '/tests'])
// Maker templates use short-echo syntax and alternative-syntax control
// structures by design — cs-fixer's @Symfony rules would mangle them.
->notPath('Maker/templates');
return (new PhpCsFixer\Config())
->setRiskyAllowed(true)

View File

@@ -27,7 +27,8 @@
"phpstan/phpstan-symfony": "^2",
"phpstan/phpstan-doctrine": "^2",
"friendsofphp/php-cs-fixer": "^3",
"symfony/phpunit-bridge": "^8.0"
"symfony/phpunit-bridge": "^8.0",
"symfony/maker-bundle": "^1.62"
},
"autoload": {
"psr-4": {

View File

@@ -9,3 +9,6 @@ parameters:
- tests
excludePaths:
- vendor/*
# Maker templates use variables injected by the Generator at
# render time; static analysis can't see the binding.
- src/Maker/templates/*

View File

@@ -0,0 +1,169 @@
<?php
declare(strict_types=1);
namespace PhpQml\Bridge\Maker;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\Mapping as ORM;
use PhpQml\Bridge\Attribute\BridgeResource;
use Symfony\Bundle\MakerBundle\ConsoleStyle;
use Symfony\Bundle\MakerBundle\DependencyBuilder;
use Symfony\Bundle\MakerBundle\Generator;
use Symfony\Bundle\MakerBundle\InputConfiguration;
use Symfony\Bundle\MakerBundle\Maker\AbstractMaker;
use Symfony\Bundle\MakerBundle\Str;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Serializer\SerializerInterface;
use Symfony\Component\Uid\Uuid;
/**
* `make:bridge:resource <Name>` — generates the three files needed to
* expose a Doctrine entity as a reactive bridge resource:
*
* - src/Entity/<Name>.php — `#[BridgeResource]` + `#[ORM\Entity]`
* - src/Controller/<Name>Controller.php — CRUD on `/api/{plural}`
* - {qml_path}/<Name>List.qml — starter `ReactiveListModel`
*
* The Doctrine subscriber installed by the bundle picks the entity up
* automatically — no per-resource listener is generated. The QML snippet
* goes to `qml_path` (default: `../qml/`, configurable via the bundle's
* `qml_path` option in services.yaml).
*
* See PLAN.md §8 (*Custom makers*).
*/
final class BridgeResourceMaker extends AbstractMaker
{
public function __construct(
private readonly string $qmlPath = '../qml/',
) {
}
public static function getCommandName(): string
{
return 'make:bridge:resource';
}
public static function getCommandDescription(): string
{
return 'Generate a #[BridgeResource] entity, CRUD controller, and QML snippet.';
}
public function configureCommand(Command $command, InputConfiguration $inputConfig): void
{
$command
->addArgument(
'name',
InputArgument::OPTIONAL,
'Singular name of the resource (e.g. Todo).',
)
->addOption(
'int-id',
null,
InputOption::VALUE_NONE,
'Use auto-incrementing int IDs instead of the default UUIDv7.',
)
->setHelp(
"The maker creates three files:\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"
."After the maker, run <info>bin/console make:migration</info> and apply it.\n"
);
}
public function interact(InputInterface $input, ConsoleStyle $io, Command $command): void
{
if (null === $input->getArgument('name')) {
$name = $io->ask('What is the resource name (e.g. Todo)?', null, static function (?string $v): string {
if (null === $v || '' === trim($v)) {
throw new \RuntimeException('Resource name cannot be empty.');
}
return ucfirst(trim($v));
});
$input->setArgument('name', $name);
}
}
public function generate(InputInterface $input, ConsoleStyle $io, Generator $generator): void
{
$rawName = (string) $input->getArgument('name');
$useUuid = !(bool) $input->getOption('int-id');
$singular = ucfirst(Str::asCamelCase($rawName));
$pluralCamel = Str::singularCamelCaseToPluralCamelCase($singular);
$resource = strtolower($singular);
$pluralUnder = strtolower(preg_replace('/(?<!^)[A-Z]/', '_$0', $pluralCamel) ?? $pluralCamel);
$route = '/api/'.$pluralUnder;
$entityFqcn = $generator->createClassNameDetails(
$singular,
'Entity\\',
);
$controllerFqcn = $generator->createClassNameDetails(
$singular,
'Controller\\',
'Controller',
);
$vars = [
'singular' => $singular,
'plural' => $pluralUnder,
'resource' => $resource,
'route' => $route,
'entity_short' => $entityFqcn->getShortName(),
'entity_fqcn' => $entityFqcn->getFullName(),
'controller_fqcn' => $controllerFqcn->getFullName(),
'use_uuid' => $useUuid,
];
$generator->generateFile(
'src/Entity/'.$entityFqcn->getShortName().'.php',
__DIR__.'/templates/Entity.tpl.php',
$vars,
);
$generator->generateFile(
'src/Controller/'.$controllerFqcn->getShortName().'.php',
__DIR__.'/templates/Controller.tpl.php',
$vars,
);
// QML snippet — outside the Symfony project root, so we use a
// path relative to the project's working dir.
$qmlTarget = rtrim($this->qmlPath, '/').'/'.$singular.'List.qml';
$generator->generateFile(
$qmlTarget,
__DIR__.'/templates/QmlSnippet.tpl.php',
$vars,
);
$generator->writeChanges();
$this->writeSuccessMessage($io);
$io->text([
'Next:',
' 1) <info>bin/console make:migration</info>',
' 2) <info>bin/console doctrine:migrations:migrate -n</info>',
" 3) Use <info>{$singular}List.qml</info> from your QML.",
]);
}
public function configureDependencies(DependencyBuilder $dependencies): void
{
$dependencies->addClassDependency(ORM\Entity::class, 'doctrine/orm');
$dependencies->addClassDependency(BridgeResource::class, 'php-qml/bridge');
$dependencies->addClassDependency(Route::class, 'symfony/routing');
$dependencies->addClassDependency(JsonResponse::class, 'symfony/http-foundation');
$dependencies->addClassDependency(Request::class, 'symfony/http-foundation');
$dependencies->addClassDependency(EntityManagerInterface::class, 'doctrine/orm');
$dependencies->addClassDependency(SerializerInterface::class, 'symfony/serializer');
$dependencies->addClassDependency(Uuid::class, 'symfony/uid');
}
}

View File

@@ -0,0 +1,95 @@
<?= "<?php\n" ?>
declare(strict_types=1);
namespace App\Controller;
use <?= $entity_fqcn ?>;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Serializer\SerializerInterface;
/**
* Auto-generated CRUD controller for the <?= $singular ?> bridge resource.
* Edit freely — re-running make:bridge:resource won't overwrite this file.
*/
#[Route('<?= $route ?>')]
final class <?= $entity_short ?>Controller
{
public function __construct(
private readonly EntityManagerInterface $em,
private readonly SerializerInterface $serializer,
) {
}
#[Route('', name: '<?= $resource ?>_list', methods: ['GET'])]
public function list(): JsonResponse
{
$items = $this->em->getRepository(<?= $entity_short ?>::class)->findAll();
return new JsonResponse($this->serializer->normalize($items, 'json'));
}
#[Route('', name: '<?= $resource ?>_create', methods: ['POST'])]
public function create(Request $request): JsonResponse
{
$data = json_decode((string) $request->getContent(), true) ?? [];
$entity = new <?= $entity_short ?>();
if (isset($data['title'])) {
$entity->setTitle((string) $data['title']);
}
if (isset($data['done'])) {
$entity->setDone((bool) $data['done']);
}
$this->em->persist($entity);
$this->em->flush();
return new JsonResponse(
$this->serializer->normalize($entity, 'json'),
Response::HTTP_CREATED,
);
}
#[Route('/{id}', name: '<?= $resource ?>_update', methods: ['PATCH'])]
public function update(string $id, Request $request): 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'],
);
}
$data = json_decode((string) $request->getContent(), true) ?? [];
if (isset($data['title'])) {
$entity->setTitle((string) $data['title']);
}
if (isset($data['done'])) {
$entity->setDone((bool) $data['done']);
}
$this->em->flush();
return new JsonResponse($this->serializer->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,71 @@
<?= "<?php\n" ?>
declare(strict_types=1);
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
use PhpQml\Bridge\Attribute\BridgeResource;
<?php if ($use_uuid): ?>
use Symfony\Component\Uid\Uuid;
<?php endif; ?>
#[ORM\Entity]
#[BridgeResource(name: '<?= $resource ?>')]
class <?= $entity_short ?>
{
<?php if ($use_uuid): ?>
#[ORM\Id]
#[ORM\Column(type: 'uuid', unique: true)]
private Uuid $id;
<?php else: ?>
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column]
private ?int $id = null;
<?php endif; ?>
#[ORM\Column(length: 255)]
private string $title = '';
#[ORM\Column]
private bool $done = false;
<?php if ($use_uuid): ?>
public function __construct()
{
$this->id = Uuid::v7();
}
public function getId(): Uuid
{
return $this->id;
}
<?php else: ?>
public function getId(): ?int
{
return $this->id;
}
<?php endif; ?>
public function getTitle(): string
{
return $this->title;
}
public function setTitle(string $title): void
{
$this->title = $title;
}
public function isDone(): bool
{
return $this->done;
}
public function setDone(bool $done): void
{
$this->done = $done;
}
}

View File

@@ -0,0 +1,28 @@
// Auto-generated by `bin/console make:bridge:resource <?= $singular ?>`.
// Drop this into your QML and customize the delegate to taste.
import QtQuick
import QtQuick.Controls
import PhpQml.Bridge
ListView {
id: <?= $resource ?>List
model: ReactiveListModel {
baseUrl: BackendConnection.url
token: BackendConnection.token
source: "<?= $route ?>"
topic: "app://model/<?= $resource ?>"
}
delegate: ItemDelegate {
required property string id
required property string title
required property bool done
required property bool pending
text: title + (done ? " ✓" : "")
opacity: pending ? 0.5 : 1.0
width: ListView.view.width
}
}