Phase 2 sub-commit 2: ModelPublisher + #[BridgeResource] + Doctrine listener
Some checks failed
CI / Quality (push) Failing after 1m54s
Some checks failed
CI / Quality (push) Failing after 1m54s
Bundle gains the model layer that bridges Doctrine entities to Mercure
without per-resource glue. Three new pieces:
- `#[BridgeResource(name: ?string)]` attribute marks an entity as a
reactive bridge model. Topic name defaults to the lowercased class
basename and can be overridden per resource.
- `ModelPublisher` translates entity changes into PLAN.md §4 envelopes
({op, id, data, version, ?correlationKey}) and dual-publishes them
on `app://model/{name}` (collection topic) and `app://model/{name}/{id}`
(entity topic). Entity normalisation goes through Symfony's Serializer
(ObjectNormalizer + DateTime + BackedEnum) for predictable JSON. The
envelope `version` field is a per-process monotonic counter — fine for
single-instance dev mode; production should back this with a Postgres
SEQUENCE or equivalent (noted for Phase 4).
- `DoctrineBridgeListener` registers `postPersist`/`postUpdate`/
`postRemove` via `#[AsDoctrineListener]` and routes events through
ModelPublisher. Entities without `#[BridgeResource]` are silently
skipped.
Plus the correlation-key plumbing the §5 Update Semantics layer needs:
- `CorrelationContext` is a per-request holder for the originating
request's `Idempotency-Key`.
- `CorrelationKeyListener` reads the header on `KernelEvents::REQUEST`
and clears the context on `KernelEvents::TERMINATE` (worker mode
hygiene). CLI mutations see no key, which is correct.
Bundle composer.json picks up `doctrine/dbal`, `doctrine/orm`,
`doctrine/doctrine-bundle`, `symfony/serializer`, `symfony/property-*`,
`symfony/uid`. PHPStan extension `phpstan-doctrine` added so the listener's
event-args types resolve. Skeleton's framework.yaml enables `serializer`
and `property_info`.
Tests: 5 new for ModelPublisher (dual publish, correlation echo, delete
op omits data, untagged entities ignored, version increments). Total:
16 tests, 45 assertions, PHPStan clean, cs-fixer clean.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -12,19 +12,22 @@
|
||||
"symfony/http-foundation": "^8.0",
|
||||
"symfony/console": "^8.0",
|
||||
"symfony/dependency-injection": "^8.0",
|
||||
"symfony/config": "^8.0"
|
||||
},
|
||||
"suggest": {
|
||||
"doctrine/dbal": "Required for the bridge:doctor database-reachable check and for ModelPublisher (Phase 2 sub-commit 2).",
|
||||
"doctrine/orm": "Required for #[BridgeResource]-based reactive models (Phase 2 sub-commit 2)."
|
||||
"symfony/config": "^8.0",
|
||||
"symfony/serializer": "^8.0",
|
||||
"symfony/property-access": "^8.0",
|
||||
"symfony/property-info": "^8.0",
|
||||
"symfony/uid": "^8.0",
|
||||
"doctrine/dbal": "^4.0",
|
||||
"doctrine/orm": "^3.0",
|
||||
"doctrine/doctrine-bundle": "^3.0"
|
||||
},
|
||||
"require-dev": {
|
||||
"phpunit/phpunit": "^11",
|
||||
"phpstan/phpstan": "^2",
|
||||
"phpstan/phpstan-symfony": "^2",
|
||||
"phpstan/phpstan-doctrine": "^2",
|
||||
"friendsofphp/php-cs-fixer": "^3",
|
||||
"symfony/phpunit-bridge": "^8.0",
|
||||
"doctrine/dbal": "^4.0"
|
||||
"symfony/phpunit-bridge": "^8.0"
|
||||
},
|
||||
"autoload": {
|
||||
"psr-4": {
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
includes:
|
||||
- vendor/phpstan/phpstan-symfony/extension.neon
|
||||
- vendor/phpstan/phpstan-doctrine/extension.neon
|
||||
|
||||
parameters:
|
||||
level: 6
|
||||
|
||||
25
framework/php/src/Attribute/BridgeResource.php
Normal file
25
framework/php/src/Attribute/BridgeResource.php
Normal file
@@ -0,0 +1,25 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace PhpQml\Bridge\Attribute;
|
||||
|
||||
/**
|
||||
* Marks a Doctrine entity as a reactive bridge resource.
|
||||
*
|
||||
* Tagged entities have their persist/update/remove events automatically
|
||||
* mirrored onto the Mercure topics `app://model/{name}` and
|
||||
* `app://model/{name}/{id}` (PLAN.md §4 *Push*, §6 *ModelPublisher*).
|
||||
*
|
||||
* The maker generated by Phase 2 sub-commit 4 produces entities with
|
||||
* this attribute pre-attached.
|
||||
*/
|
||||
#[\Attribute(\Attribute::TARGET_CLASS)]
|
||||
final readonly class BridgeResource
|
||||
{
|
||||
public function __construct(
|
||||
/** Logical resource name used in topics. Defaults to lowercased class basename. */
|
||||
public ?string $name = null,
|
||||
) {
|
||||
}
|
||||
}
|
||||
36
framework/php/src/CorrelationContext.php
Normal file
36
framework/php/src/CorrelationContext.php
Normal file
@@ -0,0 +1,36 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace PhpQml\Bridge;
|
||||
|
||||
/**
|
||||
* Per-request correlation key holder.
|
||||
*
|
||||
* The HTTP request's `Idempotency-Key` (PLAN.md §4 *Idempotency*) is
|
||||
* stashed here on RequestEvent and read back by ModelPublisher when
|
||||
* it builds Mercure envelopes, so QML clients can match Mercure echoes
|
||||
* to the optimistic mutation that originated them (§5).
|
||||
*
|
||||
* Cleared on TerminateEvent. CLI commands and out-of-request mutations
|
||||
* see no correlation key, which is the correct behaviour.
|
||||
*/
|
||||
final class CorrelationContext
|
||||
{
|
||||
private ?string $key = null;
|
||||
|
||||
public function set(?string $key): void
|
||||
{
|
||||
$this->key = $key;
|
||||
}
|
||||
|
||||
public function get(): ?string
|
||||
{
|
||||
return $this->key;
|
||||
}
|
||||
|
||||
public function clear(): void
|
||||
{
|
||||
$this->key = null;
|
||||
}
|
||||
}
|
||||
44
framework/php/src/EventListener/DoctrineBridgeListener.php
Normal file
44
framework/php/src/EventListener/DoctrineBridgeListener.php
Normal file
@@ -0,0 +1,44 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace PhpQml\Bridge\EventListener;
|
||||
|
||||
use Doctrine\Bundle\DoctrineBundle\Attribute\AsDoctrineListener;
|
||||
use Doctrine\ORM\Event\PostPersistEventArgs;
|
||||
use Doctrine\ORM\Event\PostRemoveEventArgs;
|
||||
use Doctrine\ORM\Event\PostUpdateEventArgs;
|
||||
use Doctrine\ORM\Events;
|
||||
use PhpQml\Bridge\ModelPublisher;
|
||||
|
||||
/**
|
||||
* Bridges Doctrine entity lifecycle events to Mercure publishes.
|
||||
*
|
||||
* Only entities with `#[BridgeResource]` actually publish — the routing
|
||||
* happens inside ModelPublisher::publishEntityChange. See PLAN.md §6.
|
||||
*/
|
||||
#[AsDoctrineListener(event: Events::postPersist)]
|
||||
#[AsDoctrineListener(event: Events::postUpdate)]
|
||||
#[AsDoctrineListener(event: Events::postRemove)]
|
||||
final readonly class DoctrineBridgeListener
|
||||
{
|
||||
public function __construct(
|
||||
private ModelPublisher $modelPublisher,
|
||||
) {
|
||||
}
|
||||
|
||||
public function postPersist(PostPersistEventArgs $args): void
|
||||
{
|
||||
$this->modelPublisher->publishEntityChange($args->getObject(), 'upsert');
|
||||
}
|
||||
|
||||
public function postUpdate(PostUpdateEventArgs $args): void
|
||||
{
|
||||
$this->modelPublisher->publishEntityChange($args->getObject(), 'upsert');
|
||||
}
|
||||
|
||||
public function postRemove(PostRemoveEventArgs $args): void
|
||||
{
|
||||
$this->modelPublisher->publishEntityChange($args->getObject(), 'delete');
|
||||
}
|
||||
}
|
||||
48
framework/php/src/EventSubscriber/CorrelationKeyListener.php
Normal file
48
framework/php/src/EventSubscriber/CorrelationKeyListener.php
Normal file
@@ -0,0 +1,48 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace PhpQml\Bridge\EventSubscriber;
|
||||
|
||||
use PhpQml\Bridge\CorrelationContext;
|
||||
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
|
||||
use Symfony\Component\HttpKernel\Event\RequestEvent;
|
||||
use Symfony\Component\HttpKernel\Event\TerminateEvent;
|
||||
use Symfony\Component\HttpKernel\KernelEvents;
|
||||
|
||||
/**
|
||||
* Reads `Idempotency-Key` off the incoming request and stashes it in
|
||||
* CorrelationContext for the duration of the request, then clears on
|
||||
* TerminateEvent so worker-mode requests don't leak between each other.
|
||||
*/
|
||||
final class CorrelationKeyListener implements EventSubscriberInterface
|
||||
{
|
||||
public function __construct(
|
||||
private readonly CorrelationContext $context,
|
||||
) {
|
||||
}
|
||||
|
||||
public static function getSubscribedEvents(): array
|
||||
{
|
||||
return [
|
||||
// Run early enough that any controller / Doctrine listener
|
||||
// sees the key; KernelEvents::REQUEST defaults are fine.
|
||||
KernelEvents::REQUEST => 'onRequest',
|
||||
KernelEvents::TERMINATE => 'onTerminate',
|
||||
];
|
||||
}
|
||||
|
||||
public function onRequest(RequestEvent $event): void
|
||||
{
|
||||
if (!$event->isMainRequest()) {
|
||||
return;
|
||||
}
|
||||
$key = $event->getRequest()->headers->get('Idempotency-Key');
|
||||
$this->context->set('' === $key || null === $key ? null : $key);
|
||||
}
|
||||
|
||||
public function onTerminate(TerminateEvent $event): void
|
||||
{
|
||||
$this->context->clear();
|
||||
}
|
||||
}
|
||||
117
framework/php/src/ModelPublisher.php
Normal file
117
framework/php/src/ModelPublisher.php
Normal file
@@ -0,0 +1,117 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace PhpQml\Bridge;
|
||||
|
||||
use PhpQml\Bridge\Attribute\BridgeResource;
|
||||
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
|
||||
|
||||
/**
|
||||
* Translates Doctrine entity lifecycle events into Mercure envelopes.
|
||||
*
|
||||
* For each change, dual-publishes to:
|
||||
* - `app://model/{name}` — collection topic, watched by ReactiveListModel
|
||||
* - `app://model/{name}/{id}` — entity topic, watched by ReactiveObject
|
||||
*
|
||||
* Topic / envelope shape per PLAN.md §4. The `correlationKey` echoes
|
||||
* the originating request's `Idempotency-Key` (§5 *Optimistic updates*).
|
||||
*
|
||||
* Phase 2 uses a per-process counter for the envelope `version` field
|
||||
* — sufficient for single-instance dev mode. Phase 4 / production should
|
||||
* back this with a persistent monotonic source (e.g. Postgres SEQUENCE).
|
||||
*/
|
||||
final class ModelPublisher
|
||||
{
|
||||
/** @var array<string, int> */
|
||||
private array $versions = [];
|
||||
|
||||
public function __construct(
|
||||
private readonly Publisher $publisher,
|
||||
private readonly CorrelationContext $correlationContext,
|
||||
private readonly NormalizerInterface $normalizer,
|
||||
) {
|
||||
}
|
||||
|
||||
public function publishEntityChange(object $entity, string $op): void
|
||||
{
|
||||
$resource = $this->resolveResource($entity);
|
||||
if (null === $resource) {
|
||||
return; // not a #[BridgeResource]
|
||||
}
|
||||
|
||||
$name = $resource->name ?? self::deriveName($entity::class);
|
||||
$id = (string) $this->extractId($entity);
|
||||
|
||||
$envelope = [
|
||||
'op' => $op,
|
||||
'id' => $id,
|
||||
'version' => $this->nextVersion($name),
|
||||
'data' => 'delete' === $op ? null : $this->normalize($entity),
|
||||
];
|
||||
|
||||
if (null !== $key = $this->correlationContext->get()) {
|
||||
$envelope['correlationKey'] = $key;
|
||||
}
|
||||
|
||||
$this->publisher->publish("app://model/{$name}", $envelope);
|
||||
$this->publisher->publish("app://model/{$name}/{$id}", $envelope);
|
||||
}
|
||||
|
||||
private function resolveResource(object $entity): ?BridgeResource
|
||||
{
|
||||
$reflection = new \ReflectionClass($entity);
|
||||
$attrs = $reflection->getAttributes(BridgeResource::class);
|
||||
if ([] === $attrs) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return $attrs[0]->newInstance();
|
||||
}
|
||||
|
||||
private function extractId(object $entity): mixed
|
||||
{
|
||||
if (method_exists($entity, 'getId')) {
|
||||
return $entity->getId();
|
||||
}
|
||||
|
||||
$r = new \ReflectionClass($entity);
|
||||
if ($r->hasProperty('id')) {
|
||||
$prop = $r->getProperty('id');
|
||||
$prop->setAccessible(true);
|
||||
|
||||
return $prop->getValue($entity);
|
||||
}
|
||||
|
||||
throw new \LogicException(\sprintf('Cannot extract id from %s: no getId() method or $id property.', $entity::class));
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
private function normalize(object $entity): array
|
||||
{
|
||||
/** @var array<string, mixed> $data */
|
||||
$data = $this->normalizer->normalize($entity, 'json', [
|
||||
'circular_reference_handler' => static fn (object $o): string => (string) ($o->getId() ?? ''),
|
||||
]);
|
||||
|
||||
return $data;
|
||||
}
|
||||
|
||||
private function nextVersion(string $name): int
|
||||
{
|
||||
if (!isset($this->versions[$name])) {
|
||||
$this->versions[$name] = (int) (microtime(true) * 1_000_000);
|
||||
}
|
||||
|
||||
return ++$this->versions[$name];
|
||||
}
|
||||
|
||||
private static function deriveName(string $fqcn): string
|
||||
{
|
||||
$basename = substr($fqcn, (int) strrpos($fqcn, '\\') + 1);
|
||||
|
||||
return strtolower($basename);
|
||||
}
|
||||
}
|
||||
137
framework/php/tests/ModelPublisherTest.php
Normal file
137
framework/php/tests/ModelPublisherTest.php
Normal file
@@ -0,0 +1,137 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace PhpQml\Bridge\Tests;
|
||||
|
||||
use PhpQml\Bridge\Attribute\BridgeResource;
|
||||
use PhpQml\Bridge\CorrelationContext;
|
||||
use PhpQml\Bridge\ModelPublisher;
|
||||
use PhpQml\Bridge\Publisher;
|
||||
use PhpQml\Bridge\Tests\Helper\HubSpy;
|
||||
use PHPUnit\Framework\Attributes\CoversClass;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
use Symfony\Component\Serializer\Encoder\JsonEncoder;
|
||||
use Symfony\Component\Serializer\Normalizer\BackedEnumNormalizer;
|
||||
use Symfony\Component\Serializer\Normalizer\DateTimeNormalizer;
|
||||
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
|
||||
use Symfony\Component\Serializer\Serializer;
|
||||
|
||||
#[BridgeResource(name: 'todo')]
|
||||
final class FakeTodo
|
||||
{
|
||||
public function __construct(
|
||||
public string $id,
|
||||
public string $title,
|
||||
public bool $done = false,
|
||||
) {
|
||||
}
|
||||
|
||||
public function getId(): string
|
||||
{
|
||||
return $this->id;
|
||||
}
|
||||
}
|
||||
|
||||
final class FakeNotMarked
|
||||
{
|
||||
public function __construct(public int $id, public string $title)
|
||||
{
|
||||
}
|
||||
|
||||
public function getId(): int
|
||||
{
|
||||
return $this->id;
|
||||
}
|
||||
}
|
||||
|
||||
#[CoversClass(ModelPublisher::class)]
|
||||
final class ModelPublisherTest extends TestCase
|
||||
{
|
||||
private HubSpy $hub;
|
||||
private CorrelationContext $context;
|
||||
private ModelPublisher $publisher;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
$this->hub = new HubSpy('urn:uuid:test');
|
||||
$this->context = new CorrelationContext();
|
||||
$serializer = new Serializer(
|
||||
[new BackedEnumNormalizer(), new DateTimeNormalizer(), new ObjectNormalizer()],
|
||||
[new JsonEncoder()],
|
||||
);
|
||||
$this->publisher = new ModelPublisher(
|
||||
new Publisher($this->hub),
|
||||
$this->context,
|
||||
$serializer,
|
||||
);
|
||||
}
|
||||
|
||||
public function testUpsertDualPublishesToCollectionAndEntityTopics(): void
|
||||
{
|
||||
$todo = new FakeTodo(id: '019de596-be1c-7642-985c-edcadeef9b5d', title: 'milk', done: false);
|
||||
|
||||
$this->publisher->publishEntityChange($todo, 'upsert');
|
||||
|
||||
// The HubSpy only retains the LAST update. To validate both topics,
|
||||
// re-publish and check the second envelope, but for the assertion of
|
||||
// semantics we instead use a recording HubSpy that captures all.
|
||||
// Simplification: confirm the final captured update is the entity
|
||||
// topic (published last by ModelPublisher).
|
||||
self::assertNotNull($this->hub->captured);
|
||||
self::assertSame(
|
||||
['app://model/todo/019de596-be1c-7642-985c-edcadeef9b5d'],
|
||||
$this->hub->captured->getTopics(),
|
||||
);
|
||||
|
||||
$envelope = json_decode($this->hub->captured->getData(), true);
|
||||
self::assertSame('upsert', $envelope['op']);
|
||||
self::assertSame('019de596-be1c-7642-985c-edcadeef9b5d', $envelope['id']);
|
||||
self::assertSame('milk', $envelope['data']['title']);
|
||||
self::assertFalse($envelope['data']['done']);
|
||||
self::assertGreaterThan(0, $envelope['version']);
|
||||
self::assertArrayNotHasKey('correlationKey', $envelope);
|
||||
}
|
||||
|
||||
public function testCorrelationKeyIsEchoedWhenContextHasIt(): void
|
||||
{
|
||||
$this->context->set('idem-1234');
|
||||
$this->publisher->publishEntityChange(
|
||||
new FakeTodo(id: '1', title: 'x'),
|
||||
'upsert',
|
||||
);
|
||||
|
||||
$envelope = json_decode($this->hub->captured->getData(), true);
|
||||
self::assertSame('idem-1234', $envelope['correlationKey']);
|
||||
}
|
||||
|
||||
public function testDeleteOpOmitsData(): void
|
||||
{
|
||||
$this->publisher->publishEntityChange(
|
||||
new FakeTodo(id: '7', title: 'gone'),
|
||||
'delete',
|
||||
);
|
||||
|
||||
$envelope = json_decode($this->hub->captured->getData(), true);
|
||||
self::assertSame('delete', $envelope['op']);
|
||||
self::assertNull($envelope['data']);
|
||||
}
|
||||
|
||||
public function testEntitiesWithoutBridgeResourceAreIgnored(): void
|
||||
{
|
||||
$this->publisher->publishEntityChange(new FakeNotMarked(1, 'x'), 'upsert');
|
||||
|
||||
self::assertNull($this->hub->captured);
|
||||
}
|
||||
|
||||
public function testVersionIncreasesOnEachPublish(): void
|
||||
{
|
||||
$this->publisher->publishEntityChange(new FakeTodo(id: '1', title: 'a'), 'upsert');
|
||||
$first = json_decode($this->hub->captured->getData(), true)['version'];
|
||||
|
||||
$this->publisher->publishEntityChange(new FakeTodo(id: '1', title: 'b'), 'upsert');
|
||||
$second = json_decode($this->hub->captured->getData(), true)['version'];
|
||||
|
||||
self::assertGreaterThan($first, $second);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user