Skip to content
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
33 changes: 33 additions & 0 deletions features/mercure/publish.feature
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
Feature: Mercure publish support
In order to publish an Update to the Mercure hub
As a developer
I need to specify which topics I want to send the Update on

@createSchema
# see https://github.com/api-platform/core/issues/5074
Scenario: Checks that Mercure Updates are dispatched properly
Given I add "Accept" header equal to "application/ld+json"
And I add "Content-Type" header equal to "application/ld+json"
When I send a "POST" request to "/issue5074/mercure_with_topics" with body:
"""
{
"name": "Hello World!",
"description": "Lorem ipsum dolor sit amet, consectetur adipiscing elit."
}
"""
Then the response status code should be 201
And the response should be in JSON
And the header "Content-Type" should be equal to "application/ld+json; charset=utf-8"
Then 1 Mercure update should have been sent
And the Mercure update should have topics:
| http://example.com/issue5074/mercure_with_topics/1 |
And the Mercure update should have data:
"""
{
"@context": "/contexts/MercureWithTopics",
"@id": "/issue5074/mercure_with_topics/1",
"@type": "MercureWithTopics",
"id": 1,
"name": "Hello World!"
}
"""
57 changes: 34 additions & 23 deletions src/Doctrine/EventListener/PublishMercureUpdatesListener.php
Original file line number Diff line number Diff line change
Expand Up @@ -190,35 +190,15 @@ private function storeObjectToPublish(object $object, string $property): void

$options['enable_async_update'] ??= true;

if ($options['topics'] ?? false) {
$topics = [];
foreach ((array) $options['topics'] as $topic) {
if (!\is_string($topic)) {
$topics[] = $topic;
continue;
}

if (!str_starts_with($topic, '@=')) {
$topics[] = $topic;
continue;
}

if (null === $this->expressionLanguage) {
throw new \LogicException('The "@=" expression syntax cannot be used without the Expression Language component. Try running "composer require symfony/expression-language".');
}

$topics[] = $this->expressionLanguage->evaluate(substr($topic, 2), ['object' => $object]);
}

$options['topics'] = $topics;
}

if ('deletedObjects' === $property) {
$types = $operation instanceof HttpOperation ? $operation->getTypes() : null;
if (null === $types) {
$types = [$operation->getShortName()];
}

// We need to evaluate it here, because in publishUpdate() the resource would be already deleted
$this->evaluateTopics($options, $object);

$this->deletedObjects[(object) [
'id' => $this->iriConverter->getIriFromResource($object),
'iri' => $this->iriConverter->getIriFromResource($object, UrlGeneratorInterface::ABS_URL),
Expand All @@ -244,6 +224,9 @@ private function publishUpdate(object $object, array $options, string $type): vo
$resourceClass = $this->getObjectClass($object);
$context = $options['normalization_context'] ?? $this->resourceMetadataFactory->create($resourceClass)->getOperation()->getNormalizationContext() ?? [];

// We need to evaluate it here, because in storeObjectToPublish() the resource would not have been persisted yet
$this->evaluateTopics($options, $object);

$iri = $options['topics'] ?? $this->iriConverter->getIriFromResource($object, UrlGeneratorInterface::ABS_URL);
$data = $options['data'] ?? $this->serializer->serialize($object, key($this->formats), $context);
}
Expand All @@ -260,6 +243,34 @@ private function publishUpdate(object $object, array $options, string $type): vo
}
}

private function evaluateTopics(array &$options, object $object): void
{
if (!($options['topics'] ?? false)) {
return;
}

$topics = [];
foreach ((array) $options['topics'] as $topic) {
if (!\is_string($topic)) {
$topics[] = $topic;
continue;
}

if (!str_starts_with($topic, '@=')) {
$topics[] = $topic;
continue;
}

if (null === $this->expressionLanguage) {
throw new \LogicException('The "@=" expression syntax cannot be used without the Expression Language component. Try running "composer require symfony/expression-language".');
}

$topics[] = $this->expressionLanguage->evaluate(substr($topic, 2), ['object' => $object]);
}

$options['topics'] = $topics;
}

/**
* @return Update[]
*/
Expand Down
77 changes: 77 additions & 0 deletions tests/Behat/MercureContext.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,10 @@

use Behat\Behat\Context\Context;
use Behat\Gherkin\Node\PyStringNode;
use Behat\Gherkin\Node\TableNode;
use PHPUnit\Framework\Assert;
use Psr\Container\ContainerInterface;
use Symfony\Component\Mercure\Update;

