MercureHub.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\Service;
  4. use ApiPlatform\Api\IriConverterInterface;
  5. use InvalidArgumentException;
  6. use Symfony\Component\Mercure\HubInterface;
  7. use Symfony\Component\Mercure\Update;
  8. use Symfony\Component\Serializer\Encoder\EncoderInterface;
  9. use Symfony\Component\Serializer\SerializerInterface;
  10. /**
  11. * Sends private and encrypted mercure updates to the target users.
  12. *
  13. * Updates inform of modifications on entities : updates, creations, deletions.
  14. *
  15. * The update topic is the id of the recipient user.
  16. * The content is a json containing the iri of the entity, the operation type, and the current data of this entity
  17. */
  18. class MercureHub
  19. {
  20. public const UPDATE = 'update';
  21. public const CREATE = 'create';
  22. public const DELETE = 'delete';
  23. public function __construct(
  24. private HubInterface $hub,
  25. private SerializerInterface $serializer,
  26. private EncoderInterface $encoder,
  27. private IriConverterInterface $iriConverter
  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
  39. *
  40. * @param mixed $entity
  41. * @param int $accessId
  42. * @param string $operationType
  43. */
  44. public function publish(int $accessId, mixed $entity, string $operationType = self::UPDATE): void
  45. {
  46. if (!in_array($operationType, [self::UPDATE, self::CREATE, self::DELETE], true)) {
  47. throw new InvalidArgumentException('Invalid operation type');
  48. }
  49. $data = $this->encoder->encode([
  50. 'iri' => $this->iriConverter->getIriFromResource($entity),
  51. 'operation' => $operationType,
  52. 'data' => $this->serializer->serialize($entity, 'jsonld')
  53. ], 'jsonld');
  54. $this->hub->publish(
  55. $this->createUpdate($accessId, $data)
  56. );
  57. }
  58. /**
  59. * @param mixed $entity
  60. * @param int $accessId
  61. */
  62. public function publishUpdate(int $accessId, mixed $entity): void {
  63. $this->publish($accessId, $entity, self::UPDATE);
  64. }
  65. /**
  66. * @param mixed $entity
  67. * @param int $accessId
  68. */
  69. public function publishCreate(int $accessId, mixed $entity): void {
  70. $this->publish($accessId, $entity, self::CREATE);
  71. }
  72. /**
  73. * @param mixed $entity
  74. * @param int $accessId
  75. */
  76. public function publishDelete(int $accessId, mixed $entity): void {
  77. $this->publish($accessId, $entity, self::DELETE);
  78. }
  79. }