|
|
@@ -0,0 +1,82 @@
|
|
|
+<?php
|
|
|
+
|
|
|
+namespace App\Service;
|
|
|
+
|
|
|
+use ApiPlatform\Core\Api\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 $mercureHub,
|
|
|
+ private SerializerInterface $serializer,
|
|
|
+ private EncoderInterface $encoder,
|
|
|
+ private IriConverterInterface $iriConverter
|
|
|
+ ) {}
|
|
|
+
|
|
|
+ /**
|
|
|
+ * Send an update to the
|
|
|
+ *
|
|
|
+ * @param $entity
|
|
|
+ * @param int $accessId
|
|
|
+ * @param string $operationType
|
|
|
+ */
|
|
|
+ public function publish(int $accessId, $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->getIriFromItem($entity),
|
|
|
+ 'operation' => $operationType,
|
|
|
+ 'data' => $this->serializer->serialize($entity, 'jsonld')
|
|
|
+ ], 'jsonld');
|
|
|
+
|
|
|
+ $update = new Update(
|
|
|
+ "access/{$accessId}",
|
|
|
+ $data,
|
|
|
+ true
|
|
|
+ );
|
|
|
+ $this->mercureHub->publish($update);
|
|
|
+ }
|
|
|
+
|
|
|
+ /**
|
|
|
+ * @param $entity
|
|
|
+ * @param int $accessId
|
|
|
+ */
|
|
|
+ public function publishUpdate(int $accessId, $entity): void {
|
|
|
+ $this->publish($accessId, $entity, self::UPDATE);
|
|
|
+ }
|
|
|
+
|
|
|
+ /**
|
|
|
+ * @param $entity
|
|
|
+ * @param int $accessId
|
|
|
+ */
|
|
|
+ public function publishCreate(int $accessId, $entity): void {
|
|
|
+ $this->publish($accessId, $entity, self::CREATE);
|
|
|
+ }
|
|
|
+
|
|
|
+ /**
|
|
|
+ * @param $entity
|
|
|
+ * @param int $accessId
|
|
|
+ */
|
|
|
+ public function publishDelete(int $accessId, $entity): void {
|
|
|
+ $this->publish($accessId, $entity, self::DELETE);
|
|
|
+ }
|
|
|
+}
|