| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778 |
- <?php
- declare(strict_types=1);
- namespace App\Service;
- use ApiPlatform\Metadata\IriConverterInterface;
- use Symfony\Component\Mercure\HubInterface;
- use Symfony\Component\Mercure\Update;
- use Symfony\Component\Serializer\Encoder\EncoderInterface;
- use Symfony\Component\Serializer\SerializerInterface;
- /**
- * Sends private and encrypted mercure updates to the target users.
- *
- * Updates inform of modifications on entities: updates, creations, deletions.
- *
- * The update topic is the id of the recipient user.
- * The content is a JSON containing the iri of the entity, the operation type, and the current data of this entity
- */
- class MercureHub
- {
- public const UPDATE = 'update';
- public const CREATE = 'create';
- public const DELETE = 'delete';
- public function __construct(
- private HubInterface $hub,
- private SerializerInterface $serializer,
- private EncoderInterface $encoder,
- private IriConverterInterface $iriConverter,
- ) {
- }
- protected function createUpdate(int $accessId, string $data): Update
- {
- return new Update(
- "access/{$accessId}",
- $data,
- true
- );
- }
- /**
- * Send an update to the client.
- */
- public function publish(int $accessId, mixed $entity, string $operationType = self::UPDATE): void
- {
- if (!in_array($operationType, [self::UPDATE, self::CREATE, self::DELETE], true)) {
- throw new \InvalidArgumentException('Invalid operation type');
- }
- $data = $this->encoder->encode([
- 'iri' => $this->iriConverter->getIriFromResource($entity),
- 'operation' => $operationType,
- 'data' => $this->serializer->serialize($entity, 'jsonld'),
- ], 'jsonld');
- $this->hub->publish(
- $this->createUpdate($accessId, $data)
- );
- }
- public function publishUpdate(int $accessId, mixed $entity): void
- {
- $this->publish($accessId, $entity, self::UPDATE);
- }
- public function publishCreate(int $accessId, mixed $entity): void
- {
- $this->publish($accessId, $entity, self::CREATE);
- }
- public function publishDelete(int $accessId, mixed $entity): void
- {
- $this->publish($accessId, $entity, self::DELETE);
- }
- }
|