Skip to content

[Turbo] Fixing a bug where saving a proxy would not trigger Broadcasts #951

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

Merged
merged 1 commit into from
Jun 16, 2023
Merged
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
11 changes: 10 additions & 1 deletion src/Turbo/src/Bridge/Mercure/Broadcaster.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,11 @@

namespace Symfony\UX\Turbo\Bridge\Mercure;

use Doctrine\Common\Util\ClassUtils;
use Symfony\Component\ExpressionLanguage\ExpressionLanguage;
use Symfony\Component\Mercure\HubInterface;
use Symfony\Component\Mercure\Update;
use Symfony\Component\VarExporter\LazyObjectInterface;
use Symfony\UX\Turbo\Broadcaster\BroadcasterInterface;

/**
Expand Down Expand Up @@ -61,7 +63,14 @@ public function broadcast(object $entity, string $action, array $options): void
return;
}

$entityClass = $entity::class;
if ($entity instanceof LazyObjectInterface) {
$entityClass = get_parent_class($entity);
if (false === $entityClass) {
throw new \LogicException('Parent class missing');
}
} else {
$entityClass = ClassUtils::getClass($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
14 changes: 13 additions & 1 deletion src/Turbo/src/Broadcaster/TwigBroadcaster.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@

namespace Symfony\UX\Turbo\Broadcaster;

use Doctrine\Common\Util\ClassUtils;
use Symfony\Component\VarExporter\LazyObjectInterface;
use Twig\Environment;

/**
Expand Down Expand Up @@ -42,8 +44,18 @@ public function broadcast(object $entity, string $action, array $options): void
$options['id'] = $id;
}

// handle proxies (both styles)
if ($entity instanceof LazyObjectInterface) {
$class = get_parent_class($entity);
if (false === $class) {
throw new \LogicException('Parent class missing');
}
} else {
$class = ClassUtils::getClass($entity);
}

if (null === $template = $options['template'] ?? null) {
$template = $entity::class;
$template = $class;
foreach ($this->templatePrefixes as $namespace => $prefix) {
if (str_starts_with($template, $namespace)) {
$template = substr_replace($template, $prefix, 0, \strlen($namespace));
Expand Down
12 changes: 11 additions & 1 deletion src/Turbo/src/Doctrine/BroadcastListener.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,11 @@

use Doctrine\Common\Annotations\Reader;
use Doctrine\Common\EventArgs;
use Doctrine\Common\Util\ClassUtils;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\Event\OnFlushEventArgs;
use Doctrine\ORM\Event\PostFlushEventArgs;
use Symfony\Component\VarExporter\LazyObjectInterface;
use Symfony\Contracts\Service\ResetInterface;
use Symfony\UX\Turbo\Attribute\Broadcast;
use Symfony\UX\Turbo\Broadcaster\BroadcasterInterface;
Expand Down Expand Up @@ -126,7 +128,15 @@ public function reset(): void

private function storeEntitiesToPublish(EntityManagerInterface $em, object $entity, string $property): void
{
$class = $entity::class;
// handle proxies (both styles)
if ($entity instanceof LazyObjectInterface) {
$class = get_parent_class($entity);
if (false === $class) {
throw new \LogicException('Parent class missing');
}
} else {
$class = ClassUtils::getClass($entity);
}

if (!isset($this->broadcastedClasses[$class])) {
$this->broadcastedClasses[$class] = [];
Expand Down
18 changes: 17 additions & 1 deletion src/Turbo/tests/BroadcastTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ protected function setUp(): void
parent::setUp();
}

public function testBroadcast(): void
public function testBroadcastBasic(): void
{
($client = self::createPantherClient())->request('GET', '/books');

Expand Down Expand Up @@ -88,4 +88,20 @@ public function testExpressionLanguageBroadcast(): void
'Artist 2 shows a song that does not belong to them'
);
}

public function testBroadcastWithProxy(): void
{
// testing that Artist is updated, even though it's saved as Proxy
($client = self::createPantherClient())->request('GET', '/artistFromSong');

// submit first time to create the artist
$client->submitForm('Submit');
$this->assertSelectorWillContain('#artists', 'testing artist');

// submit again to update the artist
$client->submitForm('Submit');
$this->assertSelectorWillContain('#artists', 'testing artist after change');
// this part is from the stream template
$this->assertSelectorWillContain('#artists', ', updated)');
}
}
42 changes: 39 additions & 3 deletions src/Turbo/tests/app/Kernel.php
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,6 @@
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpKernel\Kernel as BaseKernel;
use Symfony\Component\Mercure\Hub;
use Symfony\Component\Mercure\HubInterface;
use Symfony\Component\Mercure\Update;
use Symfony\Component\Routing\Loader\Configurator\RoutingConfigurator;
Expand Down Expand Up @@ -117,8 +116,6 @@ protected function configureContainer(ContainerConfigurator $container): void
],
],
]);

$container->services()->alias(Hub::class, 'mercure.hub.default'); // FIXME: temporary fix for a bug in https://github.com/symfony/mercure-bundle/pull/42
}

protected function configureRoutes(RoutingConfigurator $routes): void
Expand All @@ -135,6 +132,7 @@ protected function configureRoutes(RoutingConfigurator $routes): void
$routes->add('songs', '/songs')->controller('kernel::songs');
$routes->add('artists', '/artists')->controller('kernel::artists');
$routes->add('artist', '/artists/{id}')->controller('kernel::artist');
$routes->add('artist_from_song', '/artistFromSong')->controller('kernel::artistFromSong');
}

public function getProjectDir(): string
Expand Down Expand Up @@ -265,4 +263,42 @@ public function artist(Request $request, EntityManagerInterface $doctrine, Envir

return new Response($twig->render('artist.html.twig', ['artist' => $artist]));
}

public function artistFromSong(Request $request, EntityManagerInterface $doctrine, Environment $twig): Response
{
$song = null;
if ($request->isMethod('POST')) {
// on first post, create the objects
// on second, update the artist
$id = $request->get('id');
if (!$id) {
$artist = new Artist();
$artist->name = 'testing artist';

$song = new Song();
$song->artist = $artist;
$song->title = 'testing song title';

$doctrine->persist($artist);
$doctrine->persist($song);
$doctrine->flush();
} else {
$song = $doctrine->find(Song::class, $id);
if (!$song) {
throw new NotFoundHttpException();
}
$artist = $song->artist;
if (!$artist) {
throw new NotFoundHttpException();
}
$artist->name = $artist->name.' after change';

$doctrine->flush();
}
}

return new Response($twig->render('artist_from_song.html.twig', [
'song' => $song,
]));
}
}
14 changes: 14 additions & 0 deletions src/Turbo/tests/app/templates/artist_from_song.html.twig
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
{% extends 'base.html.twig' %}

{% block body %}
<h1>Update Artist Via Song</h1>

<div id="artists" {{ turbo_stream_listen('App\\Entity\\Artist') }}></div>

<turbo-frame id="api">
<form method="post" enctype="application/x-www-form-urlencoded">
<input name="id" value="{{ song ? song.id }}">
<button>Submit</button>
</form>
</turbo-frame>
{% endblock %}