diff --git a/.gitignore b/.gitignore index 3a2a5ba..a6a6a28 100755 --- a/.gitignore +++ b/.gitignore @@ -4,3 +4,4 @@ # Backup entities generated with doctrine:generate:entities command **/Entity/*~ +./.idea diff --git a/Annotations/SyncEntity.php b/Annotations/SyncEntity.php new file mode 100755 index 0000000..1786a19 --- /dev/null +++ b/Annotations/SyncEntity.php @@ -0,0 +1,13 @@ +get('nti.sync')->getFromMappings($mappings); + $resultData = $this->get('nti.sync')->getFromMappings($mappings); - return new JsonResponse($changes, 200); + $resultData = json_decode($this->container->get('jms_serializer')->serialize($resultData, 'json'), true); + + return new JsonResponse($resultData, 200); } /** diff --git a/Entity/SyncFailedItemState.php b/Entity/SyncFailedItemState.php old mode 100644 new mode 100755 index 7088247..4d4fcd9 --- a/Entity/SyncFailedItemState.php +++ b/Entity/SyncFailedItemState.php @@ -54,7 +54,7 @@ class SyncFailedItemState { /** * @var string * - * @ORM\Column(name="errors", columnDefinition="TEXT", length=65535, nullable=true) + * @ORM\Column(name="errors", type="text", nullable=true) */ private $errors; diff --git a/Entity/SyncMapping.php b/Entity/SyncMapping.php old mode 100644 new mode 100755 index 04ac4d2..ab4ca91 --- a/Entity/SyncMapping.php +++ b/Entity/SyncMapping.php @@ -38,7 +38,7 @@ class SyncMapping /** * @var string * - * @ORM\Column(name="sync_service", type="string", length=255, nullable=false) + * @ORM\Column(name="sync_service", type="string", length=255, nullable=true) */ private $syncService; diff --git a/Entity/SyncState.php b/Entity/SyncState.php index 1e47788..e7999ec 100755 --- a/Entity/SyncState.php +++ b/Entity/SyncState.php @@ -13,6 +13,7 @@ class SyncState { const REAL_LAST_TIMESTAMP = "_real_last_timestamp"; + const TOTAL_COUNT = "_total_count"; /** * @var int * diff --git a/EventListener/DoctrineEventSubscriber.php b/EventListener/DoctrineEventSubscriber.php deleted file mode 100755 index 8700e95..0000000 --- a/EventListener/DoctrineEventSubscriber.php +++ /dev/null @@ -1,67 +0,0 @@ -container = $container; - $this->syncService = $this->container->get('nti.sync'); - } - - public function getSubscribedEvents() - { - return array( - 'onFlush', - 'preRemove', - ); - } - - public function onFlush(OnFlushEventArgs $args) - { - $em = $args->getEntityManager(); - $uow = $em->getUnitOfWork(); - - foreach ($uow->getScheduledEntityUpdates() as $keyEntity => $entity) { - $this->handleEntityChange($em, $entity); - } - - foreach ($uow->getScheduledEntityInsertions() as $keyEntity => $entity) { - $this->handleEntityChange($em, $entity); - } - } - - public function preRemove(LifecycleEventArgs $args) - { - - $entity = $args->getEntity(); - $class = get_class($entity); - $id = null; - - if(method_exists($entity, 'getId')) { - $id = $entity->getId(); - } - - $this->syncService->addToDeleteSyncState($class, $id); - } - - private function handleEntityChange(EntityManagerInterface $em, $entity) { - if(method_exists($entity, 'getLastTimestamp')) { - $timestamp = $entity->getLastTimestamp() ?? time(); - } else { - $timestamp = time(); - } - $class = get_class($entity); - $this->syncService->updateSyncState($em, $class, $timestamp); - } - -} \ No newline at end of file diff --git a/EventSubscriber/DoctrineEventSubscriber.php b/EventSubscriber/DoctrineEventSubscriber.php new file mode 100755 index 0000000..acd0f97 --- /dev/null +++ b/EventSubscriber/DoctrineEventSubscriber.php @@ -0,0 +1,131 @@ +container = $container; + $this->syncService = $this->container->get('nti.sync'); + } + + public function getSubscribedEvents() + { + return array( + 'onFlush', + ); + } + + public function onFlush(OnFlushEventArgs $args) + { + + $em = $args->getEntityManager(); + $uow = $em->getUnitOfWork(); + + foreach ($uow->getScheduledEntityUpdates() as $entity) { + $this->processEntity($em, $entity); + } + + foreach ($uow->getScheduledEntityInsertions() as $entity) { + $this->processEntity($em, $entity); + } + + foreach ($uow->getScheduledEntityDeletions() as $entity) { + $this->processEntity($em, $entity, true); + $this->container->get('nti.sync')->addToDeleteSyncState(ClassUtils::getClass($entity), $entity->getId()); + + } + + /** @var PersistentCollection $collectionUpdate */ + foreach ($uow->getScheduledCollectionUpdates() as $collectionUpdate) { + foreach($collectionUpdate as $entity) { + $this->processEntity($em, $entity); + } + } + + /** @var PersistentCollection $collectionDeletion */ + foreach($uow->getScheduledCollectionDeletions() as $collectionDeletion) { + foreach($collectionDeletion as $entity) { + $this->processEntity($em, $entity, true); + $this->container->get('nti.sync')->addToDeleteSyncState(ClassUtils::getClass($entity), $entity->getId()); + } + } + + } + + private function processEntity(EntityManagerInterface $em, $entity, $deleting = false) + { + + $reflection = new \ReflectionClass(ClassUtils::getClass($entity)); + $annotationReader = new AnnotationReader(); + $syncEntityAnnotation = $annotationReader->getClassAnnotation($reflection, SyncEntity::class); + // Check if the entity should be synchronized + if (!$syncEntityAnnotation) { + return; + } + + $uow = $em->getUnitOfWork(); + $timestamp = time(); + + // Update the mapping's sync state if exists + $mapping = $em->getRepository(SyncMapping::class)->findOneBy(array("class" => ClassUtils::getClass($entity))); + if($mapping) { + $syncState = $em->getRepository(SyncState::class)->findOneBy(array("mapping" => $mapping)); + if(!$syncState) { + $syncState = new SyncState(); + $syncState->setMapping($mapping); + $em->persist($syncState); + } + $syncState->setTimestamp($timestamp); + if($uow->getEntityState($syncState) == UnitOfWork::STATE_MANAGED) { + if($syncState->getId()) { + $uow->recomputeSingleEntityChangeSet($em->getClassMetadata(SyncState::class), $syncState); + } else { + $uow->computeChangeSet($em->getClassMetadata(SyncState::class), $syncState); + } + } + } + + // Check if this class itself has a lastTimestamp + if(!$deleting && method_exists($entity, 'setLastTimestamp')) { + $entity->setLastTimestamp($timestamp); + $uow->recomputeSingleEntityChangeSet($em->getClassMetadata(ClassUtils::getClass($entity)), $entity); + } + + // Notify relationships + /** @var \ReflectionProperty $property */ + foreach ($reflection->getProperties() as $property) { + + /** @var SyncParent $annotation */ + if (null !== ($annotation = $annotationReader->getPropertyAnnotation($property, SyncParent::class))) { + $getter = $annotation->getter; + $parent = $entity->$getter(); + // Using ClassUtils as $parent is actually a Proxy of the class + $reflrectionParent = new \ReflectionClass(ClassUtils::getClass($parent)); + $syncParentAnnotation = $annotationReader->getClassAnnotation($reflrectionParent, SyncEntity::class); + if(!$syncParentAnnotation) { + continue; + } + $this->processEntity($em, $parent); + } + } + } +} diff --git a/Interfaces/SyncRepositoryInterface.php b/Interfaces/SyncRepositoryInterface.php index 6053bdb..375ced0 100755 --- a/Interfaces/SyncRepositoryInterface.php +++ b/Interfaces/SyncRepositoryInterface.php @@ -2,6 +2,8 @@ namespace NTI\SyncBundle\Interfaces; +use NTI\SyncBundle\Models\SyncPullRequestData; +use NTI\SyncBundle\Models\SyncPullResponseData; use Symfony\Component\DependencyInjection\ContainerInterface; /** @@ -9,25 +11,20 @@ * @package NTI\SyncBundle\Interfaces */ interface SyncRepositoryInterface { + /** - * This function should return a plain array containing the results to be sent to the client + * This function should return an instance of SyncPullResponseData containing the results to be sent to the client * when a sync is requested. The container is also passed as a parameter in order to give additional * flexibility to the repository when making decision on what to show to the client. For example, if the user * making the request only has access to a portion of the data, this can be handled via the container in this method * of the repository. * - * The resulting structure should be the following: - * - * array( - * "data" => (array of objects), - * SyncState::REAL_LAST_TIMESTAMP => (last updated_on date from the array of objects), - * ) + * The resulting structure should be an instance of SyncPullRequestData * * - * @param $timestamp * @param ContainerInterface $container - * @param array $serializationGroups - * @return mixed + * @param SyncPullRequestData $requestData + * @return SyncPullResponseData */ - public function findFromTimestamp($timestamp, ContainerInterface $container, $serializationGroups = array()); + public function findFromTimestamp(ContainerInterface $container, SyncPullRequestData $requestData); } diff --git a/Models/SyncPullRequestData.php b/Models/SyncPullRequestData.php new file mode 100755 index 0000000..afd34e5 --- /dev/null +++ b/Models/SyncPullRequestData.php @@ -0,0 +1,153 @@ + than the timestamp provided + * and all of those 300 results have the same timestamp (for example, it is normal to + * set the inital timestamp to 0 when first installing this bundle) this would cause + * a loop and the client would always sync the same 50 results over and over again. + * + * For this, the client can send the `page` parameter, which then can be used in the repository to offset the results. + * + */ + private $page = 1; + + /** + * @var array|string + * @JMS\Type("array") + * + * The serialization groups that the process should use when returning the results + */ + private $serializationGroups = array("sync_basic"); + + /** + * @return string + */ + public function getMapping() + { + return $this->mapping; + } + + /** + * @param string $mapping + * @return SyncPullRequestData + */ + public function setMapping($mapping) + { + $this->mapping = $mapping; + return $this; + } + + /** + * @return int + */ + public function getTimestamp() + { + return $this->timestamp; + } + + /** + * @param int $timestamp + * @return SyncPullRequestData + */ + public function setTimestamp($timestamp) + { + $this->timestamp = $timestamp; + return $this; + } + + /** + * @return int + */ + public function getLimit() + { + return $this->limit; + } + + /** + * @param int $limit + * @return SyncPullRequestData + */ + public function setLimit($limit) + { + $this->limit = $limit; + return $this; + } + + /** + * @return int + */ + public function getPage() + { + return $this->page; + } + + /** + * @param int $page + * @return SyncPullRequestData + */ + public function setPage($page) + { + $this->page = $page; + return $this; + } + + /** + * @return array|string + */ + public function getSerializationGroups() + { + return $this->serializationGroups; + } + + /** + * @param array|string $serializationGroups + * @return SyncPullRequestData + */ + public function setSerializationGroups($serializationGroups) + { + $this->serializationGroups = $serializationGroups; + return $this; + } + + +} \ No newline at end of file diff --git a/Models/SyncPullResponseData.php b/Models/SyncPullResponseData.php new file mode 100755 index 0000000..6fb45eb --- /dev/null +++ b/Models/SyncPullResponseData.php @@ -0,0 +1,94 @@ +realLastTimestamp; + } + + /** + * @param int $realLastTimestamp + * @return SyncPullResponseData + */ + public function setRealLastTimestamp(int $realLastTimestamp): SyncPullResponseData + { + $this->realLastTimestamp = $realLastTimestamp; + return $this; + } + + /** + * @return array + */ + public function getData(): array + { + return $this->data; + } + + /** + * @param array $data + * @return SyncPullResponseData + */ + public function setData(array $data): SyncPullResponseData + { + $this->data = $data; + return $this; + } + + /** + * @return int + */ + public function getTotalCount(): int + { + return $this->totalCount; + } + + /** + * @param int $totalCount + * @return SyncPullResponseData + */ + public function setTotalCount(int $totalCount): SyncPullResponseData + { + $this->totalCount = $totalCount; + return $this; + } + + +} \ No newline at end of file diff --git a/README.md b/README.md index b95289d..a726b09 100755 --- a/README.md +++ b/README.md @@ -40,14 +40,103 @@ Below are a list of things that need to be considered in order to implement this bundle: -1. Entities need to have a method called `getlastTimestamp()` in order for this bundle to work properly. As the name implies, it should return the `lastTimestamp` of when the object was last updated and cannot be null. (You need to handle this lastTimestamp property, for example, by using LifecyclecCallbacks) -2. Entities to be synced must have a repository implementing the `SyncRepositoryInterface`. (see below for more information) -3. The mapping (`SyncMapping`) needs to be configured foreach entity as it is the list used as reference for the lookup +1. Any Entity that needs to be taken into account during the synchronization process must have the `@NTI\SyncEntity` annotation at the class level. +2. `ManyToOne` relationships that should alter the last synchronization timestamp of their parents should use the annotation `@NTI\SyncParent(getter="[Getter Name]")` (see example below for more information). +3. Entities to be synced must have a repository implementing the `SyncRepositoryInterface` (see below for more information). +4. The mapping `SyncMapping` needs to be configured foreach entity as it is the list used as reference for the lookup. +5. The `SyncState` should be created for each mapping. This can be done with this query after creating all the `SyncMapping`: + ``` + `INSERT INTO nti_sync_state(mapping_id, timestamp) SELECT id, 0 FROM sync_nti_mapping;` +6. If the entity is going to be synched FROM the client, then a service must be defined in the `SyncMapping` database entry. Also, this method needs to implement the interface `SyncServiceInterface`. + +## Tracking Changes -## Background process +The way that the bundle tracks changes in the synchronization is as follows: -The bundle takes care of tracking the changes made to the entities by using a `DoctrineEventListener` which listenes to the `PreUpdate`, `PrePersist`, and `PreRemove` events. When any of these events is fired on an Entity that contains a `SyncMapping` defined, the bundle will call the `getlastTimestamp()` on this entity and use this value as the last `timtestamp` that the entity in general was updated. +1. The bundle has a `DoctrineEventListener` listening to the `onFlush` event. +2. Once the event is fired, the bundle will grab every entitty that has the `@NTI\SyncEntity` annotation. +3. If the entity has a `SyncMapping` defined, the system will update the `last_timestamp` field of this mapping to the current `time()`. +4. If the entity has a method called `setLastTimestamp()` it will be called with the `time()` as a parameter and the changes will be recomputed or computed. +5. All the properties of the entity will be examined in search for a property that contains the annotation `@NTI\SyncParent(getter="[Getter Name]")`. + If found, the getter will be called, if the result is an object that also has the `@NTI\SyncEntity`, it will be processed again starting from point #3. This process occurrs recursively. + +## Class Examples + + ``` + lastTimestamp = $lastTimestamp; + return $this; + } + + /** + * Get lastTimestamp + * @return integer + */ + public function getLastTimestamp() + { + return $this->lastTimestamp; + } + + } + +An example of a class using a `ManyToOne` where the child also needs the parent's `last_timestamp` to be updated can be defined as: + ``` + product; + } + } + Below is the general process that the bundles goes through to keep track of the synchronization state: ![Synchronization Process - Server](/Images/SynchronizationProcess-Server.PNG?raw=true "Synchronization State Process on the Server") @@ -111,7 +200,7 @@ Besides implementing the interface, in the database `nti_sync_mapping` the mappi First, the idea is to get a summary of the changes and mappings from the server: ``` -GET /nti/sync/getSummary +GET /nti/sync/summary ``` To which the server will respond with the following structure: @@ -146,7 +235,6 @@ Content-Type: application/json ] } ``` -Note: This request can also be done using a query and GET instead. After receiving the request, if a mapping with the specified name exists, the system will call the repository's findFromTimestamp implementation and return the following result (Using a Product entity as an example): @@ -207,7 +295,7 @@ After receiving the request, if a mapping with the specified name exists, the sy }, "classId": 137, "timestamp": 1512080747, - "errors": "{"has_error":true,"additional_errors":null,"code":403,"message":"This inventory report is already closed. Further operations are not allowed.","data":null,"redirect":null}" + "errors": [...errors provided...] }, ... ], @@ -217,16 +305,16 @@ After receiving the request, if a mapping with the specified name exists, the sy ``` -The server will return the both the `changes` , `newItems`, `failedItems` ,and the `deletes`. The `changes` will contain the `data` portion of the array returned by +The server will return the both the `changes` , `newItems`, `failedItems` , and the `deletes`. The `changes` will contain the `data` portion of the array returned by the repository's implementation of `SyncRepositoryInterface`. The `deletes` will contain the list of `SyncDeleteState` that were recorded since the specified timestamp. The `newItems` will contain the list of `SyncNewItemState` which means the new items that were created since the provided timestamp including the UUID that was given at the time (This is helpful to third party devices when first pulling the information they can verify if an item was already created but they don't have the ID of that item in their local storage and avoid creating duplicates in the server). The `failedItems` will contain the list of `SyncFailedItemState`, each item in this list -contains an `errors` JSON property with the list of errors founds processing the creation or update of the entity. +contains an `errors` property with the errors founds processing the creation or update of the entity. The `_real_last_timestamp` should be used as it can help with paginating the results for a full-sync and help the client get the real last timestamp of the last object in the response. This has to be obtained in the repository and can be done -by simply looping through the array of objects and getting the latest updatedOn. +by simply getting the last item from the repository's result and calling the `getLastTimestamp()`. From this point on, the client must keep a track of the `_real_last_timestamp` in order to perform a sync in the future. @@ -236,10 +324,10 @@ Below is the general idea over the push/pull process: ![Synchronization Process - Push/Pull](/Images/SynchronizationProcess-PushPull.PNG?raw=true "Synchronization Push Pull Process") -###Server Side +### Server Side In the `SyncMapping` for each mapped entity a service should be specified. This service must implement the `SyncServiceInterface`. -###Client Side +### Client Side In order to handle a push from a third party device it must provide the following structure in its request: ``` @@ -277,9 +365,7 @@ The server then returns the following structure: } ``` - - - ## Todo * Handle deletes from third parties +* `ManyToMany` relationships are tricky and can lead to performance issues diff --git a/Repository/SyncRepository.php b/Repository/SyncRepository.php new file mode 100755 index 0000000..675c648 --- /dev/null +++ b/Repository/SyncRepository.php @@ -0,0 +1,64 @@ +getTimestamp(); + $serializationGroups = $requestData->getSerializationGroups(); + $page = $requestData->getPage() > 0 ? $requestData->getPage() - 1 : 0; + $limit = $requestData->getLimit(); + + // Joins + $qb = $this->createQueryBuilder('i'); + $qb->andWhere($qb->expr()->gte('i.lastTimestamp', $timestamp)); + $qb->orderBy('i.lastTimestamp', 'asc'); + + /** + * This should be set BEFORE getting the total count, that way the client will receive + * the actual items that are left for it to sync, not the total amount from a timestamp. + * @Ref the "page"parameter in SyncPulLRequestData + */ + $qb->setFirstResult($page * $limit); + + // Total records + $totalCountQb = clone $qb; + $totalCountQb->select('COUNT(i.id)'); + $totalCountQuery = $totalCountQb->getQuery(); + + try { + $totalCount = intval($totalCountQuery->getSingleScalarResult()); + } catch (\Exception $e) { + $totalCount = 0; + } + + $qb->setMaxResults($limit); + + $items = $qb->getQuery()->getResult(); + + $realLastTimestamp = count($items) <= 0 ? $timestamp : $items[count($items) - 1]->getLastTimestamp(); + + $itemsArray = json_decode($container->get('jms_serializer')->serialize($items, 'json', SerializationContext::create()->setGroups($serializationGroups)), true); + + $result = new SyncPullResponseData(); + $result->setData($itemsArray); + $result->setRealLastTimestamp($realLastTimestamp); + $result->setTotalCount($totalCount); + + return $result; + } + +} \ No newline at end of file diff --git a/Resources/config/services.yml b/Resources/config/services.yml index 212e162..e065d6d 100755 --- a/Resources/config/services.yml +++ b/Resources/config/services.yml @@ -1,6 +1,6 @@ services: nti.sync.doctrine.listener: - class: NTI\SyncBundle\EventListener\DoctrineEventSubscriber + class: NTI\SyncBundle\EventSubscriber\DoctrineEventSubscriber arguments: ["@service_container"] tags: - { name: doctrine.event_subscriber, connection: default } diff --git a/Service/SyncService.php b/Service/SyncService.php index 004ce9c..d8f8496 100755 --- a/Service/SyncService.php +++ b/Service/SyncService.php @@ -5,10 +5,12 @@ use Doctrine\ORM\EntityManager; use Doctrine\ORM\EntityManagerInterface; use NTI\SyncBundle\Entity\SyncDeleteState; +use NTI\SyncBundle\Entity\SyncFailedItemState; use NTI\SyncBundle\Entity\SyncMapping; use NTI\SyncBundle\Entity\SyncNewItemState; use NTI\SyncBundle\Entity\SyncState; use NTI\SyncBundle\Interfaces\SyncRepositoryInterface; +use NTI\SyncBundle\Models\SyncPullRequestData; use Symfony\Component\DependencyInjection\ContainerInterface; /** @@ -46,72 +48,38 @@ public function getFromMappings($mappings) { foreach($mappings as $mapping) { - if(!isset($mapping["timestamp"]) || !isset($mapping["mapping"])) { - continue; - } + $requestData = $this->container->get('jms_serializer')->deserialize(json_encode($mapping), SyncPullRequestData::class, 'json'); - $timestamp = $mapping["timestamp"]; - $mappingName = $mapping["mapping"]; - $serializationGroup = (isset($mapping["serializer"])) ? $mapping["serializer"] : "sync_basic"; - - $syncMapping = $this->em->getRepository(SyncMapping::class)->findOneBy(array("name" => $mappingName)); + $syncMapping = $this->em->getRepository(SyncMapping::class)->findOneBy(array("name" => $requestData->getMapping())); if(!$syncMapping) { continue; } - $deletes = $this->em->getRepository(SyncDeleteState::class)->findFromTimestamp($mappingName, $timestamp); - $newItems = $this->em->getRepository(SyncNewItemState::class)->findFromTimestampAndMapping($mappingName, $timestamp); - /** - * Failed Items Synchronization - */ - $failedItems = $this->em->getRepository('NTISyncBundle:SyncFailedItemState')->findFromTimestampAndMapping($mappingName, $timestamp); + $deletes = $this->em->getRepository(SyncDeleteState::class)->findFromTimestamp($requestData->getMapping(), $requestData->getTimestamp()); + $newItems = $this->em->getRepository(SyncNewItemState::class)->findFromTimestampAndMapping($requestData->getMapping(), $requestData->getTimestamp()); + $failedItems = $this->em->getRepository(SyncFailedItemState::class)->findFromTimestampAndMapping($requestData->getMapping(), $requestData->getTimestamp()); /** @var SyncRepositoryInterface $repository */ $repository = $this->em->getRepository($syncMapping->getClass()); if(!($repository instanceof SyncRepositoryInterface)) { - error_log("The repository for the class {$mapping->getClass()} does not implement the SyncRepositoryInterface."); + error_log("The repository for the class {$syncMapping->getClass()} does not implement the SyncRepositoryInterface."); continue; } - $result = $repository->findFromTimestamp($timestamp, $this->container, $serializationGroup); + $result = $repository->findFromTimestamp($this->container, $requestData); - $changes[$mappingName] = array( - 'changes' => $result["data"], + $changes[$requestData->getMapping()] = array( + 'changes' => $result, 'deletes' => json_decode($this->container->get('jms_serializer')->serialize($deletes, 'json'), true), 'newItems' => json_decode($this->container->get('jms_serializer')->serialize($newItems, 'json'), true), - 'failedItems' => json_decode($this->container->get('jms_serializer')->serialize($failedItems, 'json'), true), - SyncState::REAL_LAST_TIMESTAMP => $result[SyncState::REAL_LAST_TIMESTAMP], + 'failedItems' => json_decode($this->container->get('jms_serializer')->serialize($failedItems, 'json'), true), ); } return $changes; } - public function updateSyncState(EntityManagerInterface $em, $class, $timestamp) { - - $mapping = $em->getRepository(SyncMapping::class)->findOneBy(array("class" => $class)); - if(!$mapping) { - return; - } - - $syncState = $em->getRepository(SyncState::class)->findOneBy(array("mapping" => $mapping)); - - $uow = $em->getUnitOfWork(); - - if(!$syncState) { - $syncState = new SyncState(); - $syncState->setMapping($mapping); - $syncState->setTimestamp($timestamp); - $em->persist($syncState); - $uow->computeChangeSet($em->getClassMetadata(SyncState::class), $syncState); - } else { - $syncState->setTimestamp($timestamp); - $uow->recomputeSingleEntityChangeSet($em->getClassMetadata(SyncState::class), $syncState); - } - - } - /** * Create a new SyncDeleteState for the given class/id * @@ -122,6 +90,7 @@ public function addToDeleteSyncState($class, $id) { $this->em = $this->container->get('doctrine')->getManager(); + /** @var SyncMapping $mapping */ $mapping = $this->em->getRepository(SyncMapping::class)->findOneBy(array("class" => $class)); if(!$mapping) { return; @@ -133,12 +102,7 @@ public function addToDeleteSyncState($class, $id) { $deleteEntry->setTimestamp(time()); $this->em->persist($deleteEntry); - - try { - $this->em->flush(); - } catch (\Exception $ex) { - error_log("Unable to register deletion of object: " . $class . " with ID " . $id); - error_log($ex->getMessage()); - } + $uow = $this->em->getUnitOfWork(); + $uow->computeChangeSet($this->em->getClassMetadata(SyncDeleteState::class), $deleteEntry); } }