MercureHub.php 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\Service;
  4. use ApiPlatform\Metadata\IriConverterInterface;
  5. use Symfony\Component\Mercure\HubInterface;
  6. use Symfony\Component\Mercure\Update;
  7. use Symfony\Component\Serializer\Encoder\EncoderInterface;
  8. use Symfony\Component\Serializer\SerializerInterface;
  9. /**
  10. * Sends private and encrypted mercure updates to the target users.
  11. *
  12. * Updates inform of modifications on entities: updates, creations, deletions.
  13. *
  14. * The update topic is the id of the recipient user.
  15. * The content is a JSON containing the iri of the entity, the operation type, and the current data of this entity
  16. */
  17. class MercureHub
  18. {
  19. public const UPDATE = 'update';
  20. public const CREATE = 'create';
  21. public const DELETE = 'delete';
  22. public function __construct(
  23. private HubInterface $hub,
  24. private SerializerInterface $serializer,
  25. private EncoderInterface $encoder,
  26. private IriConverterInterface $iriConverter,
  27. ) {
  28. }
  29. protected function createUpdate(int $accessId, string $data): Update
  30. {
  31. return new Update(
  32. "access/{$accessId}",
  33. $data,
  34. true
  35. );
  36. }
  37. /**
  38. * Send an update to the client.
  39. */
  40. public function publish(int $accessId, mixed $entity, string $operationType = self::UPDATE): void
  41. {
  42. if (!in_array($operationType, [self::UPDATE, self::CREATE, self::DELETE], true)) {
  43. throw new \InvalidArgumentException('Invalid operation type');
  44. }
  45. $data = $this->encoder->encode([
  46. 'iri' => $this->iriConverter->getIriFromResource($entity),
  47. 'operation' => $operationType,
  48. 'data' => $this->serializer->serialize($entity, 'jsonld'),
  49. ], 'jsonld');
  50. $this->hub->publish(
  51. $this->createUpdate($accessId, $data)
  52. );
  53. }
  54. public function publishUpdate(int $accessId, mixed $entity): void
  55. {
  56. $this->publish($accessId, $entity, self::UPDATE);
  57. }
  58. public function publishCreate(int $accessId, mixed $entity): void
  59. {
  60. $this->publish($accessId, $entity, self::CREATE);
  61. }
  62. public function publishDelete(int $accessId, mixed $entity): void
  63. {
  64. $this->publish($accessId, $entity, self::DELETE);
  65. }
  66. }