Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Turbo] Fix broadcast with composite primary key #1857

Open
wants to merge 10 commits into
base: 2.x
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion src/Turbo/CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ Start a Mercure Hub:
-e MERCURE_PUBLISHER_JWT_KEY='!ChangeMe!' \
-e MERCURE_SUBSCRIBER_JWT_KEY='!ChangeMe!' \
-p 3000:3000 \
dunglas/mercure caddy run -config /etc/caddy/Caddyfile.dev
dunglas/mercure caddy run --config /etc/caddy/Caddyfile.dev

Install the test app:

Expand All @@ -29,6 +29,7 @@ Start the test app:
- `http://localhost:8000/authors`: broadcast
- `http://localhost:8000/artists`: broadcast
- `http://localhost:8000/songs`: broadcast
- `http://localhost:8000/cart_products`: broadcast

## Run tests

Expand Down
21 changes: 20 additions & 1 deletion src/Turbo/config/services.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,12 @@

use Symfony\UX\Turbo\Broadcaster\BroadcasterInterface;
use Symfony\UX\Turbo\Broadcaster\IdAccessor;
use Symfony\UX\Turbo\Broadcaster\IdFormatter;
use Symfony\UX\Turbo\Broadcaster\ImuxBroadcaster;
use Symfony\UX\Turbo\Broadcaster\TwigBroadcaster;
use Symfony\UX\Turbo\Doctrine\BroadcastListener;
use Symfony\UX\Turbo\Doctrine\DoctrineClassResolver;
use Symfony\UX\Turbo\Doctrine\DoctrineIdAccessor;
use Symfony\UX\Turbo\Twig\TwigExtension;

/*
Expand All @@ -29,10 +32,22 @@

->alias(BroadcasterInterface::class, 'turbo.broadcaster.imux')

->set('turbo.doctrine_class_resolver', DoctrineClassResolver::class)
->args([
service('doctrine')->nullOnInvalid(),
])

->set('turbo.id_formatter', IdFormatter::class)

->set('turbo.doctrine_id_accessor', DoctrineIdAccessor::class)
->args([
service('doctrine')->nullOnInvalid(),
])

->set('turbo.id_accessor', IdAccessor::class)
->args([
service('property_accessor')->nullOnInvalid(),
service('doctrine')->nullOnInvalid(),
service('turbo.doctrine_id_accessor'),
])

->set('turbo.broadcaster.action_renderer', TwigBroadcaster::class)
Expand All @@ -41,6 +56,8 @@
service('twig'),
abstract_arg('entity template prefixes'),
service('turbo.id_accessor'),
service('turbo.id_formatter'),
service('turbo.doctrine_class_resolver'),
])
->decorate('turbo.broadcaster.imux')

Expand All @@ -52,6 +69,8 @@
->args([
service('turbo.broadcaster.imux'),
service('annotation_reader')->nullOnInvalid(),
service('turbo.doctrine_id_accessor'),
service('turbo.doctrine_class_resolver'),
])
->tag('doctrine.event_listener', ['event' => 'onFlush'])
->tag('doctrine.event_listener', ['event' => 'postFlush'])
Expand Down
15 changes: 11 additions & 4 deletions src/Turbo/src/Bridge/Mercure/Broadcaster.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,8 @@
use Symfony\Component\Mercure\HubInterface;
use Symfony\Component\Mercure\Update;
use Symfony\UX\Turbo\Broadcaster\BroadcasterInterface;
use Symfony\UX\Turbo\Doctrine\ClassUtil;
use Symfony\UX\Turbo\Broadcaster\IdFormatter;
use Symfony\UX\Turbo\Doctrine\DoctrineClassResolver;

/**
* Broadcasts updates rendered using Twig with Mercure.
Expand All @@ -42,14 +43,18 @@ final class Broadcaster implements BroadcasterInterface

private $name;
private $hub;
private $idFormatter;
private $doctrineClassResolver;

/** @var ExpressionLanguage|null */
private $expressionLanguage;

