MercureHub.php 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\Service;
  4. use ApiPlatform\Api\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. protected function createUpdate(int $accessId, string $data): Update
  29. {
  30. return new Update(
  31. "access/{$accessId}",
  32. $data,
  33. true
  34. );
  35. }
  36. /**
  37. * Send an update to the
  38. *
  39. * @param mixed $entity
  40. * @param int $accessId
  41. * @param string $operationType
  42. */
  43. public function publish(int $accessId, mixed $entity, string $operationType = self::UPDATE): void
  44. {
  45. if (!in_array($operationType, [self::UPDATE, self::CREATE, self::DELETE], true)) {
  46. throw new \InvalidArgumentException('Invalid operation type');
  47. }
  48. $data = $this->encoder->encode([
  49. 'iri' => $this->iriConverter->getIriFromResource($entity),
  50. 'operation' => $operationType,
  51. 'data' => $this->serializer->serialize($entity, 'jsonld')
  52. ], 'jsonld');
  53. $this->hub->publish(
  54. $this->createUpdate($accessId, $data)
  55. );
  56. }
  57. /**
  58. * @param mixed $entity
  59. * @param int $accessId
  60. */
  61. public function publishUpdate(int $accessId, mixed $entity): void {
  62. $this->publish($accessId, $entity, self::UPDATE);
  63. }
  64. /**
  65. * @param mixed $entity
  66. * @param int $accessId
  67. */
  68. public function publishCreate(int $accessId, mixed $entity): void {
  69. $this->publish($accessId, $entity, self::CREATE);
  70. }
  71. /**
  72. * @param mixed $entity
  73. * @param int $accessId
  74. */
  75. public function publishDelete(int $accessId, mixed $entity): void {
  76. $this->publish($accessId, $entity, self::DELETE);
  77. }
  78. }