Skip to content

Commit

Permalink
Rename synchronization service, split generic code and specific defaults
Browse files Browse the repository at this point in the history
  • Loading branch information
rjzondervan committed Sep 25, 2024
1 parent 4baf8ab commit 9e37d5b
Show file tree
Hide file tree
Showing 5 changed files with 232 additions and 182 deletions.
2 changes: 1 addition & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
"license": "EUPL-1.2",
"minimum-stability": "dev",
"require": {
"php": ">=7.4",
"php": ">=8.2",
"commongateway/corebundle": "^1.2.68 | <2.0"
},
"require-dev": {
Expand Down
109 changes: 0 additions & 109 deletions src/Service/InstallationService.php

This file was deleted.

207 changes: 207 additions & 0 deletions src/Service/NewSynchronizationService.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,207 @@
<?php

Check failure on line 2 in src/Service/NewSynchronizationService.php

View workflow job for this annotation

GitHub Actions / build

Missing file doc comment
namespace CommonGateway\VrijBRPToZGWBundle\Service;

use Adbar\Dot;
use App\Entity\Gateway as Source;
use App\Entity\ObjectEntity;
use App\Entity\Synchronization;
use App\Service\SynchronizationService;
use CommonGateway\CoreBundle\Service\CallService;
use CommonGateway\CoreBundle\Service\GatewayResourceService;
use CommonGateway\CoreBundle\Service\MappingService;
use DateInterval;
use DateTime;
use Doctrine\ORM\EntityManagerInterface;
use Exception;
use GuzzleHttp\Exception\GuzzleException;
use Psr\Log\LoggerInterface;
use Twig\Error\LoaderError;
use Twig\Error\SyntaxError;


/**
* Service to synchronize resources between gateway and external sources.
*
* This service provides synchronization functionality to synchronize between sources and the gateway.
*
* @author Robert Zondervan, Barry Brands, Ruben van der Linde
* @license EUPL<github.com/ConductionNL/contactcatalogus/blob/master/LICENSE.md>
*
* @category Service
*/
class NewSynchronizationService

Check warning on line 33 in src/Service/NewSynchronizationService.php

View workflow job for this annotation

GitHub Actions / build

The class NewSynchronizationService has a coupling between objects value of 16. Consider to reduce the number of dependencies under 13.
{
public function __construct(
private readonly GatewayResourceService $resourceService,
private readonly CallService $callService,
private readonly SynchronizationService $synchronizationService,

Check warning on line 38 in src/Service/NewSynchronizationService.php

View workflow job for this annotation

GitHub Actions / build

Avoid excessively long variable names like $synchronizationService. Keep variable name length under 20.
private readonly LoggerInterface $synchronizationLogger,

Check warning on line 39 in src/Service/NewSynchronizationService.php

View workflow job for this annotation

GitHub Actions / build

Avoid excessively long variable names like $synchronizationLogger. Keep variable name length under 20.
private readonly EntityManagerInterface $entityManager,
private readonly MappingService $mappingService,
)
{

}

/**
* Executes the synchronization from source to gateway.
* Slightly edited clone of the SynchronizationService in the gateway.
*
* @param Synchronization $synchronization The synchronization to update
* @param array $sourceObject The object in the source
* @param bool $unsafe Unset attributes that are not included in the hydrator array when calling the hydrate function

Check warning on line 53 in src/Service/NewSynchronizationService.php

View workflow job for this annotation

GitHub Actions / build

Line exceeds 125 characters; contains 141 characters
*
* @throws GuzzleException
* @throws LoaderError
* @throws SyntaxError
*
* @return Synchronization The updated synchronization
*/
public function synchronizeFromSource(Synchronization $synchronization, array $sourceObject = [], bool $unsafe = false): Synchronization

Check warning on line 61 in src/Service/NewSynchronizationService.php

View workflow job for this annotation

GitHub Actions / build

The method synchronizeFromSource() has a Cyclomatic Complexity of 10. The configured cyclomatic complexity threshold is 10.

Check warning on line 61 in src/Service/NewSynchronizationService.php

View workflow job for this annotation

GitHub Actions / build

The method synchronizeFromSource() has an NPath complexity of 256. The configured NPath complexity threshold is 200.

Check warning on line 61 in src/Service/NewSynchronizationService.php

View workflow job for this annotation

GitHub Actions / build

The method synchronizeFromSource has a boolean flag argument $unsafe, which is a certain sign of a Single Responsibility Principle violation.

Check warning on line 61 in src/Service/NewSynchronizationService.php

View workflow job for this annotation

GitHub Actions / build

Line exceeds 125 characters; contains 140 characters
{
$this->synchronizationLogger->info("handleSync for Synchronization with id = {$synchronization->getId()->toString()}");

Check warning on line 63 in src/Service/NewSynchronizationService.php

View workflow job for this annotation

GitHub Actions / build

Line exceeds 125 characters; contains 127 characters

//create new object if no object exists
if (!$synchronization->getObject()) {
isset($this->io) && $this->io->text('creating new objectEntity');
$this->synchronizationLogger->info('creating new objectEntity');
$object = new ObjectEntity($synchronization->getEntity());
$object->addSynchronization($synchronization);
$this->entityManager->persist($object);
$this->entityManager->persist($synchronization);
$oldDateModified = null;
} else {

Check warning on line 74 in src/Service/NewSynchronizationService.php

View workflow job for this annotation

GitHub Actions / build

The method synchronizeFromSource uses an else expression. Else clauses are basically not necessary and you can simplify the code by not using them.
$oldDateModified = $synchronization->getObject()->getDateModified()->getTimestamp();
}
$sourceObject = $sourceObject ?: $this->synchronizationService->getSingleFromSource($synchronization);

if ($sourceObject === null) {
$this->synchronizationLogger->warning("Can not handle Synchronization with id = {$synchronization->getId()->toString()} if \$sourceObject === null");

return $synchronization;
}

// Let check
$now = new DateTime();
$synchronization->setLastChecked($now);

$sha = hash('sha256', json_encode($sourceObject));

// Checking if data on source has changed.
if($synchronization->getSha() === $sha) {
return $synchronization;
}

// Counter
$counter = $synchronization->getTryCounter() + 1;
if ($counter > 10000) {
$counter = 10000;
}
$synchronization->setTryCounter($counter);

// Set dont try before, expensional so in minutes 1,8,27,64,125,216,343,512,729,1000
$addMinutes = pow($counter, 3);
if ($synchronization->getDontSyncBefore()) {
$dontTryBefore = $synchronization->getDontSyncBefore()->add(new DateInterval('PT'.$addMinutes.'M'));
} else {

Check warning on line 107 in src/Service/NewSynchronizationService.php

View workflow job for this annotation

GitHub Actions / build

The method synchronizeFromSource uses an else expression. Else clauses are basically not necessary and you can simplify the code by not using them.
$dontTryBefore = new DateTime();
}
$synchronization->setDontSyncBefore($dontTryBefore);

if ($synchronization->getMapping()) {
$sourceObject = $this->mappingService->mapping($synchronization->getMapping(), $sourceObject);
}
$synchronization->getObject()->hydrate($sourceObject, $unsafe);

$synchronization->setSha($sha);

$this->entityManager->persist($synchronization->getObject());
$this->entityManager->persist($synchronization);

if ($oldDateModified !== $synchronization->getObject()->getDateModified()->getTimestamp()) {
$date = new DateTime();
isset($this->io) ?? $this->io->text("set new dateLastChanged to {$date->format('d-m-YTH:i:s')}");
$synchronization->setLastSynced(new DateTime());
$synchronization->setTryCounter(0);
} else {

Check warning on line 127 in src/Service/NewSynchronizationService.php

View workflow job for this annotation

GitHub Actions / build

The method synchronizeFromSource uses an else expression. Else clauses are basically not necessary and you can simplify the code by not using them.
isset($this->io) ?? $this->io->text("lastSynced is still {$synchronization->getObject()->getDateModified()->format('d-m-YTH:i:s')}");

Check warning on line 128 in src/Service/NewSynchronizationService.php

View workflow job for this annotation

GitHub Actions / build

Line exceeds 125 characters; contains 149 characters
}

return $synchronization;
}

/**
* Fetch data from source in a way that is as abstract as possible at this time.
*
* @param array $configuration
* @param Source $source
* @return array
* @throws Exception
*/
public function getResults(array $configuration, Source $source): array
{
$response = $this->callService->call(source: $source, endpoint: $configuration['endpoint'], method: $configuration['method'], config: ['json' => ['types' => $configuration['types']]]);

$result = $this->callService->decodeResponse(source: $source, response: $response, contentType: $configuration['content-type'] ?? 'application/json');

$resultDot = new Dot($result);


if($resultDot->has(keys: $configuration['resultsPath']) === true) {
$return = $resultDot->get(key: $configuration['resultsPath']);
if($return instanceof Dot) {
return $return->jsonSerialize();
} else if (is_array($return)) {
return $return;
}
}

throw new Exception('No cases found');
}


/**
* This function is designed to in time replace the existing syncCollectionHandler.
* At the moment it depends on the in-gateway SynchronizationService, and is one way with the source as the leading version.

Check warning on line 166 in src/Service/NewSynchronizationService.php

View workflow job for this annotation

GitHub Actions / build

Line exceeds 125 characters; contains 128 characters
*
* @param array $data
* @param array $configuration
* @return array
* @throws \GuzzleHttp\Exception\GuzzleException
*/
public function synchronizeCollectionHandler (array $data, array $configuration): array
{
$source = $this->resourceService->getSource(reference: $configuration['source'], pluginName: "common-gateway/vrijbrp-to-zgw-bundle");

Check warning on line 175 in src/Service/NewSynchronizationService.php

View workflow job for this annotation

GitHub Actions / build

Line exceeds 125 characters; contains 141 characters
$schema = $this->resourceService->getSchema(reference: $configuration['schema'], pluginName: "common-gateway/vrijbrp-to-zgw-bundle");

Check warning on line 176 in src/Service/NewSynchronizationService.php

View workflow job for this annotation

GitHub Actions / build

Line exceeds 125 characters; contains 141 characters

if(isset($configuration['mapping']) === true) {
$mapping = $this->resourceService->getMapping(reference: $configuration['mapping'], pluginName: "common-gateway/vrijbrp-to-zgw-bundle");

Check warning on line 179 in src/Service/NewSynchronizationService.php

View workflow job for this annotation

GitHub Actions / build

Line exceeds 125 characters; contains 148 characters
}

try {
$dossiers = $this->getResults(configuration: $configuration, source: $source);
} catch (Exception $exception) {
$this->synchronizationLogger->warning(message: $exception->getMessage(), context: ['plugin' => 'common-gateway/vrijbrp-to-zgw-bundle']);

Check warning on line 185 in src/Service/NewSynchronizationService.php

View workflow job for this annotation

GitHub Actions / build

Line exceeds 125 characters; contains 148 characters
return $data;
}

foreach($dossiers as $dossier) {
$dossierDot = new Dot($dossier);

$synchronization = $this->synchronizationService->findSyncBySource(source: $source, entity: $schema, sourceId: $dossierDot[$configuration['idLocation']], endpoint: $configuration['endpoint']);

if($synchronization->getMapping() === null && isset($mapping) === true) {
$synchronization->setMapping($mapping);
}

try{
$this->synchronizeFromSource(synchronization: $synchronization, sourceObject: $dossier);
} catch (Exception $exception) {
$this->synchronizationLogger->error(message: $exception->getMessage(), context: ['plugin' => 'common-gateway/vrijbrp-to-zgw-bundle']);

Check warning on line 201 in src/Service/NewSynchronizationService.php

View workflow job for this annotation

GitHub Actions / build

Line exceeds 125 characters; contains 150 characters
}
}

return $data;
}
}
24 changes: 24 additions & 0 deletions src/Service/VrijBrpService.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
<?php

Check failure on line 2 in src/Service/VrijBrpService.php

View workflow job for this annotation

GitHub Actions / build

Missing file doc comment
namespace CommonGateway\VrijBRPToZGWBundle\Service;

class VrijBrpService
{
public function setVrijBRPDefaults(array $configuration): array

Check failure on line 7 in src/Service/VrijBrpService.php

View workflow job for this annotation

GitHub Actions / build

Missing doc comment for function setVrijBRPDefaults()

Check failure on line 7 in src/Service/VrijBrpService.php

View workflow job for this annotation

GitHub Actions / build

Expected 2 blank lines before function; 0 found
{
if (isset($configuration['endpoint']) === false) {
$configuration['endpoint'] = '/v1/api/dossiers/search';
}

Check failure on line 11 in src/Service/VrijBrpService.php

View workflow job for this annotation

GitHub Actions / build

No blank line found after control structure
if (isset($configuration['method']) === false) {
$configuration['method'] = 'POST';
}

Check failure on line 14 in src/Service/VrijBrpService.php

View workflow job for this annotation

GitHub Actions / build

No blank line found after control structure
if (isset($configuration['types']) === false) {
$configuration['types'] = [
'intra_mun_relocation',
'inter_mun_relocation',
];
}

return $configuration;
}

Check failure on line 23 in src/Service/VrijBrpService.php

View workflow job for this annotation

GitHub Actions / build

Expected //end setVrijBRPDefaults()

Check failure on line 23 in src/Service/VrijBrpService.php

View workflow job for this annotation

GitHub Actions / build

Expected 1 blank line before closing function brace; 0 found

Check failure on line 23 in src/Service/VrijBrpService.php

View workflow job for this annotation

GitHub Actions / build

Expected 2 blank lines after function; 0 found
}

Check failure on line 24 in src/Service/VrijBrpService.php

View workflow job for this annotation

GitHub Actions / build

Expected //end class
Loading

0 comments on commit 9e37d5b

Please sign in to comment.