public function __construct(string $name, HubInterface $hub)
public function __construct(string $name, HubInterface $hub, ?IdFormatter $idFormatter = null, ?DoctrineClassResolver $doctrineClassResolver = null)
{
$this->name = $name;
$this->hub = $hub;
$this->idFormatter = $idFormatter ?? new IdFormatter();
$this->doctrineClassResolver = $doctrineClassResolver ?? new DoctrineClassResolver();

if (class_exists(ExpressionLanguage::class)) {
$this->expressionLanguage = new ExpressionLanguage();
Expand All @@ -62,7 +67,7 @@ public function broadcast(object $entity, string $action, array $options): void
return;
}

$entityClass = ClassUtil::getEntityClass($entity);
$entityClass = $this->doctrineClassResolver->resolve($entity);

if (!isset($options['rendered_action'])) {
throw new \InvalidArgumentException(sprintf('Cannot broadcast entity of class "%s" as option "rendered_action" is missing.', $entityClass));
Expand Down Expand Up @@ -99,7 +104,9 @@ public function broadcast(object $entity, string $action, array $options): void
throw new \InvalidArgumentException(sprintf('Cannot broadcast entity of class "%s": the option "topics" is empty and "id" is missing.', $entityClass));
}

$options['topics'] = (array) sprintf(self::TOPIC_PATTERN, rawurlencode($entityClass), rawurlencode(implode('-', (array) $options['id'])));
$id = $this->idFormatter->format($options['id']);

$options['topics'] = (array) sprintf(self::TOPIC_PATTERN, rawurlencode($entityClass), rawurlencode($id));
}