/**
* Context for Mercure.
Expand All @@ -28,6 +31,80 @@ public function __construct(private readonly ContainerInterface $driverContainer
{
}

/**
* @Then :number Mercure updates should have been sent
* @Then :number Mercure update should have been sent
*/
public function mercureUpdatesShouldHaveBeenSent(int $number): void
{
$updateHandler = $this->driverContainer->get('mercure.hub.default.message_handler');
$total = \count($updateHandler->getUpdates());

if (0 === $total) {
throw new \RuntimeException('No Mercure update has been sent.');
}

Assert::assertEquals($number, $total, sprintf('Expected %d Mercure updates to be sent, got %d.', $number, $total));
}

/**
* @Then the first Mercure update should have topics:
* @Then the Mercure update should have topics:
*/
public function firstMercureUpdateShouldHaveTopics(TableNode $table): void
{
$this->mercureUpdateShouldHaveTopics(1, $table);
}

/**
* @Then the first Mercure update should have data:
* @Then the Mercure update should have data:
*/
public function firstMercureUpdateShouldHaveData(PyStringNode $data): void
{
$this->mercureUpdateShouldHaveData(1, $data);
}

/**
* @Then the Mercure update number :index should have topics:
*/
public function mercureUpdateShouldHaveTopics(int $index, TableNode $table): void
{
$updateHandler = $this->driverContainer->get('mercure.hub.default.message_handler');
$updates = $updateHandler->getUpdates();

if (0 === \count($updates)) {
throw new \RuntimeException('No Mercure update has been sent.');
}

if (!isset($updates[$index - 1])) {
throw new \RuntimeException(sprintf('Mercure update #%d does not exist.', $index));
}
/** @var Update $update */
$update = $updates[$index - 1];
Assert::assertEquals(array_keys($table->getRowsHash()), array_values($update->getTopics()));
}

/**
* @Then the Mercure update number :index should have data:
*/
public function mercureUpdateShouldHaveData(int $index, PyStringNode $data): void
{
$updateHandler = $this->driverContainer->get('mercure.hub.default.message_handler');
$updates = $updateHandler->getUpdates();

if (0 === \count($updates)) {
throw new \RuntimeException('No Mercure update has been sent.');
}

if (!isset($updates[$index - 1])) {
throw new \RuntimeException(sprintf('Mercure update #%d does not exist.', $index));
}
/** @var Update $update */
$update = $updates[$index - 1];
Assert::assertJsonStringEqualsJsonString($data->getRaw(), $update->getData());
}

/**
* @Then the following Mercure update with topics :topics should have been sent:
*/
Expand Down
36 changes: 36 additions & 0 deletions tests/Fixtures/TestBundle/Document/Issue5074/MercureWithTopics.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
<?php

/*
* This file is part of the API Platform project.
*
* (c) Kévin Dunglas <dunglas@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

declare(strict_types=1);

namespace ApiPlatform\Tests\Fixtures\TestBundle\Document\Issue5074;

use ApiPlatform\Metadata\ApiResource;
use ApiPlatform\Metadata\Get;
use ApiPlatform\Metadata\Post;
use Doctrine\ODM\MongoDB\Mapping\Annotations as ODM;

#[ApiResource(
operations: [
new Get(uriTemplate: '/issue5074/mercure_with_topics/{id}{._format}'),
new Post(uriTemplate: '/issue5074/mercure_with_topics{._format}'),
],
mercure: ['topics' => '@=iri(object)'],
extraProperties: ['standard_put' => false]
)]
#[ODM\Document]
class MercureWithTopics
{
#[ODM\Id(strategy: 'INCREMENT', type: 'int')]
public $id;
#[ODM\Field(type: 'string')]
public $name;
}
38 changes: 38 additions & 0 deletions tests/Fixtures/TestBundle/Entity/Issue5074/MercureWithTopics.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
<?php

/*
* This file is part of the API Platform project.
*
* (c) Kévin Dunglas <dunglas@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

declare(strict_types=1);

namespace ApiPlatform\Tests\Fixtures\TestBundle\Entity\Issue5074;

use ApiPlatform\Metadata\ApiResource;
use ApiPlatform\Metadata\Get;
use ApiPlatform\Metadata\Post;
use Doctrine\ORM\Mapping as ORM;

#[ApiResource(
operations: [
new Get(uriTemplate: '/issue5074/mercure_with_topics/{id}{._format}'),
new Post(uriTemplate: '/issue5074/mercure_with_topics{._format}'),
],
mercure: ['topics' => '@=iri(object)'],
extraProperties: ['standard_put' => false]
)]
#[ORM\Entity]
class MercureWithTopics
{
#[ORM\Id]
#[ORM\Column(type: 'integer')]
#[ORM\GeneratedValue(strategy: 'AUTO')]
public $id;
#[ORM\Column]
public $name;
}