Created
January 13, 2022 18:39
-
-
Save MarcDiaz/15c613a5217fd764261b6338008c0833 to your computer and use it in GitHub Desktop.
Listener to publish a Soft Delete with Mercure on API Platform project
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
services: | |
App\Doctrine\Mercure\EventListener\PublishMercureSoftDeletesListener: | |
tags: | |
- { name: doctrine.event_listener, event: postSoftDelete } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This Gist works with API Platform, Mercure and the StofDoctrineExtensionsBundle.