$update = new Update(
Expand Down
14 changes: 11 additions & 3 deletions src/Turbo/src/Bridge/Mercure/TurboStreamListenRenderer.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@
use Symfony\Component\Mercure\HubInterface;
use Symfony\UX\StimulusBundle\Helper\StimulusHelper;
use Symfony\UX\Turbo\Broadcaster\IdAccessor;
use Symfony\UX\Turbo\Broadcaster\IdFormatter;
use Symfony\UX\Turbo\Doctrine\DoctrineClassResolver;
use Symfony\UX\Turbo\Twig\TurboStreamListenRendererInterface;
use Symfony\WebpackEncoreBundle\Twig\StimulusTwigExtension;
use Twig\Environment;
Expand All @@ -28,14 +30,18 @@ final class TurboStreamListenRenderer implements TurboStreamListenRendererInterf
private HubInterface $hub;
private StimulusHelper $stimulusHelper;
private IdAccessor $idAccessor;
private IdFormatter $idFormatter;
private DoctrineClassResolver $doctrineClassResolver;

/**
* @param $stimulus StimulusHelper
*/
public function __construct(HubInterface $hub, StimulusHelper|StimulusTwigExtension $stimulus, IdAccessor $idAccessor)
public function __construct(HubInterface $hub, StimulusHelper|StimulusTwigExtension $stimulus, IdAccessor $idAccessor, ?IdFormatter $idFormatter = null, ?DoctrineClassResolver $doctrineClassResolver = null)
{
$this->hub = $hub;
$this->idAccessor = $idAccessor;
$this->idFormatter = $idFormatter ?? new IdFormatter();
$this->doctrineClassResolver = $doctrineClassResolver ?? new DoctrineClassResolver();

if ($stimulus instanceof StimulusTwigExtension) {
trigger_deprecation('symfony/ux-turbo', '2.9', 'Passing an instance of "%s" as second argument of "%s" is deprecated, pass an instance of "%s" instead.', StimulusTwigExtension::class, __CLASS__, StimulusHelper::class);
Expand All @@ -49,13 +55,15 @@ public function __construct(HubInterface $hub, StimulusHelper|StimulusTwigExtens
public function renderTurboStreamListen(Environment $env, $topic): string
{
if (\is_object($topic)) {
$class = $topic::class;
$class = $this->doctrineClassResolver->resolve($topic);

if (!$id = $this->idAccessor->getEntityId($topic)) {
throw new \LogicException(sprintf('Cannot listen to entity of class "%s" as the PropertyAccess component is not installed. Try running "composer require symfony/property-access".', $class));
}

$topic = sprintf(Broadcaster::TOPIC_PATTERN, rawurlencode($class), rawurlencode(implode('-', $id)));
$formattedId = $this->idFormatter->format($id);

$topic = sprintf(Broadcaster::TOPIC_PATTERN, rawurlencode($class), rawurlencode($formattedId));
} elseif (!preg_match('/[^a-zA-Z0-9_\x7f-\xff\\\\]/', $topic) && class_exists($topic)) {
// Generate a URI template to subscribe to updates for all objects of this class
$topic = sprintf(Broadcaster::TOPIC_PATTERN, rawurlencode($topic), '{id}');
Expand Down
2 changes: 1 addition & 1 deletion src/Turbo/src/Broadcaster/BroadcasterInterface.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
interface BroadcasterInterface
{
/**
* @param array{id?: string|string[], transports?: string|string[], topics?: string|string[], template?: string, rendered_action?: string, private?: bool, sse_id?: string, sse_type?: string, sse_retry?: int} $options
* @param array{id?: array<string, string>|array<string, array<string, string>>, transports?: string|string[], topics?: string|string[], template?: string, rendered_action?: string, private?: bool, sse_id?: string, sse_type?: string, sse_retry?: int} $options
*/
public function broadcast(object $entity, string $action, array $options): void;
}
16 changes: 7 additions & 9 deletions src/Turbo/src/Broadcaster/IdAccessor.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,30 +11,28 @@

namespace Symfony\UX\Turbo\Broadcaster;

use Doctrine\Persistence\ManagerRegistry;
use Symfony\Component\PropertyAccess\PropertyAccess;
use Symfony\Component\PropertyAccess\PropertyAccessorInterface;
use Symfony\UX\Turbo\Doctrine\DoctrineIdAccessor;

class IdAccessor
{
private $propertyAccessor;
private $doctrine;
private $doctrineIdAccessor;

public function __construct(?PropertyAccessorInterface $propertyAccessor = null, ?ManagerRegistry $doctrine = null)
public function __construct(?PropertyAccessorInterface $propertyAccessor = null, ?DoctrineIdAccessor $doctrineIdAccessor = null)
{
$this->propertyAccessor = $propertyAccessor ?? (class_exists(PropertyAccess::class) ? PropertyAccess::createPropertyAccessor() : null);
$this->doctrine = $doctrine;
$this->doctrineIdAccessor = $doctrineIdAccessor ?? new DoctrineIdAccessor();
}

/**
* @return string[]
* @return array<string, array<string, string>>|array<string, string>|null
*/
public function getEntityId(object $entity): ?array
{
$entityClass = $entity::class;

if ($this->doctrine && $em = $this->doctrine->getManagerForClass($entityClass)) {
return $em->getClassMetadata($entityClass)->getIdentifierValues($entity);
if (null !== ($id = $this->doctrineIdAccessor->getEntityId($entity))) {
return $id;
}

if ($this->propertyAccessor) {
Expand Down
41 changes: 41 additions & 0 deletions src/Turbo/src/Broadcaster/IdFormatter.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\UX\Turbo\Broadcaster;

/**
* Formats an id array to a string.
*
* In defaults the id array is something like `['id' => 1]` or `['uuid' => '00000000-0000-0000-0000-000000000000']`.
* For a composite key it could be something like `['cart' => ['id' => 1], 'product' => ['id' => 1]]`.
*
* To create a string representation of the id, the values of the array are flattened and concatenated with a dash.
*
* @author Jason Schilling <jason@sourecode.dev>
*/
class IdFormatter
{
/**
* @param array<string, array<string, string>>|array<string, string>|string $id
*/
public function format(array|string $id): string
{
if (\is_string($id)) {
return $id;
}

$flatten = [];

array_walk_recursive($id, static function ($item) use (&$flatten) { $flatten[] = $item; });

return implode('-', $flatten);
}
}
15 changes: 9 additions & 6 deletions src/Turbo/src/Broadcaster/TwigBroadcaster.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@

namespace Symfony\UX\Turbo\Broadcaster;

use Symfony\UX\Turbo\Doctrine\ClassUtil;
use Symfony\UX\Turbo\Doctrine\DoctrineClassResolver;
use Twig\Environment;

/**
Expand All @@ -25,16 +25,20 @@ final class TwigBroadcaster implements BroadcasterInterface
private $twig;
private $templatePrefixes;
private $idAccessor;
private $idFormatter;
private $doctrineClassResolver;

/**
* @param array<string, string> $templatePrefixes
*/
public function __construct(BroadcasterInterface $broadcaster, Environment $twig, array $templatePrefixes = [], ?IdAccessor $idAccessor = null)
public function __construct(BroadcasterInterface $broadcaster, Environment $twig, array $templatePrefixes = [], ?IdAccessor $idAccessor = null, ?IdFormatter $idFormatter = null, ?DoctrineClassResolver $doctrineClassResolver = null)
{
$this->broadcaster = $broadcaster;
$this->twig = $twig;
$this->templatePrefixes = $templatePrefixes;
$this->idAccessor = $idAccessor ?? new IdAccessor();
$this->idFormatter = $idFormatter ?? new IdFormatter();
$this->doctrineClassResolver = $doctrineClassResolver ?? new DoctrineClassResolver();
}

public function broadcast(object $entity, string $action, array $options): void
Expand All @@ -43,10 +47,9 @@ public function broadcast(object $entity, string $action, array $options): void
$options['id'] = $id;
}

$class = ClassUtil::getEntityClass($entity);

if (null === $template = $options['template'] ?? null) {
$template = $class;
$template = $this->doctrineClassResolver->resolve($entity);

foreach ($this->templatePrefixes as $namespace => $prefix) {
if (str_starts_with($template, $namespace)) {
$template = substr_replace($template, $prefix, 0, \strlen($namespace));
Expand All @@ -63,7 +66,7 @@ public function broadcast(object $entity, string $action, array $options): void
->renderBlock($action, [
'entity' => $entity,
'action' => $action,
'id' => implode('-', (array) ($options['id'] ?? [])),
'id' => $this->idFormatter->format($options['id'] ?? []),
] + $options);

$this->broadcaster->broadcast($entity, $action, $options);
Expand Down
24 changes: 14 additions & 10 deletions src/Turbo/src/Doctrine/BroadcastListener.php
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,8 @@ final class BroadcastListener implements ResetInterface
{
private $broadcaster;
private $annotationReader;
private $doctrineIdAccessor;
private $doctrineClassResolver;

/**
* @var array<class-string, array<mixed>>
Expand All @@ -48,12 +50,14 @@ final class BroadcastListener implements ResetInterface
*/
private $removedEntities;

public function __construct(BroadcasterInterface $broadcaster, ?Reader $annotationReader = null)
public function __construct(BroadcasterInterface $broadcaster, ?Reader $annotationReader = null, ?DoctrineIdAccessor $doctrineIdAccessor = null, ?DoctrineClassResolver $doctrineClassResolver = null)
{
$this->reset();

$this->broadcaster = $broadcaster;
$this->annotationReader = $annotationReader;
$this->doctrineIdAccessor = $doctrineIdAccessor ?? new DoctrineIdAccessor();
$this->doctrineClassResolver = $doctrineClassResolver ?? new DoctrineClassResolver();
}

/**
Expand Down Expand Up @@ -94,7 +98,7 @@ public function postFlush(EventArgs $eventArgs): void
try {
foreach ($this->createdEntities as $entity) {
$options = $this->createdEntities[$entity];
$id = $em->getClassMetadata($entity::class)->getIdentifierValues($entity);
$id = $this->doctrineIdAccessor->getEntityId($entity, $em);
foreach ($options as $option) {
$option['id'] = $id;
$this->broadcaster->broadcast($entity, Broadcast::ACTION_CREATE, $option);
Expand Down Expand Up @@ -126,28 +130,28 @@ public function reset(): void

private function storeEntitiesToPublish(EntityManagerInterface $em, object $entity, string $property): void
{
$class = ClassUtil::getEntityClass($entity);
$entityClass = $this->doctrineClassResolver->resolve($entity, $em);

if (!isset($this->broadcastedClasses[$class])) {
$this->broadcastedClasses[$class] = [];
$r = new \ReflectionClass($class);
if (!isset($this->broadcastedClasses[$entityClass])) {
$this->broadcastedClasses[$entityClass] = [];
$r = new \ReflectionClass($entityClass);
Comment on lines +135 to +137
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not sure this is worth the change.


if ($options = $r->getAttributes(Broadcast::class)) {
foreach ($options as $option) {
$this->broadcastedClasses[$class][] = $option->newInstance()->options;
$this->broadcastedClasses[$entityClass][] = $option->newInstance()->options;
}
} elseif ($this->annotationReader && $options = $this->annotationReader->getClassAnnotations($r)) {
foreach ($options as $option) {
if ($option instanceof Broadcast) {
$this->broadcastedClasses[$class][] = $option->options;
$this->broadcastedClasses[$entityClass][] = $option->options;
}
}
}
}

if ($options = $this->broadcastedClasses[$class]) {
if ($options = $this->broadcastedClasses[$entityClass]) {
if ('createdEntities' !== $property) {
$id = $em->getClassMetadata($class)->getIdentifierValues($entity);
$id = $this->doctrineIdAccessor->getEntityId($entity, $em);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could you illustrate precisely what cannot be done before, what it would look like, and same after your changes ? :)

foreach ($options as $k => $option) {
$options[$k]['id'] = $id;
}
Expand Down
Loading
Loading