Skip to content

Instantly share code, notes, and snippets.

@MarcDiaz
Created January 13, 2022 18:39
Show Gist options
  • Save MarcDiaz/15c613a5217fd764261b6338008c0833 to your computer and use it in GitHub Desktop.
Save MarcDiaz/15c613a5217fd764261b6338008c0833 to your computer and use it in GitHub Desktop.
Listener to publish a Soft Delete with Mercure on API Platform project
<?php
namespace App\Doctrine\Mercure\EventListener;
use ApiPlatform\Core\Api\IriConverterInterface;
use ApiPlatform\Core\Api\UrlGeneratorInterface;
use Doctrine\Persistence\Event\LifecycleEventArgs;
use Symfony\Component\Mercure\HubInterface;
use Symfony\Component\Mercure\Update;
/**
* Entity Listener for catching Soft Delete and publishing it on Mercure hub
*/
final class PublishMercureSoftDeletesListener
{
private IriConverterInterface $iriConverter;
private HubInterface $hub;
public function __construct(IriConverterInterface $iriConverter, HubInterface $hub)
{
$this->iriConverter = $iriConverter;
$this->hub = $hub;
}
public function postSoftDelete(LifecycleEventArgs $args): void
{
$softDeletedObject = $args->getObject();
// Put your Mercure options here or try to retrieve them from the ApiResource annotation
$mercureOptions = [...];
if (!$mercureOptions) {
return;
}
$defaultTopic = $this->iriConverter->getIriFromItem($softDeletedObject, UrlGeneratorInterface::ABS_URL);
$softDeletedInfo = ['@id' => $this->iriConverter->getIriFromItem($softDeletedObject)];
$update = new Update(
$mercureOptions['topics'] ?? $defaultTopic,
json_encode($softDeletedInfo),
$mercureOptions['private'] ?? false,
$mercureOptions['id'] ?? null,
$mercureOptions['type'] ?? null,
$mercureOptions['retry'] ?? null
);
$this->hub->publish($update);
}
}
services:
App\Doctrine\Mercure\EventListener\PublishMercureSoftDeletesListener:
tags:
- { name: doctrine.event_listener, event: postSoftDelete }
@MarcDiaz
Copy link
Author

This Gist works with API Platform, Mercure and the StofDoctrineExtensionsBundle.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment