diff --git a/.github/workflows/code-quality.yml b/.github/workflows/code-quality.yml index e76b6ab2..c3024c32 100644 --- a/.github/workflows/code-quality.yml +++ b/.github/workflows/code-quality.yml @@ -1,8 +1,6 @@ name: Code Quality on: - push: - branches: [main, development, feature/**, bugfix/**, hotfix/**] pull_request: branches: [main, beta, development] diff --git a/.license-overrides.json b/.license-overrides.json new file mode 100644 index 00000000..7dec2249 --- /dev/null +++ b/.license-overrides.json @@ -0,0 +1,3 @@ +{ + "@fortawesome/free-solid-svg-icons": "License is (CC-BY-4.0 AND MIT) — both are approved open-source licenses, compound AND expression not parsed by checker" +} diff --git a/lib/Controller/AangebodenGebruikController.php b/lib/Controller/AangebodenGebruikController.php index fcb0fbf3..3f188c66 100644 --- a/lib/Controller/AangebodenGebruikController.php +++ b/lib/Controller/AangebodenGebruikController.php @@ -85,8 +85,6 @@ public function __construct( * @NoCSRFRequired * @PublicPage * @PublicPage - * - * @SuppressWarnings(PHPMD.ElseExpression) */ public function getGebruiksWhereAfnemer(): JSONResponse { @@ -108,10 +106,8 @@ public function getGebruiksWhereAfnemer(): JSONResponse $result = $this->gebruikSvc->getGebruiksWhereAfnemer($options); // Determine HTTP status code based on whether there's an error. - if (isset($result['error']) === true) { - $statusCode = 500; - } else { $statusCode = 200; + if (isset($result['error']) === true) { } $this->logger->info( @@ -164,8 +160,6 @@ public function getGebruiksWhereAfnemer(): JSONResponse * @NoAdminRequired * @NoCSRFRequired * @PublicPage - * - * @SuppressWarnings(PHPMD.ElseExpression) */ public function getKoppelingenGebruikByUuid(string $uuid): JSONResponse { @@ -202,10 +196,8 @@ public function getKoppelingenGebruikByUuid(string $uuid): JSONResponse ); // Determine HTTP status code based on whether there's an error. - if (isset($result['error']) === true) { - $statusCode = 500; - } else { $statusCode = 200; + if (isset($result['error']) === true) { } $this->logger->info( @@ -258,8 +250,6 @@ public function getKoppelingenGebruikByUuid(string $uuid): JSONResponse * @NoAdminRequired * @NoCSRFRequired * @PublicPage - * - * @SuppressWarnings(PHPMD.ElseExpression) */ public function getAllGebruiksForAmbtenaar(): JSONResponse { @@ -278,11 +268,9 @@ public function getAllGebruiksForAmbtenaar(): JSONResponse $isAmbtenaar = $this->isUserInGroup(groupName: 'ambtenaar'); if ($isAdmin === false && $isAmbtenaar === false) { // Get user ID for logging (may be null if not authenticated). - $user = $this->userSession->getUser(); - if ($user !== null) { - $userId = $user->getUID(); - } else { + $user = $this->userSession->getUser(); $userId = 'null'; + if ($user !== null) { } $this->logger->info( @@ -315,10 +303,8 @@ public function getAllGebruiksForAmbtenaar(): JSONResponse $result = $this->gebruikSvc->getAllGebruiksForAmbtenaar($options); // Determine HTTP status code based on whether there's an error. - if (isset($result['error']) === true) { - $statusCode = 500; - } else { $statusCode = 200; + if (isset($result['error']) === true) { } $this->logger->info( @@ -370,7 +356,6 @@ public function getAllGebruiksForAmbtenaar(): JSONResponse * @PublicPage * @PublicPage * - * @SuppressWarnings(PHPMD.ElseExpression) * @SuppressWarnings(PHPMD.ExcessiveMethodLength) */ public function getSingleGebruikForAmbtenaar(string $gebruikId): JSONResponse @@ -391,11 +376,9 @@ public function getSingleGebruikForAmbtenaar(string $gebruikId): JSONResponse $isAmbtenaar = $this->isUserInGroup(groupName: 'ambtenaar'); if ($isAdmin === false && $isAmbtenaar === false) { // Get user ID for logging (may be null if not authenticated). - $user = $this->userSession->getUser(); - if ($user !== null) { - $userId = $user->getUID(); - } else { + $user = $this->userSession->getUser(); $userId = 'null'; + if ($user !== null) { } $this->logger->info( @@ -432,10 +415,8 @@ public function getSingleGebruikForAmbtenaar(string $gebruikId): JSONResponse ); // Determine HTTP status code based on whether there's an error. - if (isset($result['error']) === true) { - $statusCode = 500; - } else { $statusCode = 200; + if (isset($result['error']) === true) { } $this->logger->info( @@ -548,8 +529,6 @@ private function isUserInGroup(string $groupName): bool * @NoCSRFRequired * @PublicPage * @PublicPage - * - * @SuppressWarnings(PHPMD.ElseExpression) */ public function getGebruiksWhereDeelnemers(): JSONResponse { @@ -571,10 +550,8 @@ public function getGebruiksWhereDeelnemers(): JSONResponse $result = $this->gebruikSvc->getGebruiksWhereDeelnemers($options); // Determine appropriate HTTP status code. - if ($result['success'] === true) { - $statusCode = 200; - } else { $statusCode = 500; + if ($result['success'] === true) { } $this->logger->info( @@ -625,8 +602,6 @@ public function getGebruiksWhereDeelnemers(): JSONResponse * @NoCSRFRequired * @PublicPage * @PublicPage - * - * @SuppressWarnings(PHPMD.ElseExpression) */ public function setGebruikSelfToActiveOrg(string $gebruikId): JSONResponse { @@ -673,14 +648,13 @@ function ($key) { ); // Determine appropriate HTTP status code. + $statusCode = 500; if ($result['success'] === true) { $statusCode = 200; } else if ($result['error'] === 'Gebruik object not found') { $statusCode = 404; } else if (strpos(haystack: ($result['error'] ?? ''), needle: 'Operation not allowed') !== false) { $statusCode = 403; - } else { - $statusCode = 500; } $this->logger->info( @@ -735,8 +709,6 @@ function ($key) { * @NoCSRFRequired * @PublicPage * @PublicPage - * - * @SuppressWarnings(PHPMD.ElseExpression) */ public function deleteGebruikAsAfnemer(string $gebruikId): JSONResponse { @@ -783,14 +755,13 @@ function ($key) { ); // Determine appropriate HTTP status code. + $statusCode = 500; if ($result['success'] === true) { $statusCode = 200; } else if ($result['error'] === 'Gebruik object not found') { $statusCode = 404; } else if (strpos(haystack: ($result['error'] ?? ''), needle: 'Operation not allowed') !== false) { $statusCode = 403; - } else { - $statusCode = 500; } $this->logger->info( diff --git a/lib/Controller/ContactpersonenController.php b/lib/Controller/ContactpersonenController.php index 32ce5cd6..07fc783f 100644 --- a/lib/Controller/ContactpersonenController.php +++ b/lib/Controller/ContactpersonenController.php @@ -264,7 +264,6 @@ function ($group) { * @SuppressWarnings(PHPMD.CyclomaticComplexity) * @SuppressWarnings(PHPMD.NPathComplexity) * @SuppressWarnings(PHPMD.ExcessiveMethodLength) - * @SuppressWarnings(PHPMD.ElseExpression) */ public function convertToUser(string $contactpersoonId): JSONResponse { @@ -402,11 +401,9 @@ public function convertToUser(string $contactpersoonId): JSONResponse $contactpersoonObject->setObject($contactData); // Debug logging to understand data types before save. - $achternaamValue = $contactData['achternaam'] ?? 'not set'; - if (isset($contactData['achternaam']) === true) { - $achternaamType = gettype($contactData['achternaam']); - } else { + $achternaamValue = $contactData['achternaam'] ?? 'not set'; $achternaamType = 'not set'; + if (isset($contactData['achternaam']) === true) { } $this->logger->info( @@ -580,7 +577,6 @@ public function changePassword(string $username, string $newPassword): JSONRespo * * @SuppressWarnings(PHPMD.CyclomaticComplexity) * @SuppressWarnings(PHPMD.ExcessiveMethodLength) - * @SuppressWarnings(PHPMD.ElseExpression) */ public function updateUserGroups(string $username, array $groups=[]): JSONResponse { @@ -633,18 +629,7 @@ public function updateUserGroups(string $username, array $groups=[]): JSONRespon $groupsToAdd = array_diff($validGroups, $curCatalogGroups); foreach ($groupsToAdd as $groupName) { $group = $this->groupManager->get($groupName); - if ($group !== null) { - if ($group->inGroup($user) === false) { - $group->addUser($user); - $this->logger->info( - 'Added user to group', - [ - 'username' => $username, - 'group' => $groupName, - ] - ); - } - } else { + if ($group === null) { $this->logger->warning( 'Group does not exist, skipping', [ @@ -652,6 +637,18 @@ public function updateUserGroups(string $username, array $groups=[]): JSONRespon 'group' => $groupName, ] ); + continue; + } + + if ($group->inGroup($user) === false) { + $group->addUser($user); + $this->logger->info( + 'Added user to group', + [ + 'username' => $username, + 'group' => $groupName, + ] + ); } }//end foreach @@ -1076,28 +1073,20 @@ public function enableUser(string $contactpersoonId): JSONResponse * * @NoAdminRequired * @NoCSRFRequired - * - * @SuppressWarnings(PHPMD.ElseExpression) */ public function testBulkUserInfo(): JSONResponse { try { - if ($this->contactSvc !== null) { - $objectServiceAvail = 'available'; - } else { $objectServiceAvail = 'null'; + if ($this->contactSvc !== null) { } - if ($this->userManager !== null) { - $userManagerAvail = 'available'; - } else { $userManagerAvail = 'null'; + if ($this->userManager !== null) { } - if ($this->groupManager !== null) { - $groupManagerAvail = 'available'; - } else { $groupManagerAvail = 'null'; + if ($this->groupManager !== null) { } $this->logger->info( diff --git a/lib/Controller/SettingsController.php b/lib/Controller/SettingsController.php index 5264e523..9491e29a 100644 --- a/lib/Controller/SettingsController.php +++ b/lib/Controller/SettingsController.php @@ -541,8 +541,6 @@ public function status(): JSONResponse * @return JSONResponse JSON response containing the auto-configuration results * * @NoCSRFRequired - * - * @SuppressWarnings(PHPMD.ElseExpression) */ public function autoConfigure(): JSONResponse { @@ -556,14 +554,14 @@ public function autoConfigure(): JSONResponse 'configuration' => $result, ] ); - } else { - return new JSONResponse( - [ - 'success' => false, - 'message' => 'No matching registers or schemas found for auto-configuration', - ] - ); } + + return new JSONResponse( + [ + 'success' => false, + 'message' => 'No matching registers or schemas found for auto-configuration', + ] + ); } catch (\Exception $e) { $this->logger->error( 'Failed to auto-configure settings', @@ -703,8 +701,6 @@ public function getSyncStatus(int $minutesBack=10): JSONResponse * @return JSONResponse JSON response containing sync results * * @NoCSRFRequired - * - * @SuppressWarnings(PHPMD.ElseExpression) */ public function performSync(int $minutesBack=0): JSONResponse { @@ -726,16 +722,15 @@ public function performSync(int $minutesBack=0): JSONResponse 'isOptimized' => true, ] ); - } else { - // For incremental sync, use the original method. - $result = $this->orgSyncSvc->performManualSync($minutesBack); - - if ($result['success'] === true) { - return new JSONResponse($result); - } else { - return new JSONResponse($result, 500); - } }//end if + + // For incremental sync, use the original method. + $result = $this->orgSyncSvc->performManualSync($minutesBack); + + if ($result['success'] === true) { + } + + return new JSONResponse($result, 500); } catch (\Exception $e) { $this->logger->error( 'Manual sync failed', @@ -856,8 +851,6 @@ public function getVersionInfo(): JSONResponse * @return JSONResponse JSON response containing reset results. * * @NoCSRFRequired - * - * @SuppressWarnings(PHPMD.ElseExpression) */ public function resetAutoConfig(): JSONResponse { @@ -868,10 +861,9 @@ public function resetAutoConfig(): JSONResponse $result = $this->settingsService->resetAutoConfiguration($resetConfiguration); if ($result['success'] === true) { - return new JSONResponse($result); - } else { - return new JSONResponse($result, 400); } + + return new JSONResponse($result, 400); } catch (\Exception $e) { return new JSONResponse( [ @@ -929,8 +921,6 @@ public function clearCache(): JSONResponse * @return JSONResponse JSON response containing import results. * * @NoCSRFRequired - * - * @SuppressWarnings(PHPMD.ElseExpression) */ public function manualImport(): JSONResponse { @@ -959,10 +949,9 @@ public function manualImport(): JSONResponse $result['timestamp'] = time(); if ($result['success'] === true) { - return new JSONResponse($result); - } else { - return new JSONResponse($result, 400); } + + return new JSONResponse($result, 400); } catch (\Exception $e) { $this->logger->error( 'SettingsController: Manual import failed', @@ -1061,8 +1050,6 @@ public function forceUpdate(): JSONResponse * @return JSONResponse JSON response containing consolidated results * * @NoCSRFRequired - * - * @SuppressWarnings(PHPMD.ElseExpression) */ public function consolidatedAutoConfigure(): JSONResponse { @@ -1074,16 +1061,12 @@ public function consolidatedAutoConfigure(): JSONResponse $results = $this->settingsService->performConsolidatedAutoConfiguration($force); // Determine HTTP status based on results. + $httpStatus = 200; if ($results['success'] === false) { // Multi-status or Server Error. + $httpStatus = 500; if (empty($results['errors']) === false) { - $httpStatus = 207; - } else { - $httpStatus = 500; } - } else { - // Success. - $httpStatus = 200; } return new JSONResponse($results, $httpStatus); @@ -1288,7 +1271,6 @@ public function render(): string * @SuppressWarnings(PHPMD.CyclomaticComplexity) * @SuppressWarnings(PHPMD.ExcessiveMethodLength) * @SuppressWarnings(PHPMD.Superglobals) - * @SuppressWarnings(PHPMD.ElseExpression) */ public function importArchiMate(): JSONResponse { @@ -1353,10 +1335,8 @@ public function importArchiMate(): JSONResponse if ($hasUploadedFiles === true || $hasFilesArray === true) { // Use $_FILES as fallback if getUploadedFile doesn't work. - if ($uploadedFiles !== null) { - $fileData = $uploadedFiles; - } else { $fileData = $filesArray; + if ($uploadedFiles !== null) { } // Handle file upload. @@ -1374,10 +1354,8 @@ public function importArchiMate(): JSONResponse $this->logger->info('File upload detected.', ['options' => $options]); } else if ($data !== null && isset($data['file_path']) === true) { // Handle file path from JSON payload. - if (file_exists($data['file_path']) === true) { - $fileSize = filesize($data['file_path']); - } else { $fileSize = 0; + if (file_exists($data['file_path']) === true) { } $options = [ @@ -1392,7 +1370,9 @@ public function importArchiMate(): JSONResponse ]; $this->logger->info('JSON payload detected.', ['options' => $options]); - } else { + }//end if + + if (isset($options) === false) { $this->logger->error( 'No file uploaded or file path provided — DETAILED DEBUG', [ @@ -1429,12 +1409,11 @@ public function importArchiMate(): JSONResponse // OPTIMIZATION: Use optimized method if available or if explicitly requested. $useOptimized = $this->request->getParam('useOptimized', 'true') === 'true'; $hasOptimized = method_exists($this->archiMateService, 'importArchiMateFileFromPathOptimized'); + $this->logger->info('Using STANDARD ArchiMate import method.'); + $result = $this->archiMateService->importArchiMateFileFromPath($options); if ($useOptimized === true && $hasOptimized === true) { $this->logger->info('Using OPTIMIZED ArchiMate import method.'); $result = $this->archiMateService->importArchiMateFileFromPathOptimized($options); - } else { - $this->logger->info('Using STANDARD ArchiMate import method.'); - $result = $this->archiMateService->importArchiMateFileFromPath($options); } return new JSONResponse($result); @@ -2002,8 +1981,6 @@ public function getEmailTemplate(string $templateName): JSONResponse * * @NoAdminRequired * @NoCSRFRequired - * - * @SuppressWarnings(PHPMD.ElseExpression) */ public function updateEmailTemplate(string $templateName): JSONResponse { @@ -2026,10 +2003,8 @@ public function updateEmailTemplate(string $templateName): JSONResponse templateContent: $templateContent ); - if ($success === true) { - $updateMsg = "Template {$templateName} updated successfully"; - } else { $updateMsg = "Failed to update template {$templateName}"; + if ($success === true) { } return new JSONResponse( @@ -2496,18 +2471,14 @@ public function killArchiMateImport(): JSONResponse * @NoCSRFRequired * * @return JSONResponse Cancellation result - * - * @SuppressWarnings(PHPMD.ElseExpression) */ public function cancelArchiMateImport(): JSONResponse { try { $result = $this->settingsService->cancelArchiMateImport(); - if ($result['cancelled'] === true) { - $message = 'ArchiMate import cancelled successfully'; - } else { $message = 'ArchiMate import cancellation failed'; + if ($result['cancelled'] === true) { } return new JSONResponse( @@ -3145,8 +3116,6 @@ private function getHttpStatusForErrorMessage(string $message): int * @NoCSRFRequired * * @return JSONResponse The sync results - * - * @SuppressWarnings(PHPMD.ElseExpression) */ public function syncOrganisations(): JSONResponse { @@ -3165,10 +3134,8 @@ public function syncOrganisations(): JSONResponse // Call the settings service method. $result = $this->settingsService->syncOrganisationsToVoorzieningenOptimized($options); - if ($result['success'] === true) { - $statusCode = 200; - } else { $statusCode = 500; + if ($result['success'] === true) { } $this->logger->info( @@ -3298,8 +3265,6 @@ public function getCronjobConfig(): JSONResponse * @NoCSRFRequired * * @return JSONResponse Update result - * - * @SuppressWarnings(PHPMD.ElseExpression) */ public function updateCronjobConfig(): JSONResponse { @@ -3307,10 +3272,8 @@ public function updateCronjobConfig(): JSONResponse $data = $this->request->getParams(); $result = $this->settingsService->updateCronjobConfig($data); - if ($result['success'] === true) { - $statusCode = 200; - } else { $statusCode = 400; + if ($result['success'] === true) { } return new JSONResponse($result, $statusCode); diff --git a/lib/EventListener/OpenRegisterEventsDebugListener.php b/lib/EventListener/OpenRegisterEventsDebugListener.php index 2f0e8ac1..28b24a4d 100644 --- a/lib/EventListener/OpenRegisterEventsDebugListener.php +++ b/lib/EventListener/OpenRegisterEventsDebugListener.php @@ -179,7 +179,6 @@ private function getEventTypeName(string $eventClass): string * * @SuppressWarnings(PHPMD.CyclomaticComplexity) * @SuppressWarnings(PHPMD.ExcessiveMethodLength) - * @SuppressWarnings(PHPMD.ElseExpression) */ private function extractEventData(Event $event): array { @@ -207,10 +206,8 @@ private function extractEventData(Event $event): array $newObject = $event->getNewObject(); $oldObject = $event->getOldObject(); - if ($oldObject !== null) { - $oldObjectData = $this->getSafeObjectData(objectData: $oldObject->getObject()); - } else { $oldObjectData = null; + if ($oldObject !== null) { } $data = array_merge( @@ -361,11 +358,12 @@ private function extractEventData(Event $event): array 'organisationTitle' => $organisation->getName(), ] ); - // Unknown event type. - } else { + }//end if + + if (isset($data['eventType']) === false) { $data['eventType'] = 'Unknown'; $data['note'] = 'Event type not specifically handled by SoftwareCatalog debug listener'; - }//end if + } return $data; diff --git a/lib/EventListener/SoftwareCatalogEventListener.php b/lib/EventListener/SoftwareCatalogEventListener.php index ed3fd571..cba76e64 100644 --- a/lib/EventListener/SoftwareCatalogEventListener.php +++ b/lib/EventListener/SoftwareCatalogEventListener.php @@ -68,8 +68,6 @@ public function __construct() * @param Event $event The event to handle * * @return void - * - * @SuppressWarnings(PHPMD.ElseExpression) */ public function handle(Event $event): void { @@ -325,7 +323,6 @@ private function handleObjectCreated( * @SuppressWarnings(PHPMD.CyclomaticComplexity) * @SuppressWarnings(PHPMD.NPathComplexity) * @SuppressWarnings(PHPMD.ExcessiveMethodLength) - * @SuppressWarnings(PHPMD.ElseExpression) */ private function handleObjectUpdated( ObjectUpdatedEvent $event, @@ -388,10 +385,8 @@ private function handleObjectUpdated( $objectData = $object->getObject(); $status = strtolower($objectData['status'] ?? ''); - if ($oldObject !== null) { - $oldStatus = strtolower($oldObject->getObject()['status'] ?? ''); - } else { $oldStatus = ''; + if ($oldObject !== null) { } $logger->debug( @@ -468,7 +463,9 @@ private function handleObjectUpdated( ] ); }//end try - } else { + }//end if + + if (in_array(needle: $status, haystack: ['actief', 'active']) !== true || $status === $oldStatus) { $logger->debug( 'SoftwareCatalog: Skipping non-active organization update', [ @@ -477,7 +474,7 @@ private function handleObjectUpdated( 'schemaId' => $objectSchemaId, ] ); - }//end if + } return; }//end if diff --git a/lib/Service/AanbodService.php b/lib/Service/AanbodService.php index 4b53a309..4187270a 100644 --- a/lib/Service/AanbodService.php +++ b/lib/Service/AanbodService.php @@ -44,7 +44,6 @@ * @link https://github.com/ConductionNL/SoftwareCatalog * * @SuppressWarnings(PHPMD.ExcessiveClassComplexity) - * @SuppressWarnings(PHPMD.ElseExpression) * @SuppressWarnings(PHPMD.CyclomaticComplexity) * @SuppressWarnings(PHPMD.NPathComplexity) * @SuppressWarnings(PHPMD.ExcessiveMethodLength) @@ -191,10 +190,8 @@ public function getAanbod(array $options=[]): array foreach ($searchResult['results'] ?? [] as $result) { // Use jsonSerialize() instead of getObject() to include @self metadata. // GetObject() only returns raw object data without @self.organisation. - if (is_array($result) === true) { - $resultData = $result; - } else { $resultData = $result->jsonSerialize(); + if (is_array($result) === true) { } $selfOrg = $resultData['@self']['organisation'] ?? null; @@ -231,19 +228,15 @@ public function getAanbod(array $options=[]): array $requestedLimit = $options['_limit'] ?? $options['limit'] ?? 20; $requestedPage = $options['_page'] ?? 1; - if (isset($options['_offset']) === true) { - $requestedOffset = $options['_offset']; - } else { $requestedOffset = (($requestedPage - 1) * $requestedLimit); + if (isset($options['_offset']) === true) { } $totalFiltered = count($allResults); $paginatedResults = array_slice($allResults, $requestedOffset, $requestedLimit); - if ($requestedLimit > 0) { - $totalPages = (int) ceil($totalFiltered / $requestedLimit); - } else { $totalPages = 1; + if ($requestedLimit > 0) { } return [ diff --git a/lib/Service/AangebodenGebruikService.php b/lib/Service/AangebodenGebruikService.php index 4f8c8d6a..eb5d14d3 100644 --- a/lib/Service/AangebodenGebruikService.php +++ b/lib/Service/AangebodenGebruikService.php @@ -44,7 +44,6 @@ * * @SuppressWarnings(PHPMD.ExcessiveClassLength) * @SuppressWarnings(PHPMD.ExcessiveClassComplexity) - * @SuppressWarnings(PHPMD.ElseExpression) * @SuppressWarnings(PHPMD.CyclomaticComplexity) * @SuppressWarnings(PHPMD.NPathComplexity) * @SuppressWarnings(PHPMD.ExcessiveMethodLength) @@ -149,11 +148,9 @@ public function getGebruiksWhereAfnemer(array $options=[]): array $requestedPage = $options['_page'] ?? 1; // Calculate offset from page or use explicit offset. + $requestedOffset = ($requestedPage - 1) * $requestedLimit; if (isset($options['_offset']) === true) { $requestedOffset = $options['_offset']; - } else { - // Calculate offset from page number. - $requestedOffset = ($requestedPage - 1) * $requestedLimit; } // Fetch a large batch for filtering (since we filter post-fetch). @@ -206,10 +203,8 @@ public function getGebruiksWhereAfnemer(array $options=[]): array $filteredResults = []; foreach ($searchResult['results'] ?? [] as $result) { // Convert ObjectEntity to array if needed. - if (is_array(value: $result) === true) { - $resultData = $result; - } else { $resultData = $result->getObject(); + if (is_array(value: $result) === true) { } $selfOrg = $resultData['@self']['organisation'] ?? null; @@ -235,16 +230,12 @@ public function getGebruiksWhereAfnemer(array $options=[]): array $paginatedResults = array_slice(array: $filteredResults, offset: $requestedOffset, length: $requestedLimit); // Calculate pagination metadata. - if ($requestedLimit > 0) { - $totalPages = (int) ceil(num: $totalFiltered / $requestedLimit); - } else { $totalPages = 1; + if ($requestedLimit > 0) { } - if ($requestedOffset > 0) { - $currentPage = (int) floor(num: $requestedOffset / $requestedLimit) + 1; - } else { $currentPage = $requestedPage; + if ($requestedOffset > 0) { } // Build next/previous links. @@ -280,10 +271,9 @@ public function getGebruiksWhereAfnemer(array $options=[]): array $searchResult['page'] = $currentPage; $searchResult['limit'] = $requestedLimit; $searchResult['offset'] = $requestedOffset; + unset($searchResult['next']); if ($nextLink !== null) { $searchResult['next'] = $nextLink; - } else { - unset($searchResult['next']); } if ($prevLink !== null) { @@ -412,10 +402,8 @@ public function getKoppelingenGebruikByUuid(string $uuid, array $options=[], boo } // Get organization filter if provided (for ambtenaar). - if ($isAmbtenaar === true && isset($options['organisation']) === true) { - $organisationFilter = $options['organisation']; - } else { $organisationFilter = null; + if ($isAmbtenaar === true && isset($options['organisation']) === true) { } // Build search query using ObjectService's buildSearchQuery. @@ -478,7 +466,9 @@ public function getKoppelingenGebruikByUuid(string $uuid, array $options=[], boo _multitenancy: false, deleted: false ); - } else { + }//end if + + if ($isOrganisationUuid === false) { // For suite/module UUIDs, use 'uses' parameter to filter by relations. // Add organization filter if provided. if ($organisationFilter !== null) { @@ -823,10 +813,8 @@ public function getGebruiksWhereDeelnemers(array $options=[]): array // Process and add to results. foreach ($gebruikItems as $gebruik) { - if (is_array(value: $gebruik) === true) { - $gebruikData = $gebruik; - } else { $gebruikData = $gebruik->jsonSerialize(); + if (is_array(value: $gebruik) === true) { } $gebruikData['_filter_type'] = 'deelnemers'; @@ -1358,10 +1346,8 @@ private function getApplicationsOwnedByOrganisation( ); foreach ($suites as $suite) { - if (is_array(value: $suite) === true) { - $suiteData = $suite; - } else { $suiteData = $suite->getObject(); + if (is_array(value: $suite) === true) { } $appUuids[] = $suiteData['uuid'] ?? $suiteData['id'] ?? null; @@ -1386,10 +1372,8 @@ private function getApplicationsOwnedByOrganisation( ); foreach ($modules as $module) { - if (is_array(value: $module) === true) { - $moduleData = $module; - } else { $moduleData = $module->getObject(); + if (is_array(value: $module) === true) { } $appUuids[] = $moduleData['uuid'] ?? $moduleData['id'] ?? null; diff --git a/lib/Service/ArchiMateExportService.php b/lib/Service/ArchiMateExportService.php index e1c12c67..49cabefe 100644 --- a/lib/Service/ArchiMateExportService.php +++ b/lib/Service/ArchiMateExportService.php @@ -36,7 +36,6 @@ * @SuppressWarnings(PHPMD.ExcessiveClassComplexity) * @SuppressWarnings(PHPMD.TooManyMethods) * @SuppressWarnings(PHPMD.TooManyPublicMethods) - * @SuppressWarnings(PHPMD.ElseExpression) * @SuppressWarnings(PHPMD.CyclomaticComplexity) * @SuppressWarnings(PHPMD.NPathComplexity) * @SuppressWarnings(PHPMD.ExcessiveMethodLength) @@ -344,10 +343,8 @@ private function getNamespaceUri(\SimpleXMLElement $xml, string $prefix): string return $wellKnown[$prefix]; } - if ($xml->getDocNamespaces(true) !== false) { - $namespaces = $xml->getDocNamespaces(true); - } else { $namespaces = []; + if ($xml->getDocNamespaces(true) !== false) { } return $namespaces[$prefix] ?? ''; @@ -542,16 +539,12 @@ private function addViewToFolder(\SimpleXMLElement $folder, array $view): void // DEBUG: Check if this is our target view with nodes. $targetId = 'id-1c197dc3-71e5-40dc-8f5d-a96e983b41af'; if (isset($viewData['_identifier']) === true && $viewData['_identifier'] === $targetId) { - if (is_array($viewData['node'] ?? null) === true) { - $nodeCountValue = count($viewData['node']); - } else { $nodeCountValue = 0; + if (is_array($viewData['node'] ?? null) === true) { } - if (isset($viewData['node'][0]) === true) { - $nodeSampleValue = $viewData['node'][0]; - } else { $nodeSampleValue = 'NO FIRST NODE'; + if (isset($viewData['node'][0]) === true) { } $this->logger->debug( @@ -569,16 +562,12 @@ private function addViewToFolder(\SimpleXMLElement $folder, array $view): void ); }//end if - if (is_array($viewData['node'] ?? null) === true) { - $nodeCountValue = count($viewData['node']); - } else { $nodeCountValue = 0; + if (is_array($viewData['node'] ?? null) === true) { } - if (is_array($viewData['connection'] ?? null) === true) { - $connectionCountValue = count($viewData['connection']); - } else { $connectionCountValue = 0; + if (is_array($viewData['connection'] ?? null) === true) { } $this->logger->debug( @@ -616,32 +605,26 @@ private function extractViewData(array $view): ?array { // Format 1: OpenRegister object format with properties.xml_data. if (isset($view['properties']['xml_data']) === true) { - if (is_string($view['properties']['xml_data']) === true) { - $xmlData = json_decode($view['properties']['xml_data'], true); - } else { $xmlData = $view['properties']['xml_data']; + if (is_string($view['properties']['xml_data']) === true) { } if (is_array($xmlData) === true) { - return $xmlData; - } else { - return null; } + + return null; } // Format 2: Object with xml_data field (from database). if (isset($view['xml_data']) === true) { - if (is_string($view['xml_data']) === true) { - $xmlData = json_decode($view['xml_data'], true); - } else { $xmlData = $view['xml_data']; + if (is_string($view['xml_data']) === true) { } if (is_array($xmlData) === true) { - return $xmlData; - } else { - return null; } + + return null; } // Format 3: Direct XML data (from convertFromOpenRegisterObjects). @@ -741,10 +724,8 @@ private function addObjectToFolder(\SimpleXMLElement $folder, array $object, str // 3. Raw object data as fallback. if (isset($object['properties']['xml_data']) === true) { // Format 1: OpenRegister object format. - if (is_string($object['properties']['xml_data']) === true) { - $xmlData = json_decode($object['properties']['xml_data'], true); - } else { $xmlData = $object['properties']['xml_data']; + if (is_string($object['properties']['xml_data']) === true) { } if (is_array($xmlData) === true) { @@ -752,10 +733,8 @@ private function addObjectToFolder(\SimpleXMLElement $folder, array $object, str } } else if (isset($object['xml_data']) === true) { // Format 2: Object with xml_data field (from database). - if (is_string($object['xml_data']) === true) { - $xmlData = json_decode($object['xml_data'], true); - } else { $xmlData = $object['xml_data']; + if (is_string($object['xml_data']) === true) { } if (is_array($xmlData) === true) { @@ -2566,10 +2545,8 @@ private function buildModuleLookupMaps(array $gebruikData, array $modulesData): } foreach ($refComps as $refComp) { - if (is_string($refComp) === true) { - $refCompUuid = $refComp; - } else { $refCompUuid = ($refComp['id'] ?? $refComp['uuid'] ?? null); + if (is_string($refComp) === true) { } if ($refCompUuid === null) { @@ -2651,11 +2628,9 @@ private function generateApplicationElements( string $bronPropDefId, string $prefix='' ): array { - $elements = []; - if ($prefix !== '') { - $idPrefix = 'id-swc-'.$prefix.'-app-'; - } else { + $elements = []; $idPrefix = 'id-swc-app-'; + if ($prefix !== '') { } foreach ($moduleRefMap as $moduleId => $refCompIds) { @@ -2689,17 +2664,13 @@ private function generateSpecializationRelationships( string $bronPropDefId, string $prefix='' ): array { - $relationships = []; - if ($prefix !== '') { - $appIdPrefix = 'id-swc-'.$prefix.'-app-'; - } else { + $relationships = []; $appIdPrefix = 'id-swc-app-'; + if ($prefix !== '') { } - if ($prefix !== '') { - $relIdPrefix = 'id-swc-'.$prefix.'-rel-'; - } else { $relIdPrefix = 'id-swc-rel-'; + if ($prefix !== '') { } foreach ($moduleRefMap as $moduleId => $refCompIds) { @@ -2854,10 +2825,9 @@ private function getViewSwcTitle(array $viewData): ?string $propName = $prop['_name'] ?? $prop['name'] ?? ''; if (is_string($propName) === true && stripos($propName, 'Titel view SWC') !== false && $value !== null) { if (is_string($value) === true) { - return $value; - } else { - return null; } + + return null; } } diff --git a/lib/Service/ArchiMateImportService.php b/lib/Service/ArchiMateImportService.php index ff6a2190..93a4d795 100644 --- a/lib/Service/ArchiMateImportService.php +++ b/lib/Service/ArchiMateImportService.php @@ -47,7 +47,6 @@ * @SuppressWarnings(PHPMD.ExcessiveClassComplexity) * @SuppressWarnings(PHPMD.CouplingBetweenObjects) * @SuppressWarnings(PHPMD.TooManyMethods) - * @SuppressWarnings(PHPMD.ElseExpression) * @SuppressWarnings(PHPMD.CyclomaticComplexity) * @SuppressWarnings(PHPMD.NPathComplexity) * @SuppressWarnings(PHPMD.ExcessiveMethodLength) @@ -204,10 +203,8 @@ public function xmlToArray(\SimpleXMLElement $xml): array $name = (string) $attrName; $value = (string) $attrValue; // OPTIMIZATION: Only create underscored key if needed (skip str_replace for simple names). - if ((strpos($name, ':') !== false)) { - $underscoredKey = '_'.str_replace(':', '__', $name); - } else { $underscoredKey = '_'.$name; + if ((strpos($name, ':') !== false)) { } $result[$underscoredKey] = $value; @@ -504,13 +501,11 @@ public function importArchiMateFileFromPath(array $options=[]): array $statistics = $this->calculateObjectStatistics(normalizedData: $normalizedData, savedObjects: $savedObjects); // Calculate performance metrics. - $created = $statistics['summary']['total_objects_created']; - $updated = $statistics['summary']['total_objects_updated']; - $totalObjects = $created + $updated; - if ($totalObjects > 0) { - $itemsPerSecond = $totalObjects / $totalTime; - } else { + $created = $statistics['summary']['total_objects_created']; + $updated = $statistics['summary']['total_objects_updated']; + $totalObjects = $created + $updated; $itemsPerSecond = 0; + if ($totalObjects > 0) { } // Extract detailed error information from statistics. @@ -1271,14 +1266,12 @@ private function saveObjectsToDatabase(array $objects): array // DEBUG: Log basic object info before sending to ObjectService. // Find first element with gemmaType for debugging. - $gemmaElements = array_filter( + $gemmaElements = array_filter( $objects, fn($o) => ($o['section'] ?? '') === 'element' && empty($o['gemmaType']) === false ); - if (empty($gemmaElements) === false) { - $sampleGemmaElem = array_values($gemmaElements)[0]; - } else { $sampleGemmaElem = null; + if (empty($gemmaElements) === false) { } $this->logger->debug( @@ -1344,10 +1337,8 @@ private function saveObjectsToDatabase(array $objects): array try { // Save this schema group with the specific schema ID. // PERFORMANCE: Disabled validation and events for bulk import (like CSV import pattern). - if ($schemaId !== 'unknown') { - $schemaValue = (int) $schemaId; - } else { $schemaValue = null; + if ($schemaId !== 'unknown') { } $saveResult = $objectService->saveObjects( @@ -1419,14 +1410,12 @@ private function saveObjectsToDatabase(array $objects): array // Database save completed. // Store timing breakdown for performance metrics. // FIX: Use aggregatedStats counts instead of $result which may be empty from bulk operations. - $savedCount = count($aggregatedStats['saved'] ?? []); - $updatedCount = count($aggregatedStats['updated'] ?? []); - $unchangedCount = count($aggregatedStats['unchanged'] ?? []); - $totalSavedCount = $savedCount + $updatedCount + $unchangedCount; - if ($totalSavedCount > 0) { - $objectsSavedValue = $totalSavedCount; - } else { + $savedCount = count($aggregatedStats['saved'] ?? []); + $updatedCount = count($aggregatedStats['updated'] ?? []); + $unchangedCount = count($aggregatedStats['unchanged'] ?? []); + $totalSavedCount = $savedCount + $updatedCount + $unchangedCount; $objectsSavedValue = count($objects); + if ($totalSavedCount > 0) { } $this->lastSaveTiming = [ @@ -1564,10 +1553,8 @@ private function saveObjectsDirectToService(array $objects, ObjectService $objec $allInvalid = []; foreach ($schemaGroups as $schemaId => $schemaObjects) { - if ($schemaId !== 'unknown') { - $schemaValue = (int) $schemaId; - } else { $schemaValue = null; + if ($schemaId !== 'unknown') { } $saveResult = $objectService->saveObjects( @@ -1672,10 +1659,8 @@ private function saveObjectsInParallelBatches(array $objects, ObjectService $obj $chunkInputCount = count($chunk); try { - if (self::PERFORMANCE_OPTIMIZATIONS['disable_rbac'] === true) { - $_rbacValue = false; - } else { $_rbacValue = true; + if (self::PERFORMANCE_OPTIMIZATIONS['disable_rbac'] === true) { } $saveResult = $objectService->saveObjects( @@ -1764,10 +1749,8 @@ private function saveObjectsInParallelBatches(array $objects, ObjectService $obj private function saveObjectsInSingleBatch(array $objects, ObjectService $objectService, int $registerId): array { // Using single batch processing. - if (self::PERFORMANCE_OPTIMIZATIONS['disable_rbac'] === true) { - $_rbacValue = false; - } else { $_rbacValue = true; + if (self::PERFORMANCE_OPTIMIZATIONS['disable_rbac'] === true) { } $saveResult = $objectService->saveObjects( @@ -2015,10 +1998,8 @@ private function getAmefRegisterId(): ?int // Fallback to legacy individual app config keys if not present in JSON. if ($rawRegisterId === null || $rawRegisterId === '') { - if ($this->config->getValueString('softwarecatalog', 'amef_register', '') !== '') { - $rawRegisterId = $this->config->getValueString('softwarecatalog', 'amef_register', ''); - } else { $rawRegisterId = $this->config->getValueString('softwarecatalog', 'amef_register_id', ''); + if ($this->config->getValueString('softwarecatalog', 'amef_register', '') !== '') { } } @@ -2026,10 +2007,9 @@ private function getAmefRegisterId(): ?int if ($rawRegisterId !== null && $rawRegisterId !== '' && is_numeric((string) $rawRegisterId) === true) { $registerId = (int) $rawRegisterId; if ($registerId > 0) { - return $registerId; - } else { - return null; } + + return null; } return null; @@ -2091,10 +2071,8 @@ private function getAmefSchemaIdForType(string $archiMateType): ?int // Fallback to legacy individual app config keys if not present in JSON. foreach ($candidates as $key) { - if ($this->config->getValueString('softwarecatalog', 'amef_'.$key, '') !== '') { - $raw = $this->config->getValueString('softwarecatalog', 'amef_'.$key, ''); - } else { $raw = $this->config->getValueString('softwarecatalog', $key, ''); + if ($this->config->getValueString('softwarecatalog', 'amef_'.$key, '') !== '') { } if ($raw !== '' && is_numeric((string) $raw) === true) { @@ -2687,17 +2665,13 @@ private function extractIdentifierByPattern(array $item, array $pattern): ?strin switch ($type) { case 'direct': if (is_string($current) === true) { - return $current; - } else { - return null; } + return null; case 'value': if (is_array($current) === true && isset($current['_value']) === true) { - return (string) $current['_value']; - } else { - return null; } + return null; case 'array_search': if (is_array($current) === true) { @@ -2906,28 +2880,20 @@ private function extractViewNodesRecursively($nodeData, array $elementsLookup=[] } // Create viewNode with standardized structure. - if (isset($node['_attributes']['x']) === true) { - $xValue = (int) $node['_attributes']['x']; - } else { $xValue = 0; + if (isset($node['_attributes']['x']) === true) { } - if (isset($node['_attributes']['y']) === true) { - $yValue = (int) $node['_attributes']['y']; - } else { $yValue = 0; + if (isset($node['_attributes']['y']) === true) { } - if (isset($node['_attributes']['w']) === true) { - $widthValue = (int) $node['_attributes']['w']; - } else { $widthValue = 100; + if (isset($node['_attributes']['w']) === true) { } - if (isset($node['_attributes']['h']) === true) { - $heightValue = (int) $node['_attributes']['h']; - } else { $heightValue = 50; + if (isset($node['_attributes']['h']) === true) { } $viewNode = [ @@ -3119,28 +3085,20 @@ private function extractNodesRecursively($nodeData, array $elementsLookup=[]): a foreach ($nodeData as $node) { if (isset($node['_attributes']) === true) { - if (isset($node['_attributes']['x']) === true) { - $xValue = (int) $node['_attributes']['x']; - } else { $xValue = null; + if (isset($node['_attributes']['x']) === true) { } - if (isset($node['_attributes']['y']) === true) { - $yValue = (int) $node['_attributes']['y']; - } else { $yValue = null; + if (isset($node['_attributes']['y']) === true) { } - if (isset($node['_attributes']['w']) === true) { - $wValue = (int) $node['_attributes']['w']; - } else { $wValue = null; + if (isset($node['_attributes']['w']) === true) { } - if (isset($node['_attributes']['h']) === true) { - $hValue = (int) $node['_attributes']['h']; - } else { $hValue = null; + if (isset($node['_attributes']['h']) === true) { } $processedNode = [ @@ -3332,22 +3290,16 @@ private function applyNodeStyle(array &$viewNode, array $style): void // Extract fillColor. if (isset($style['fillColor']['_attributes']) === true) { $fillColor = $style['fillColor']['_attributes']; + $r = 255; if (isset($fillColor['r']) === true) { - $r = (int) $fillColor['r']; - } else { - $r = 255; } - if (isset($fillColor['g']) === true) { - $g = (int) $fillColor['g']; - } else { $g = 255; + if (isset($fillColor['g']) === true) { } - if (isset($fillColor['b']) === true) { - $b = (int) $fillColor['b']; - } else { $b = 255; + if (isset($fillColor['b']) === true) { } $viewNode['color'] = "rgb($r, $g, $b)"; @@ -3356,28 +3308,20 @@ private function applyNodeStyle(array &$viewNode, array $style): void // Extract lineColor (including alpha for border visibility). if (isset($style['lineColor']['_attributes']) === true) { $lineColor = $style['lineColor']['_attributes']; + $r = 0; if (isset($lineColor['r']) === true) { - $r = (int) $lineColor['r']; - } else { - $r = 0; } - if (isset($lineColor['g']) === true) { - $g = (int) $lineColor['g']; - } else { $g = 0; + if (isset($lineColor['g']) === true) { } - if (isset($lineColor['b']) === true) { - $b = (int) $lineColor['b']; - } else { $b = 0; + if (isset($lineColor['b']) === true) { } - if (isset($lineColor['a']) === true) { - $a = (int) $lineColor['a']; - } else { $a = 100; + if (isset($lineColor['a']) === true) { } if ($a < 100) { @@ -3403,22 +3347,16 @@ private function applyNodeStyle(array &$viewNode, array $style): void if (isset($style['font']['color']['_attributes']) === true) { $fontColor = $style['font']['color']['_attributes']; + $r = 0; if (isset($fontColor['r']) === true) { - $r = (int) $fontColor['r']; - } else { - $r = 0; } - if (isset($fontColor['g']) === true) { - $g = (int) $fontColor['g']; - } else { $g = 0; + if (isset($fontColor['g']) === true) { } - if (isset($fontColor['b']) === true) { - $b = (int) $fontColor['b']; - } else { $b = 0; + if (isset($fontColor['b']) === true) { } $font['color'] = "rgb($r, $g, $b)"; @@ -3484,24 +3422,18 @@ private function extractViewRelationshipsRecursively($connectionData): array // Extract bend points if present. if (isset($connection['bendpoint']) === true) { - if (isset($connection['bendpoint'][0]) === true) { - $bendpoints = $connection['bendpoint']; - } else { $bendpoints = [$connection['bendpoint']]; + if (isset($connection['bendpoint'][0]) === true) { } foreach ($bendpoints as $bendpoint) { if (isset($bendpoint['_attributes']) === true) { - if (isset($bendpoint['_attributes']['x']) === true) { - $xValue = (float) $bendpoint['_attributes']['x']; - } else { $xValue = 0; + if (isset($bendpoint['_attributes']['x']) === true) { } - if (isset($bendpoint['_attributes']['y']) === true) { - $yValue = (float) $bendpoint['_attributes']['y']; - } else { $yValue = 0; + if (isset($bendpoint['_attributes']['y']) === true) { } $viewRelationship['bendpoints'][] = [ @@ -3568,28 +3500,20 @@ private function extractLabelMarkup(array $style): array if (isset($style['font']['color']['_attributes']) === true) { $fontColor = $style['font']['color']['_attributes']; + $r = 0; if (isset($fontColor['r']) === true) { - $r = (int) $fontColor['r']; - } else { - $r = 0; } - if (isset($fontColor['g']) === true) { - $g = (int) $fontColor['g']; - } else { $g = 0; + if (isset($fontColor['g']) === true) { } - if (isset($fontColor['b']) === true) { - $b = (int) $fontColor['b']; - } else { $b = 0; + if (isset($fontColor['b']) === true) { } - if (isset($fontColor['a']) === true) { - $a = ((int) $fontColor['a'] / 100); - } else { $a = 1; + if (isset($fontColor['a']) === true) { } // Convert percentage to decimal. @@ -3615,15 +3539,16 @@ private function extractNodeType(array $node): ?string // Handle different xsi:type formats. if ($xsiType === 'Label') { - return 'label'; - } else if ($xsiType === 'Element') { - return 'element'; - } else if (str_contains($xsiType, ':') === true) { + } + + if ($xsiType === 'Element') { + } + + if (str_contains($xsiType, ':') === true) { // Handle namespaced types like "archimate:BusinessService". - return strtolower(preg_replace('/^[a-z]+:/', '', $xsiType)); - } else { - return strtolower($xsiType); } + + return strtolower($xsiType); } // Priority 2: Check if this is a Label node (has label content). @@ -3661,13 +3586,13 @@ private function extractConnectionType(array $connection): string // Remove namespace. $type = preg_replace('/relationship$/i', '', $type); // Remove "Relationship" suffix. - return strtolower($type); - } else if (str_contains($xsiType, ':') === true) { + } + + if (str_contains($xsiType, ':') === true) { // Handle other namespaced types. - return strtolower(preg_replace('/^[a-z]+:/', '', $xsiType)); - } else { - return strtolower($xsiType); } + + return strtolower($xsiType); } // Priority 2: Check if this has a relationshipRef (use that to determine type if possible). @@ -3694,29 +3619,21 @@ private function extractNodeStyle(array $style): array // Extract fillColor. if (isset($style['fillColor']['_attributes']) === true) { - $fillColor = $style['fillColor']['_attributes']; - if (isset($fillColor['r']) === true) { - $rValue = (int) $fillColor['r']; - } else { + $fillColor = $style['fillColor']['_attributes']; $rValue = 255; + if (isset($fillColor['r']) === true) { } - if (isset($fillColor['g']) === true) { - $gValue = (int) $fillColor['g']; - } else { $gValue = 255; + if (isset($fillColor['g']) === true) { } - if (isset($fillColor['b']) === true) { - $bValue = (int) $fillColor['b']; - } else { $bValue = 255; + if (isset($fillColor['b']) === true) { } - if (isset($fillColor['a']) === true) { - $aValue = (int) $fillColor['a']; - } else { $aValue = 100; + if (isset($fillColor['a']) === true) { } $processedStyle['fillColor'] = [ @@ -3729,29 +3646,21 @@ private function extractNodeStyle(array $style): array // Extract lineColor. if (isset($style['lineColor']['_attributes']) === true) { - $lineColor = $style['lineColor']['_attributes']; - if (isset($lineColor['r']) === true) { - $rValue = (int) $lineColor['r']; - } else { + $lineColor = $style['lineColor']['_attributes']; $rValue = 0; + if (isset($lineColor['r']) === true) { } - if (isset($lineColor['g']) === true) { - $gValue = (int) $lineColor['g']; - } else { $gValue = 0; + if (isset($lineColor['g']) === true) { } - if (isset($lineColor['b']) === true) { - $bValue = (int) $lineColor['b']; - } else { $bValue = 0; + if (isset($lineColor['b']) === true) { } - if (isset($lineColor['a']) === true) { - $aValue = (int) $lineColor['a']; - } else { $aValue = 100; + if (isset($lineColor['a']) === true) { } $processedStyle['lineColor'] = [ @@ -3775,23 +3684,17 @@ private function extractNodeStyle(array $style): array } if (isset($style['font']['color']['_attributes']) === true) { - $fontColor = $style['font']['color']['_attributes']; - if (isset($fontColor['r']) === true) { - $rValue = (int) $fontColor['r']; - } else { + $fontColor = $style['font']['color']['_attributes']; $rValue = 0; + if (isset($fontColor['r']) === true) { } - if (isset($fontColor['g']) === true) { - $gValue = (int) $fontColor['g']; - } else { $gValue = 0; + if (isset($fontColor['g']) === true) { } - if (isset($fontColor['b']) === true) { - $bValue = (int) $fontColor['b']; - } else { $bValue = 0; + if (isset($fontColor['b']) === true) { } $font['color'] = [ @@ -3822,23 +3725,17 @@ private function extractConnectionStyle(array $style): array // Extract lineColor. if (isset($style['lineColor']['_attributes']) === true) { - $lineColor = $style['lineColor']['_attributes']; - if (isset($lineColor['r']) === true) { - $rValue = (int) $lineColor['r']; - } else { + $lineColor = $style['lineColor']['_attributes']; $rValue = 0; + if (isset($lineColor['r']) === true) { } - if (isset($lineColor['g']) === true) { - $gValue = (int) $lineColor['g']; - } else { $gValue = 0; + if (isset($lineColor['g']) === true) { } - if (isset($lineColor['b']) === true) { - $bValue = (int) $lineColor['b']; - } else { $bValue = 0; + if (isset($lineColor['b']) === true) { } $processedStyle['lineColor'] = [ @@ -3861,23 +3758,17 @@ private function extractConnectionStyle(array $style): array } if (isset($style['font']['color']['_attributes']) === true) { - $fontColor = $style['font']['color']['_attributes']; - if (isset($fontColor['r']) === true) { - $rValue = (int) $fontColor['r']; - } else { + $fontColor = $style['font']['color']['_attributes']; $rValue = 0; + if (isset($fontColor['r']) === true) { } - if (isset($fontColor['g']) === true) { - $gValue = (int) $fontColor['g']; - } else { $gValue = 0; + if (isset($fontColor['g']) === true) { } - if (isset($fontColor['b']) === true) { - $bValue = (int) $fontColor['b']; - } else { $bValue = 0; + if (isset($fontColor['b']) === true) { } $font['color'] = [ @@ -3933,10 +3824,8 @@ private function extractGemmaType(array $object): ?string if (isset($object[$propertyName]) === true && empty($object[$propertyName]) === false) { $rawValue = $object[$propertyName]; // Handle case where value might be an array (e.g., from XML parsing with _value key). - if (is_array($rawValue) === true) { - $value = $rawValue['_value'] ?? $rawValue[0] ?? ''; - } else { $value = (string) $rawValue; + if (is_array($rawValue) === true) { } // Log the first successful match for debugging. @@ -4339,12 +4228,14 @@ private function extractRelationshipEndpoint(array $relationship, string $endpoi // Handle different XML structures. if (is_string($endpointData) === true) { - return $endpointData; - } else if (is_array($endpointData) === true) { + } + + if (is_array($endpointData) === true) { // Try _attributes.href or _value. if (isset($endpointData['_attributes']['href']) === true) { - return $endpointData['_attributes']['href']; - } else if (isset($endpointData['_value']) === true) { + } + + if (isset($endpointData['_value']) === true) { return $endpointData['_value']; } } @@ -4354,8 +4245,9 @@ private function extractRelationshipEndpoint(array $relationship, string $endpoi if (isset($relationship['xml']['_attributes']) === true) { $attr = $relationship['xml']['_attributes']; if ($endpoint === 'source' && isset($attr['source']) === true) { - return $attr['source']; - } else if ($endpoint === 'target' && isset($attr['target']) === true) { + } + + if ($endpoint === 'target' && isset($attr['target']) === true) { return $attr['target']; } } @@ -4757,10 +4649,8 @@ private function buildElementsLookupFromRawData( // Fast properties flattening (only essential properties for splicing). if (isset($rawItem['properties']['property']) === true && empty($propDefMap) === false) { - if (isset($rawItem['properties']['property'][0]) === true) { - $props = $rawItem['properties']['property']; - } else { $props = [$rawItem['properties']['property']]; + if (isset($rawItem['properties']['property'][0]) === true) { } foreach ($props as $prop) { @@ -4954,10 +4844,8 @@ private function transformSectionObjectsBatch( ]; // Debug: Log XML data extraction. - if (isset($item['properties']) === true) { - $propsStructVal = array_keys($item['properties']); - } else { $propsStructVal = null; + if (isset($item['properties']) === true) { } $this->logger->debug( @@ -5043,28 +4931,20 @@ private function transformSectionObjectsBatch( } // DEBUG: Log final object structure before adding to array. - if (isset($object['xml']) === true) { - $xmlKeysValue = array_keys($object['xml']); - } else { $xmlKeysValue = null; + if (isset($object['xml']) === true) { } - if (isset($object['_propertyMapping']) === true) { - $propMapCountVal = count($object['_propertyMapping']); - } else { $propMapCountVal = 0; + if (isset($object['_propertyMapping']) === true) { } - if (isset($object['viewNodes']) === true) { - $viewNodesCountValue = count($object['viewNodes']); - } else { $viewNodesCountValue = 0; + if (isset($object['viewNodes']) === true) { } - if (isset($object['viewRelationships']) === true) { - $viewRelCountVal = count($object['viewRelationships']); - } else { $viewRelCountVal = 0; + if (isset($object['viewRelationships']) === true) { } $this->logger->debug( @@ -5121,10 +5001,9 @@ private function findItemsSimplified(array $sectionData, string $sectionType): a if ($sectionType === 'view' && isset($sectionData['diagrams']['view']) === true) { $viewData = $sectionData['diagrams']['view']; if (isset($viewData[0]) === true) { - return $viewData; - } else { - return [$viewData]; } + + return [$viewData]; } // Try common patterns: Singular, plural, item, propertyDefinition. @@ -5139,10 +5018,9 @@ private function findItemsSimplified(array $sectionData, string $sectionType): a if (isset($sectionData[$pattern]) === true) { $data = $sectionData[$pattern]; if (is_array($data) === true && isset($data[0]) === true) { - return $data; - } else { - return [$data]; } + + return [$data]; } } @@ -5161,10 +5039,8 @@ private function findItemsSimplified(array $sectionData, string $sectionType): a */ private function flattenPropertiesBatch(array &$object, array $properties, array $propDefMap): void { - if (isset($properties[0]) === true) { - $props = $properties; - } else { $props = [$properties]; + if (isset($properties[0]) === true) { } $processedProperties = []; @@ -6090,10 +5966,8 @@ private function extractDetailedErrors(array $statistics): array // Group errors by type/message for better presentation. $errorGroups = []; foreach ($sectionErrors as $error) { - if (is_string($error) === true) { - $errorMessage = $error; - } else { $errorMessage = ($error['message'] ?? 'Unknown error'); + if (is_string($error) === true) { } $errorType = $this->categorizeError(errorMessage: $errorMessage); diff --git a/lib/Service/ArchiMateService.php b/lib/Service/ArchiMateService.php index 7691d8b7..e35b8222 100644 --- a/lib/Service/ArchiMateService.php +++ b/lib/Service/ArchiMateService.php @@ -46,7 +46,6 @@ * @SuppressWarnings(PHPMD.ExcessiveClassComplexity) * @SuppressWarnings(PHPMD.CouplingBetweenObjects) * @SuppressWarnings(PHPMD.TooManyMethods) - * @SuppressWarnings(PHPMD.ElseExpression) * @SuppressWarnings(PHPMD.CyclomaticComplexity) * @SuppressWarnings(PHPMD.NPathComplexity) * @SuppressWarnings(PHPMD.ExcessiveMethodLength) @@ -314,17 +313,13 @@ public function exportOrgArchiMate(string $organizationUuid, array $options=[]): } // Look up the organization from Voorzieningen register. - $voorzConfig = $this->settingsService->getVoorzieningenConfig(); - if (empty($voorzConfig['register']) === false) { - $orgRegisterId = (int) $voorzConfig['register']; - } else { + $voorzConfig = $this->settingsService->getVoorzieningenConfig(); $orgRegisterId = null; + if (empty($voorzConfig['register']) === false) { } - if (empty($voorzConfig['organisatie_schema']) === false) { - $orgSchemaId = (int) $voorzConfig['organisatie_schema']; - } else { $orgSchemaId = null; + if (empty($voorzConfig['organisatie_schema']) === false) { } if ($orgRegisterId === null || $orgSchemaId === false) { @@ -369,10 +364,8 @@ public function exportOrgArchiMate(string $organizationUuid, array $options=[]): $schemaIdMap = $this->createSchemaIdMap(); // Query organization's gebruik and modules from Voorzieningen register. - if (empty($voorzConfig['gebruik_schema']) === false) { - $gebruikSchemaId = (int) $voorzConfig['gebruik_schema']; - } else { $gebruikSchemaId = null; + if (empty($voorzConfig['gebruik_schema']) === false) { } $gebruikData = []; @@ -388,10 +381,8 @@ public function exportOrgArchiMate(string $organizationUuid, array $options=[]): $gebruikData = $objectService->searchObjects(query: $gebruikQuery, _rbac: false, _multitenancy: false); } - if (empty($voorzConfig['module_schema']) === false) { - $moduleSchemaId = (int) $voorzConfig['module_schema']; - } else { $moduleSchemaId = null; + if (empty($voorzConfig['module_schema']) === false) { } $modulesData = []; @@ -450,10 +441,8 @@ public function exportOrgArchiMate(string $organizationUuid, array $options=[]): // Merge into modulesData, deduplicating by ID. $existingIds = []; foreach ($modulesData as $m) { - if (is_array($m) === true) { - $mid = ($m['id'] ?? $m['@self']['id'] ?? null); - } else { $mid = null; + if (is_array($m) === true) { } if (empty($mid) === false) { @@ -462,10 +451,8 @@ public function exportOrgArchiMate(string $organizationUuid, array $options=[]): } foreach ($allModules as $mod) { - if ((is_object($mod) === true && method_exists($mod, 'jsonSerialize') === true)) { - $modArr = $mod->jsonSerialize(); - } else { $modArr = $mod; + if ((is_object($mod) === true && method_exists($mod, 'jsonSerialize') === true)) { } $modId = $modArr['id'] ?? $modArr['@self']['id'] ?? null; @@ -774,17 +761,13 @@ private function extractIdentifierByPattern(array $item, array $pattern): ?strin switch ($type) { case 'direct': if (is_string($current) === true) { - return $current; - } else { - return null; } + return null; case 'value': if (is_array($current) === true && isset($current['_value']) === true) { - return (string) $current['_value']; - } else { - return null; } + return null; case 'array_search': if (is_array($current) === true) { @@ -1114,10 +1097,8 @@ private function saveObjectsInParallelBatches(array $objects, ObjectService $obj foreach ($chunks as $chunkIndex => $chunk) { // OPTIMIZATION: Removed debug logging from chunk processing loop. try { - if (self::PERFORMANCE_OPTIMIZATIONS['disable_rbac'] === true) { - $rbacValue = false; - } else { $rbacValue = true; + if (self::PERFORMANCE_OPTIMIZATIONS['disable_rbac'] === true) { } $saveResult = $objectService->saveObjects( @@ -1208,10 +1189,8 @@ private function saveObjectsInSingleBatch(array $objects, ObjectService $objectS ] ); - if (self::PERFORMANCE_OPTIMIZATIONS['disable_rbac'] === true) { - $rbacValue = false; - } else { $rbacValue = true; + if (self::PERFORMANCE_OPTIMIZATIONS['disable_rbac'] === true) { } $saveResult = $objectService->saveObjects( @@ -1775,10 +1754,8 @@ private function getAmefRegisterId(): ?int // Fallback to legacy individual app config keys if not present in JSON. if ($rawRegisterId === null || $rawRegisterId === '') { - if ($this->config->getValueString('softwarecatalog', 'amef_register', '') !== '') { - $rawRegisterId = $this->config->getValueString('softwarecatalog', 'amef_register', ''); - } else { $rawRegisterId = $this->config->getValueString('softwarecatalog', 'amef_register_id', ''); + if ($this->config->getValueString('softwarecatalog', 'amef_register', '') !== '') { } } @@ -1786,10 +1763,9 @@ private function getAmefRegisterId(): ?int if ($rawRegisterId !== null && $rawRegisterId !== '' && is_numeric((string) $rawRegisterId) === true) { $registerId = (int) $rawRegisterId; if ($registerId > 0) { - return $registerId; - } else { - return null; } + + return null; } return null; @@ -1926,19 +1902,15 @@ private function getObjectsWithPagination(string $schemaType, array $query=[]): $isAmefType = in_array($schemaType, $amefObjectTypes, true) === true; // Use AMEF register ID for AMEF types, otherwise use per-type register ID. - if ($isAmefType === true) { - $registerId = $this->getAmefRegisterId(); - } else { $registerId = $this->settingsService->getRegisterIdForObjectType($schemaType); + if ($isAmefType === true) { } $schemaId = $this->settingsService->getSchemaIdForObjectType($schemaType); if ($registerId === null || $schemaId === false) { - if ($isAmefType === true) { - $errorMessage = "ArchiMateService: AMEF register or {$schemaType} schema not configured"; - } else { $errorMessage = "ArchiMateService: Register or {$schemaType} schema not configured"; + if ($isAmefType === true) { } $this->logger->error( @@ -1981,10 +1953,8 @@ private function getObjectsWithPagination(string $schemaType, array $query=[]): ]; } - if ($usePagination === true) { - $paginationValue = ['limit' => $limit, 'offset' => $offset]; - } else { $paginationValue = 'disabled'; + if ($usePagination === true) { } $this->logger->debug( @@ -2000,10 +1970,8 @@ private function getObjectsWithPagination(string $schemaType, array $query=[]): // Use searchObjects method for filtering. $objects = $objectService->searchObjects($finalQuery); - if ($usePagination === true) { - $paginationValue = ['limit' => $limit, 'offset' => $offset]; - } else { $paginationValue = 'disabled'; + if ($usePagination === true) { } $this->logger->debug( @@ -2648,10 +2616,9 @@ private function findItemsSimplified(array $sectionData, string $sectionType): a if ($sectionType === 'view' && isset($sectionData['diagrams']['view']) === true) { $viewData = $sectionData['diagrams']['view']; if (isset($viewData[0]) === true) { - return $viewData; - } else { - return [$viewData]; } + + return [$viewData]; } // Try common patterns. @@ -2670,10 +2637,9 @@ private function findItemsSimplified(array $sectionData, string $sectionType): a if (isset($sectionData[$pattern]) === true) { $data = $sectionData[$pattern]; if (is_array($data) === true && isset($data[0]) === true) { - return $data; - } else { - return [$data]; } + + return [$data]; } } @@ -2692,10 +2658,8 @@ private function findItemsSimplified(array $sectionData, string $sectionType): a */ private function flattenPropertiesBatch(array &$object, array $properties, array $propDefMap): void { - if (isset($properties[0]) === true) { - $props = $properties; - } else { $props = [$properties]; + if (isset($properties[0]) === true) { } $processedProperties = []; @@ -3134,12 +3098,14 @@ private function extractRelationshipEndpoint(array $relationship, string $endpoi // Handle different XML structures. if (is_string($endpointData) === true) { - return $endpointData; - } else if (is_array($endpointData) === true) { + } + + if (is_array($endpointData) === true) { // Try _attributes.href or _value. if (isset($endpointData['_attributes']['href']) === true) { - return $endpointData['_attributes']['href']; - } else if (isset($endpointData['_value']) === true) { + } + + if (isset($endpointData['_value']) === true) { return $endpointData['_value']; } } @@ -3149,8 +3115,9 @@ private function extractRelationshipEndpoint(array $relationship, string $endpoi if (isset($relationship['xml']['_attributes']) === true) { $attr = $relationship['xml']['_attributes']; if ($endpoint === 'source' && isset($attr['source']) === true) { - return $attr['source']; - } else if ($endpoint === 'target' && isset($attr['target']) === true) { + } + + if ($endpoint === 'target' && isset($attr['target']) === true) { return $attr['target']; } } diff --git a/lib/Service/ContactpersoonService.php b/lib/Service/ContactpersoonService.php index 1ed176da..44270af6 100644 --- a/lib/Service/ContactpersoonService.php +++ b/lib/Service/ContactpersoonService.php @@ -42,7 +42,6 @@ * @SuppressWarnings(PHPMD.ExcessiveClassLength) * @SuppressWarnings(PHPMD.ExcessiveClassComplexity) * @SuppressWarnings(PHPMD.CouplingBetweenObjects) - * @SuppressWarnings(PHPMD.ElseExpression) * @SuppressWarnings(PHPMD.CyclomaticComplexity) * @SuppressWarnings(PHPMD.NPathComplexity) * @SuppressWarnings(PHPMD.ExcessiveMethodLength) @@ -280,11 +279,11 @@ public function processContactpersoon(object $contactpersoonObject, bool $isUpda 'username' => $username, ] ); - } else { - if ($organisationEntity !== null) { - $orgActive = $organisationEntity->getActive(); - } else { + }//end if + + if ($organisationEntity === null || $organisationEntity->getActive() !== true) { $orgActive = false; + if ($organisationEntity !== null) { } $this->logger->info( @@ -298,7 +297,7 @@ public function processContactpersoon(object $contactpersoonObject, bool $isUpda ] ); return false; - }//end if + } } catch (\Exception $e) { $this->logger->error( 'ContactpersoonService: User creation failed', @@ -310,14 +309,14 @@ public function processContactpersoon(object $contactpersoonObject, bool $isUpda ); return false; }//end try - } else { + $this->logger->warning( 'ContactpersoonService: Contactpersoon has no organization reference, skipping user creation', ['contactId' => $contactId] ); return false; }//end if - } else { + $this->logger->info( 'ContactpersoonService: User account already exists', [ @@ -390,16 +389,17 @@ public function updateUserGroups(object $contactpersoonObject, string $username) // Use the new organization type-based logic instead of old role-based logic. $userManager = \OC::$server->get('OCP\IUserManager'); $user = $userManager->get($username); - if ($user !== null) { - $contactData = $contactpersoonObject->getObject(); - $this->contactPersonHandler->updateUserGroupsFromContactData( - user: $user, - contactData: $contactData - ); - } else { + if ($user === null) { $this->logger->warning('User not found for group update', ['username' => $username]); + return; } + $contactData = $contactpersoonObject->getObject(); + $this->contactPersonHandler->updateUserGroupsFromContactData( + user: $user, + contactData: $contactData + ); + }//end updateUserGroups() /** @@ -573,11 +573,9 @@ public function handleContactpersoonUpdate(object $contactpersoonObject, object */ private function syncNameFieldsToUser(object $contactpersoonObject, ?object $oldContactpersoonObject): void { - $newData = $contactpersoonObject->getObject(); - if ($oldContactpersoonObject !== null) { - $oldData = $oldContactpersoonObject->getObject(); - } else { + $newData = $contactpersoonObject->getObject(); $oldData = []; + if ($oldContactpersoonObject !== null) { } // Check if any name/functie fields have changed. @@ -732,6 +730,16 @@ public function handleContactDeletion(object $contactObject): void $userManager = \OC::$server->get('OCP\IUserManager'); $user = $userManager->get($username); + if ($user === null) { + $this->logger->warning( + 'ContactpersoonService: User not found for deleted contact', + [ + 'contactId' => $contactObject->getId(), + 'username' => $username, + ] + ); + } + if ($user !== null) { // Disable the user instead of deleting. $user->setEnabled(false); @@ -743,14 +751,6 @@ public function handleContactDeletion(object $contactObject): void 'username' => $username, ] ); - } else { - $this->logger->warning( - 'ContactpersoonService: User not found for deleted contact', - [ - 'contactId' => $contactObject->getId(), - 'username' => $username, - ] - ); } } catch (\Exception $e) { $this->logger->error( @@ -871,6 +871,15 @@ public function getContactPersonsWithUserDetailsForOrganization(string $organiza $userDetails = null; // If username exists, fetch user details. + if ($username === null) { + $this->logger->debug( + 'ContactpersoonService: No username found for contact person', + [ + 'contactPersonId' => $contactPerson->getId(), + ] + ); + } + if ($username !== null) { $user = $userManager->get($username); if ($user !== null) { @@ -895,7 +904,9 @@ public function getContactPersonsWithUserDetailsForOrganization(string $organiza 'userEnabled' => $user->isEnabled(), ] ); - } else { + }//end if + + if ($user === null) { $this->logger->warning( 'ContactpersoonService: User not found for username', [ @@ -903,14 +914,7 @@ public function getContactPersonsWithUserDetailsForOrganization(string $organiza 'username' => $username, ] ); - }//end if - } else { - $this->logger->debug( - 'ContactpersoonService: No username found for contact person', - [ - 'contactPersonId' => $contactPerson->getId(), - ] - ); + } }//end if // Create enhanced contact person object with user details spliced in. @@ -1060,14 +1064,7 @@ public function getBulkUserInfo(array $contactpersoonIds): array // If user exists, get their current groups. if (empty($username) === false) { $user = $userManager->get($username); - if ($user !== null) { - $groupManager = \OC::$server->get('OCP\IGroupManager'); - $userGroups = $groupManager->getUserGroups($user); - $userInfo['groups'] = array_keys($userGroups); - $userInfo['enabled'] = $user->isEnabled(); - $userInfo['displayName'] = $user->getDisplayName(); - $userInfo['lastLogin'] = $user->getLastLogin(); - } else { + if ($user === null) { $this->logger->warning( 'ContactpersoonService: User not found for bulk user info', [ @@ -1076,7 +1073,16 @@ public function getBulkUserInfo(array $contactpersoonIds): array ] ); } - } + + if ($user !== null) { + $groupManager = \OC::$server->get('OCP\IGroupManager'); + $userGroups = $groupManager->getUserGroups($user); + $userInfo['groups'] = array_keys($userGroups); + $userInfo['enabled'] = $user->isEnabled(); + $userInfo['displayName'] = $user->getDisplayName(); + $userInfo['lastLogin'] = $user->getLastLogin(); + } + }//end if $bulkUserInfo[$contactpersoonId] = $userInfo; } catch (\Exception $e) { @@ -1181,6 +1187,16 @@ private function updateContactpersoonObjectOwner(object $contactObject, string $ // Set the organisation field in @self metadata to the organization UUID. // This ensures the contact person is properly linked to their organization. $organizationUuid = ($currentObject['organisation'] ?? $currentObject['organisatie'] ?? ''); + if (empty($organizationUuid) === true) { + $this->logger->warning( + 'ContactpersoonService: No organization UUID found for contact person', + [ + 'contactId' => $contactId, + 'contactData' => $currentObject, + ] + ); + } + if (empty($organizationUuid) === false) { $selfMetadata['organisation'] = $organizationUuid; $this->logger->info( @@ -1190,14 +1206,6 @@ private function updateContactpersoonObjectOwner(object $contactObject, string $ 'organizationUuid' => $organizationUuid, ] ); - } else { - $this->logger->warning( - 'ContactpersoonService: No organization UUID found for contact person', - [ - 'contactId' => $contactId, - 'contactData' => $currentObject, - ] - ); } // Update the object with the new @self metadata. diff --git a/lib/Service/GebruikService.php b/lib/Service/GebruikService.php index bf9bd842..edbad2f6 100644 --- a/lib/Service/GebruikService.php +++ b/lib/Service/GebruikService.php @@ -23,8 +23,6 @@ /** * Service for handling gebruik-related operations - * - * @SuppressWarnings(PHPMD.ElseExpression) */ class GebruikService { @@ -197,10 +195,9 @@ function ($object) { if (method_exists($object, 'jsonSerialize') === true) { $object = $object->jsonSerialize(); } else if (method_exists($object, 'getId') === true) { - return $object->getId(); - } else { - $object = $object->getObject(); } + + $object = $object->getObject(); } return $object['@self']['id'] ?? $object['id'] ?? null; diff --git a/lib/Service/GebruikSyncService.php b/lib/Service/GebruikSyncService.php index 8abe2403..c60af9ca 100644 --- a/lib/Service/GebruikSyncService.php +++ b/lib/Service/GebruikSyncService.php @@ -37,7 +37,6 @@ * @version GIT: * @link https://github.com/conduction/nextcloud-software-catalog * - * @SuppressWarnings(PHPMD.ElseExpression) * @SuppressWarnings(PHPMD.CyclomaticComplexity) * @SuppressWarnings(PHPMD.NPathComplexity) * @SuppressWarnings(PHPMD.ExcessiveMethodLength) @@ -259,6 +258,15 @@ private function processAmefElements(ObjectEntity $gebruikObject): array } // Update the gebruik object with AMEF slugs. + if (empty($amefSlugs) === true) { + $this->logger->info( + 'No AMEF elements with slugs found', + [ + 'gebruikId' => $gebruikUuid, + ] + ); + }//end if + if (empty($amefSlugs) === false) { $gebruikData['amefElements'] = array_unique($amefSlugs); $this->updateGebruikObject( @@ -275,14 +283,7 @@ private function processAmefElements(ObjectEntity $gebruikObject): array 'amefElementsCount' => count($amefSlugs), ] ); - } else { - $this->logger->info( - 'No AMEF elements with slugs found', - [ - 'gebruikId' => $gebruikUuid, - ] - ); - }//end if + } return $stats; } catch (Exception $e) { @@ -437,10 +438,20 @@ private function updateStatusBasedOnDates(ObjectEntity $gebruikObject): array ); $stats['statusUpdated'] = true; - if ($targetDate !== null) { - $basedOnDate = $targetDate->format('Y-m-d'); - } else { $basedOnDate = null; + if ($targetDate === null) { + $this->logger->info( + 'No status update needed', + [ + 'app' => 'softwarecatalog', + 'gebruikId' => $gebruikUuid, + 'currentStatus' => $currentStatus, + 'targetStatus' => $targetStatus, + ] + ); + } + + if ($targetDate !== null) { } $this->logger->critical( @@ -453,16 +464,6 @@ private function updateStatusBasedOnDates(ObjectEntity $gebruikObject): array 'basedOnDate' => $basedOnDate, ] ); - } else { - $this->logger->info( - 'No status update needed', - [ - 'app' => 'softwarecatalog', - 'gebruikId' => $gebruikUuid, - 'currentStatus' => $currentStatus, - 'targetStatus' => $targetStatus, - ] - ); }//end if return $stats; diff --git a/lib/Service/ModuleComplianceService.php b/lib/Service/ModuleComplianceService.php index b7b9820b..fb221b51 100644 --- a/lib/Service/ModuleComplianceService.php +++ b/lib/Service/ModuleComplianceService.php @@ -37,7 +37,6 @@ * @link https://github.com/ConductionNL/SoftwareCatalog * * @SuppressWarnings(PHPMD.ExcessiveClassComplexity) - * @SuppressWarnings(PHPMD.ElseExpression) * @SuppressWarnings(PHPMD.CyclomaticComplexity) * @SuppressWarnings(PHPMD.NPathComplexity) * @SuppressWarnings(PHPMD.ExcessiveMethodLength) @@ -189,7 +188,9 @@ public function handleModuleComplianceUpdate(object $moduleObject): void 'standaarden' => $standaardversieUuids, ] ); - } else { + }//end if + + if ($this->arraysAreDifferent(array1: $currentStandaarden, array2: $standaardversieUuids) === false) { $this->logger->debug( 'ModuleComplianceService: Standaarden are already up to date', [ @@ -197,7 +198,7 @@ public function handleModuleComplianceUpdate(object $moduleObject): void 'moduleUuid' => $moduleUuid, ] ); - }//end if + } $endTime = microtime(true); $executionTime = round(($endTime - $startTime) * 1000, 2); @@ -328,58 +329,7 @@ private function extractStandaardversieUuids(array $complianceObjects): array $complianceData = $complianceObject->getObject(); $standaardversie = $complianceData['standaardversie'] ?? null; - if ($standaardversie !== null) { - $tracking['withStandaardversie']++; - - // Handle both string UUID and object with UUID property. - if (is_string($standaardversie) === true) { - $tracking['stringType']++; - $standaardversieUuids[] = $standaardversie; - $this->logger->debug( - 'ModuleComplianceService: Found string standaardversie', - [ - 'complianceId' => $complianceObject->getId(), - 'standaardversie' => $standaardversie, - ] - ); - } else if (is_array($standaardversie) === true && isset($standaardversie['uuid']) === true) { - $tracking['arrayType']++; - $standaardversieUuids[] = $standaardversie['uuid']; - $this->logger->debug( - 'ModuleComplianceService: Found array standaardversie', - [ - 'complianceId' => $complianceObject->getId(), - 'standaardversie' => $standaardversie['uuid'], - ] - ); - } else if (is_object($standaardversie) === true && isset($standaardversie->uuid) === true) { - $tracking['objectType']++; - $standaardversieUuids[] = $standaardversie->uuid; - $this->logger->debug( - 'ModuleComplianceService: Found object standaardversie', - [ - 'complianceId' => $complianceObject->getId(), - 'standaardversie' => $standaardversie->uuid, - ] - ); - } else { - $tracking['invalidType']++; - if (is_array($standaardversie) === true) { - $standaardversieValue = json_encode($standaardversie); - } else { - $standaardversieValue = (string) $standaardversie; - } - - $this->logger->warning( - 'ModuleComplianceService: Invalid standaardversie type', - [ - 'complianceId' => $complianceObject->getId(), - 'type' => gettype($standaardversie), - 'value' => $standaardversieValue, - ] - ); - }//end if - } else { + if ($standaardversie === null) { $tracking['withoutStandaardversie']++; $this->logger->debug( 'ModuleComplianceService: Compliance object missing standaardversie', @@ -388,7 +338,62 @@ private function extractStandaardversieUuids(array $complianceObjects): array 'complianceUuid' => $complianceData['uuid'] ?? 'unknown', ] ); + continue; + } + + $tracking['withStandaardversie']++; + + // Handle both string UUID and object with UUID property. + if (is_string($standaardversie) === true) { + $tracking['stringType']++; + $standaardversieUuids[] = $standaardversie; + $this->logger->debug( + 'ModuleComplianceService: Found string standaardversie', + [ + 'complianceId' => $complianceObject->getId(), + 'standaardversie' => $standaardversie, + ] + ); + } else if (is_array($standaardversie) === true && isset($standaardversie['uuid']) === true) { + $tracking['arrayType']++; + $standaardversieUuids[] = $standaardversie['uuid']; + $this->logger->debug( + 'ModuleComplianceService: Found array standaardversie', + [ + 'complianceId' => $complianceObject->getId(), + 'standaardversie' => $standaardversie['uuid'], + ] + ); + } else if (is_object($standaardversie) === true && isset($standaardversie->uuid) === true) { + $tracking['objectType']++; + $standaardversieUuids[] = $standaardversie->uuid; + $this->logger->debug( + 'ModuleComplianceService: Found object standaardversie', + [ + 'complianceId' => $complianceObject->getId(), + 'standaardversie' => $standaardversie->uuid, + ] + ); }//end if + + if (is_string($standaardversie) === false + && (is_array($standaardversie) === false || isset($standaardversie['uuid']) === false) + && (is_object($standaardversie) === false || isset($standaardversie->uuid) === false) + ) { + $tracking['invalidType']++; + $standaardversieValue = (string) $standaardversie; + if (is_array($standaardversie) === true) { + } + + $this->logger->warning( + 'ModuleComplianceService: Invalid standaardversie type', + [ + 'complianceId' => $complianceObject->getId(), + 'type' => gettype($standaardversie), + 'value' => $standaardversieValue, + ] + ); + } }//end foreach // Remove duplicates and empty values. @@ -583,7 +588,9 @@ public function bulkSyncModuleStandards(): array 'module' => $moduleUuid, 'standaardversie' => $standaardversie, ]; - } else { + } + + if ($standaardversie === null) { $results['samples']['complianceWithoutStandaardversie'][] = [ 'id' => $complianceObject->getId(), 'uuid' => $complianceData['uuid'] ?? 'unknown', @@ -601,13 +608,16 @@ public function bulkSyncModuleStandards(): array } // Handle both string UUID and object with UUID property. + $moduleUuidValue = null; if (is_string($moduleUuid) === true) { $moduleUuidValue = $moduleUuid; } else if (is_array($moduleUuid) === true && isset($moduleUuid['uuid']) === true) { $moduleUuidValue = $moduleUuid['uuid']; } else if (is_object($moduleUuid) === true && isset($moduleUuid->uuid) === true) { $moduleUuidValue = $moduleUuid->uuid; - } else { + } + + if ($moduleUuidValue === null) { $results['errors'][] = 'Invalid module reference in compliance object: '.$complianceObject->getId(); continue; } @@ -737,7 +747,9 @@ public function bulkSyncModuleStandards(): array 'count' => count($standaardversieUuids), ] ); - } else { + }//end if + + if ($this->arraysAreDifferent(array1: $currentStandaarden, array2: $standaardversieUuids) === false) { $results['modulesAlreadyUpToDate']++; // Add to full modules list. diff --git a/lib/Service/ModuleVersionService.php b/lib/Service/ModuleVersionService.php index 86667447..8e080703 100644 --- a/lib/Service/ModuleVersionService.php +++ b/lib/Service/ModuleVersionService.php @@ -29,7 +29,6 @@ * @category Service * @package OCA\SoftwareCatalog\Service * - * @SuppressWarnings(PHPMD.ElseExpression) * @SuppressWarnings(PHPMD.ExcessiveMethodLength) */ class ModuleVersionService @@ -107,10 +106,9 @@ public function ensureDefaultVersion(object $moduleObject): void _multitenancy: false ); + $versionCount = 0; if (is_array($existingVersions) === true) { $versionCount = count($existingVersions); - } else { - $versionCount = 0; } if ($versionCount > 0) { diff --git a/lib/Service/OrganizationSyncService.php b/lib/Service/OrganizationSyncService.php index a5e72e22..549bf753 100644 --- a/lib/Service/OrganizationSyncService.php +++ b/lib/Service/OrganizationSyncService.php @@ -45,7 +45,6 @@ * @SuppressWarnings(PHPMD.CouplingBetweenObjects) * @SuppressWarnings(PHPMD.TooManyMethods) * @SuppressWarnings(PHPMD.TooManyPublicMethods) - * @SuppressWarnings(PHPMD.ElseExpression) * @SuppressWarnings(PHPMD.CyclomaticComplexity) * @SuppressWarnings(PHPMD.NPathComplexity) * @SuppressWarnings(PHPMD.ExcessiveMethodLength) @@ -165,10 +164,8 @@ private function jsonExtract(string $column, string $path): string } // MySQL/MariaDB: Use json_unquote(json_extract()). - if (str_starts_with($path, '$.') === true) { - $jsonPath = $path; - } else { $jsonPath = '$.'.$path; + if (str_starts_with($path, '$.') === true) { } return "json_unquote(json_extract({$column}, '{$jsonPath}'))"; @@ -493,10 +490,8 @@ public function performUserSync(): array $platform = $this->db->getDatabasePlatform(); $isPostgres = $platform instanceof \Doctrine\DBAL\Platforms\PostgreSQLPlatform; - if ($isPostgres === true) { - $jsonContainsCheck = "NOT (oo.users::jsonb @> to_jsonb(o.username::text))"; - } else { $jsonContainsCheck = "JSON_CONTAINS(oo.users, CONCAT('\"', o.username, '\"')) = 0"; + if ($isPostgres === true) { } // Find contacts with a username whose username is NOT in their org's users array. @@ -544,10 +539,8 @@ public function performUserSync(): array */ public function performFullSync(int $minutesBack=10): array { - if ($minutesBack === 0) { - $syncModeValue = 'full'; - } else { $syncModeValue = 'incremental'; + if ($minutesBack === 0) { } $this->logger->info( @@ -591,10 +584,8 @@ public function performFullSync(int $minutesBack=10): array organizationSchema: $organizationSchema, minutesBack: $minutesBack ); + $syncModeValue = 'incremental'; if ($minutesBack === 0) { - $syncModeValue = 'full'; - } else { - $syncModeValue = 'incremental'; } $this->logger->info( @@ -694,7 +685,9 @@ private function getOrganisatieObjectsByTimeWindow(string $register, string $org 'query' => $query, ] ); - } else { + }//end if + + if ($minutesBack <= 0) { $this->logger->debug( 'OrganizationSyncService: Using searchObjects for all objects', [ @@ -703,7 +696,7 @@ private function getOrganisatieObjectsByTimeWindow(string $register, string $org 'query' => $query, ] ); - }//end if + } // Use searchObjects method for filtering. $objects = $objectService->searchObjects(query: $query, _rbac: false, _multitenancy: false); @@ -926,7 +919,9 @@ private function ensureOrganisationEntity(object $organisatieObject, array &$sta '📧 Organization activation email sent successfully', ['organisatieId' => $organisatieId] ); - } else { + } + + if (empty($emailSent) === true) { $this->logger->info( '📧 Organization activation email not sent (disabled or not configured)', ['organisatieId' => $organisatieId] @@ -1017,7 +1012,9 @@ private function ensureOrganisationEntity(object $organisatieObject, array &$sta '📧 Organization registration email sent successfully', ['organisatieId' => $organisatieId] ); - } else { + } + + if (empty($emailSent) === true) { $this->logger->info( '📧 Organization registration email not sent (disabled or not configured)', ['organisatieId' => $organisatieId] @@ -1032,7 +1029,9 @@ private function ensureOrganisationEntity(object $organisatieObject, array &$sta register: $register, organizationSchema: $organizationSchema ); - } else { + }//end if + + if (empty($organisationEntity) === true) { $this->logger->error( '❌ ORGANISATION ENTITY CREATION FAILED', [ @@ -1040,7 +1039,7 @@ private function ensureOrganisationEntity(object $organisatieObject, array &$sta 'organisatieId' => $organisatieId, ] ); - }//end if + } return $organisationEntity; }//end try @@ -1194,11 +1193,9 @@ private function processContactPerson(object $contactPerson, array &$stats): ?st } // Check if user already exists. - $userManager = \OC::$server->get('OCP\IUserManager'); - if (empty($existingUsername) === false) { - $username = $existingUsername; - } else { + $userManager = \OC::$server->get('OCP\IUserManager'); $username = $email; + if (empty($existingUsername) === false) { } $user = $userManager->get($username); @@ -1224,8 +1221,8 @@ private function processContactPerson(object $contactPerson, array &$stats): ?st 'username' => $username, ] ); - return $username; - } else { + } + $this->logger->error( 'OrganizationSyncService: Failed to create user account', [ @@ -1233,23 +1230,21 @@ private function processContactPerson(object $contactPerson, array &$stats): ?st 'username' => $username, ] ); - return null; - } - } else { + }//end if + // User exists, update username in contact if needed. - if (empty($existingUsername) === true) { - $this->logger->debug( - 'OrganizationSyncService: Updating contact person with username', - [ - 'contactId' => $contactPerson->getId(), - 'username' => $username, - ] - ); - $stats['usersUpdated']++; - } + if (empty($existingUsername) === true) { + $this->logger->debug( + 'OrganizationSyncService: Updating contact person with username', + [ + 'contactId' => $contactPerson->getId(), + 'username' => $username, + ] + ); + $stats['usersUpdated']++; + } return $username; - }//end if } catch (\Exception $e) { $this->logger->error( 'OrganizationSyncService: Failed to process contact person', @@ -1313,7 +1308,9 @@ private function updateOrganisationEntityUsers(object $organisationEntity, array 'totalUsers' => count($allUsernames), ] ); - } else { + }//end if + + if ($currentUsersSet === $allUsernames) { $this->logger->debug( 'OrganizationSyncService: Organisation entity users unchanged', [ @@ -1321,7 +1318,7 @@ private function updateOrganisationEntityUsers(object $organisationEntity, array 'userCount' => count($allUsernames), ] ); - }//end if + } } catch (\Exception $e) { $this->logger->error( 'OrganizationSyncService: Failed to update organisation entity users', @@ -1429,32 +1426,26 @@ public function getSyncStatus(int $minutesBack=10): array } // Calculate efficiency metrics. + $efficiencyImprovement = 0; if (count($allOrganisatieObjects) > 0) { $ratio = count($incrementalOrganisatieObjects) / count($allOrganisatieObjects); $efficiencyImprovement = round(((1 - $ratio) * 100), 1); - } else { - $efficiencyImprovement = 0; } - if ($minutesBack === 0) { - $syncModeValue = 'full'; - } else { $syncModeValue = 'incremental'; + if ($minutesBack === 0) { } + $messageValue = 'No organizations to process in the current time window'; if (count($incrementalOrganisatieObjects) > 0) { $orgCount = $this->formatNumber(number: count($incrementalOrganisatieObjects)); $contactCount = $this->formatNumber(number: $predictedContactPersonsToProcess); // phpcs:ignore Generic.Files.LineLength.TooLong $messageValue = "Ready to process {$orgCount} organizations and {$contactCount} contact persons"; - } else { - $messageValue = 'No organizations to process in the current time window'; } - if ($minutesBack > 0) { - $nextScheduledSyncValue = "Will process organizations updated in the last {$minutesBack} minutes"; - } else { $nextScheduledSyncValue = 'Will process all organizations (full sync)'; + if ($minutesBack > 0) { } return [ @@ -1639,7 +1630,9 @@ public function processSpecificOrganization($organizationObject): array organizationObject: $organizationObject, stats: $stats ); - } else { + }//end if + + if (empty($organisationEntity) === true) { $this->logger->error( '❌ ORGANISATION ENTITY FAILED', [ @@ -1649,7 +1642,7 @@ public function processSpecificOrganization($organizationObject): array ] ); $stats['errors'][] = 'Failed to create/update organisation entity'; - }//end if + } $stats['endTime'] = date('Y-m-d H:i:s'); $stats['duration'] = round((microtime(true) - $startTime), 3); @@ -1770,14 +1763,12 @@ private function processNestedContactPersons($organizationObject, array &$stats) } // Get the object data as array. + $contactData = []; + if (is_array($contactObject) === true) { + } + if ($contactObject instanceof \OCA\OpenRegister\Db\ObjectEntity) { $contactData = $contactObject->getObject(); - } else { - if (is_array($contactObject) === true) { - $contactData = $contactObject; - } else { - $contactData = []; - } } // Add the UUID if not present. @@ -1931,10 +1922,8 @@ private function processRelatedContactPersons(string $organizationUuid, $organiz _multitenancy: false ); - if ($rawOrgObject !== null) { - $rawOrgData = $rawOrgObject->getObject(); - } else { $rawOrgData = []; + if ($rawOrgObject !== null) { } $contactUuids = ($rawOrgData['contactpersonen'] ?? []); @@ -2394,7 +2383,9 @@ private function createOrUpdateContactPersonObject( 'username' => $user->getUID(), ] ); - } else { + }//end if + + if (empty($user) === true) { $this->logger->error( 'User account creation failed', [ @@ -2404,12 +2395,12 @@ private function createOrUpdateContactPersonObject( ] ); $stats['errors'][] = "Failed to create user account for {$email}"; - }//end if - } else { - if ($organisationEntity !== null) { - $organizationActiveValue = $organisationEntity->getActive(); - } else { + } + }//end if + + if ($organisationEntity === false || $organisationEntity->getActive() !== true) { $organizationActiveValue = false; + if ($organisationEntity !== null) { } $this->logger->info( @@ -2422,7 +2413,7 @@ private function createOrUpdateContactPersonObject( 'email' => $email, ] ); - }//end if + } } catch (\Exception $e) { // Organization not found in entity table = not active. $this->logger->info( @@ -2617,7 +2608,9 @@ public function processSpecificContactPerson($contactObject): array ); $stats['usersCreated']++; - } else { + }//end if + + if ($user === null) { $this->logger->debug( '[EVENT] Skipping contact - user account creation failed (likely no email)', [ @@ -2625,12 +2618,12 @@ public function processSpecificContactPerson($contactObject): array 'contactId' => $contactObject->getUuid(), ] ); - }//end if - } else { - if ($organisationEntity !== null) { - $organizationActiveValue = $organisationEntity->getActive(); - } else { + } + }//end if + + if ($organisationEntity === false || $organisationEntity->getActive() !== true) { $organizationActiveValue = false; + if ($organisationEntity !== null) { } $skipEmail = ($contactEntityObject['email'] ?? $contactEntityObject['e-mailadres'] ?? 'unknown'); @@ -2644,7 +2637,7 @@ public function processSpecificContactPerson($contactObject): array 'email' => $skipEmail, ] ); - }//end if + } } catch (\Exception $e) { $this->logger->error( '[EVENT] User creation failed for contact', @@ -2798,10 +2791,8 @@ public function performOptimizedManualSync(int $maxRounds=10, int $batchSize=100 */ public function performScheduledSync(int $minutesBack=0): array { - if ($minutesBack === 0) { - $syncModeValue = 'full'; - } else { $syncModeValue = 'incremental'; + if ($minutesBack === 0) { } $this->logger->info( @@ -2897,10 +2888,8 @@ public function performScheduledSync(int $minutesBack=0): array */ public function performManualSync(int $minutesBack=0): array { - if ($minutesBack === 0) { - $syncModeValue = 'full'; - } else { $syncModeValue = 'incremental'; + if ($minutesBack === 0) { } $this->logger->info( @@ -2980,10 +2969,8 @@ public function getSyncStatusWithErrorHandling(int $minutesBack=10): array ] ); - if ($minutesBack === 0) { - $syncModeValue = 'full'; - } else { $syncModeValue = 'incremental'; + if ($minutesBack === 0) { } return [ @@ -3140,10 +3127,18 @@ private function updateContactpersoonObjectOwner( $organizationUuid = ($organizationUuidOverride ?? $orgUuid); if (empty($organizationUuid) === false) { $selfMetadata['organisation'] = $organizationUuid; - if (empty($organizationUuidOverride) === false) { - $sourceValue = 'override'; - } else { $sourceValue = 'object'; + if (empty($organizationUuidOverride) === true) { + $this->logger->warning( + 'OrganizationSyncService: No organization UUID found for contact person', + [ + 'contactId' => $contactId, + 'contactData' => $currentObject, + ] + ); + } + + if (empty($organizationUuidOverride) === false) { } $this->logger->info( @@ -3154,14 +3149,6 @@ private function updateContactpersoonObjectOwner( 'source' => $sourceValue, ] ); - } else { - $this->logger->warning( - 'OrganizationSyncService: No organization UUID found for contact person', - [ - 'contactId' => $contactId, - 'contactData' => $currentObject, - ] - ); }//end if // Restore the organisatie field if it was removed during username save. diff --git a/lib/Service/ProgressTracker.php b/lib/Service/ProgressTracker.php index 3fc13aee..b4c95e04 100644 --- a/lib/Service/ProgressTracker.php +++ b/lib/Service/ProgressTracker.php @@ -30,8 +30,6 @@ * @license AGPL-3.0-or-later https://www.gnu.org/licenses/agpl-3.0.html * @version GIT: 1.0.0 * @link https://github.com/ConductionNL/SoftwareCatalog - * - * @SuppressWarnings(PHPMD.ElseExpression) */ class ProgressTracker { @@ -362,20 +360,17 @@ private function calculateOverallPercentage(): int if ($currentPhaseIndex !== false) { $currentPhaseWeight = self::PHASES[$this->progress['phase']]['weight']; + // If no items to process, consider phase as complete. + $currentPhaseProgress = $currentPhaseWeight; if ($this->progress['total_items'] > 0) { $itemRatio = $this->progress['processed_items'] / $this->progress['total_items']; $currentPhaseProgress = $itemRatio * $currentPhaseWeight; - } else { - // If no items to process, consider phase as complete. - $currentPhaseProgress = $currentPhaseWeight; } } $overallProgress = $completedWeight + $currentPhaseProgress; + $percentage = 0; if ($totalWeight > 0) { - $percentage = intval(($overallProgress / $totalWeight) * 100); - } else { - $percentage = 0; } return min(100, max(0, $percentage)); diff --git a/lib/Service/SettingsService.php b/lib/Service/SettingsService.php index 3cd3e27f..3e09f712 100644 --- a/lib/Service/SettingsService.php +++ b/lib/Service/SettingsService.php @@ -46,7 +46,6 @@ * @SuppressWarnings(PHPMD.TooManyMethods) * @SuppressWarnings(PHPMD.TooManyPublicMethods) * @SuppressWarnings(PHPMD.ExcessivePublicCount) - * @SuppressWarnings(PHPMD.ElseExpression) * @SuppressWarnings(PHPMD.CyclomaticComplexity) * @SuppressWarnings(PHPMD.NPathComplexity) * @SuppressWarnings(PHPMD.ExcessiveMethodLength) @@ -262,10 +261,9 @@ public function getSettings(): array $rawRegisters = array_map( function ($register) { if (is_object($register) === true && method_exists($register, 'jsonSerialize') === true) { - return $register->jsonSerialize(); - } else { - return (array) $register; } + + return (array) $register; }, $rawRegisters ); @@ -445,10 +443,8 @@ public function updateSettings(array $data): array $stringValue = json_encode($value); } else { // Ensure value is converted to string as required by setValueString. - if (is_string($value) === true) { - $stringValue = $value; - } else { $stringValue = (string) $value; + if (is_string($value) === true) { } } @@ -943,10 +939,8 @@ public function getRegisterIdForObjectType(string $objectType): ?int // Fallback to legacy per-object-type register config. if ($result === null) { $registerId = $this->config->getValueString($this->appName, "{$objectType}_register", ''); - if (empty($registerId) === false) { - $result = (int) $registerId; - } else { $result = null; + if (empty($registerId) === false) { } } @@ -1443,10 +1437,9 @@ public function getGenericUserGroups(): array $groups = json_decode($groupsJson, true); if (is_array($groups) === true) { - return $groups; - } else { - return []; } + + return []; }//end getGenericUserGroups() /** @@ -1521,10 +1514,9 @@ public function getSuperUserGroups(): array $groups = json_decode($groupsJson, true); if (is_array($groups) === true) { - return $groups; - } else { - return []; } + + return []; }//end getSuperUserGroups() /** @@ -2068,10 +2060,8 @@ public function updateEmailSettings(array $emailSettings): array // Convert boolean values to strings. if (is_bool($value) === true) { - if ($value === true) { - $value = 'true'; - } else { $value = 'false'; + if ($value === true) { } } @@ -2622,10 +2612,8 @@ private function getConnectionDetails(array $emailSettings): array switch ($transportType) { case 'smtp': - if (empty($emailSettings['smtpUsername']) === false) { - $usernameValue = '***'; - } else { $usernameValue = 'none'; + if (empty($emailSettings['smtpUsername']) === false) { } return [ 'type' => 'SMTP', @@ -2811,10 +2799,8 @@ private function createSmtpTransport(array $settings): \Symfony\Component\Mailer $dsn .= '?encryption='.$encryption; } - if (empty($encryption) === false && $encryption !== 'none') { - $encSuffix = '?encryption='.$encryption; - } else { $encSuffix = ''; + if (empty($encryption) === false && $encryption !== 'none') { } $dsnPattern = sprintf('smtp://***:***@%s:%d%s', $host, $port, $encSuffix); @@ -2965,10 +2951,8 @@ public function getVersionInfo(): array $openRegisterInstalled = $this->isOpenRegisterInstalled(); $openRegisterEnabled = $openRegisterInstalled && $this->isOpenRegisterEnabled(); - if ($storedConfigVersion !== null) { - $versionComparisonValue = version_compare($currentAppVersion, $storedConfigVersion); - } else { $versionComparisonValue = null; + if ($storedConfigVersion !== null) { } $versionInfo = [ @@ -3050,10 +3034,8 @@ public function forceUpdate(): array ); // Return concise response to avoid serialization issues with large nested structures. - if ($success === true) { - $messageValue = 'Force update completed successfully'; - } else { $messageValue = 'Force update completed but configuration needs attention'; + if ($success === true) { } return [ @@ -3198,10 +3180,8 @@ public function manualImport(bool $forceImport=false): array // If force import is requested or auto-config not completed, reset auto-configuration flag. if ($forceImport === true || $versionInfo['autoConfigCompleted'] === false) { $this->config->setValueString($this->appName, 'auto_config_completed', 'false'); - if ($forceImport === true) { - $reasonValue = 'force_import'; - } else { $reasonValue = 'auto_config_not_completed'; + if ($forceImport === true) { } $this->logger->info( @@ -3582,16 +3562,12 @@ private function configureVoorzieningen(): array $originalSlug = $schema['slug'] ?? ''; $lowercaseSlug = strtolower($originalSlug); - if (isset($slugToKey[$originalSlug]) === true) { - $hasMappingOriginalValue = 'YES'; - } else { $hasMappingOriginalValue = 'NO'; + if (isset($slugToKey[$originalSlug]) === true) { } - if (isset($slugToKey[$lowercaseSlug]) === true) { - $hasMappingLowercaseValue = 'YES'; - } else { $hasMappingLowercaseValue = 'NO'; + if (isset($slugToKey[$lowercaseSlug]) === true) { } $this->logger->info( @@ -3707,10 +3683,9 @@ private function configureAmef(): array $registers = array_map( function ($register) { if (($register instanceof \OCA\OpenRegister\Db\Register)) { - return $register->jsonSerialize(); - } else { - return (array) $register; } + + return (array) $register; }, $registers ); @@ -3775,10 +3750,8 @@ function ($register) { } }//end foreach - if (isset($best) === true) { - $targetRegister = $best; - } else { $targetRegister = $candidate; + if (isset($best) === true) { } if ($targetRegister === null) { @@ -3804,10 +3777,8 @@ function ($register) { $allowed = ['organization','element','relation','view','model','property-definition']; if (in_array($slug, $allowed, true) === true) { // Handle property-definition schema with underscore in config key. - if ($slug === 'property-definition') { - $configKey = 'property_definition_schema'; - } else { $configKey = $slug.'_schema'; + if ($slug === 'property-definition') { } $config[$configKey] = (string) $schema['id']; @@ -4202,16 +4173,12 @@ public function getArchiMateStatus(): array // Get AMEF object counts. $amefObjectCounts = $this->getAmefObjectCounts(); - if (is_array($importDecoded) === true) { - $importValue = $importDecoded; - } else { $importValue = []; + if (is_array($importDecoded) === true) { } - if (is_array($exportDecoded) === true) { - $exportValue = $exportDecoded; - } else { $exportValue = []; + if (is_array($exportDecoded) === true) { } return [ @@ -5501,10 +5468,8 @@ public function updateAmefConfig(array $config): array if (isset($config['register']) === true) { $targetRegisterId = (string) $config['register']; } else { - if (isset($existing['register']) === true) { - $targetRegisterId = (string) $existing['register']; - } else { $targetRegisterId = ''; + if (isset($existing['register']) === true) { } } @@ -5980,10 +5945,8 @@ function ($org) { } // Prepare organisatie data with forced UUID. - if ($organisation->getActive() === true) { - $statusValue = 'Actief'; - } else { $statusValue = 'Inactief'; + if ($organisation->getActive() === true) { } $organisationsToCreate[] = [ @@ -6108,16 +6071,12 @@ function ($org) { }//end foreach $totalTime = microtime(true) - $startTime; - if ($results['created_count'] > 0) { - $overallPerformance = $results['created_count'] / $totalTime; - } else { $overallPerformance = 0; + if ($results['created_count'] > 0) { } - if ($overallPerformance > 10) { - $estimatedImprovementValue = round($overallPerformance / 10, 1).'x faster than individual operations'; - } else { $estimatedImprovementValue = 'baseline'; + if ($overallPerformance > 10) { } $createdCount = $results['created_count']; @@ -6165,10 +6124,12 @@ private function determineOrganisationType(\OCA\OpenRegister\Db\Organisation $or $name = strtolower($organisation->getName()); if (strpos($name, 'gemeente') !== false) { - return 'Gemeente'; - } else if (strpos($name, 'provincie') !== false) { - return 'Provincie'; - } else if (strpos($name, 'ministerie') !== false) { + } + + if (strpos($name, 'provincie') !== false) { + } + + if (strpos($name, 'ministerie') !== false) { return 'Ministerie'; } else { return 'Leverancier'; diff --git a/lib/Service/SoftwareCatalogue/ContactPersonHandler.php b/lib/Service/SoftwareCatalogue/ContactPersonHandler.php index bc3480ad..f90e5949 100644 --- a/lib/Service/SoftwareCatalogue/ContactPersonHandler.php +++ b/lib/Service/SoftwareCatalogue/ContactPersonHandler.php @@ -43,7 +43,6 @@ * @SuppressWarnings(PHPMD.CouplingBetweenObjects) * @SuppressWarnings(PHPMD.TooManyMethods) * @SuppressWarnings(PHPMD.TooManyPublicMethods) - * @SuppressWarnings(PHPMD.ElseExpression) * @SuppressWarnings(PHPMD.CyclomaticComplexity) * @SuppressWarnings(PHPMD.NPathComplexity) * @SuppressWarnings(PHPMD.ExcessiveMethodLength) @@ -609,19 +608,19 @@ public function createUserAccount(object $contactpersoonObject, bool $isFirstCon ); return $user; - } else { - $this->_logger->error( - '❌ USER CREATION RETURNED NULL', - [ - 'app' => 'softwarecatalog', - 'username' => $username, - 'email' => $email, - 'contactpersoonId' => $contactId, - 'note' => 'No exception thrown but createUser returned null', - ] - ); }//end if + $this->_logger->error( + '❌ USER CREATION RETURNED NULL', + [ + 'app' => 'softwarecatalog', + 'username' => $username, + 'email' => $email, + 'contactpersoonId' => $contactId, + 'note' => 'No exception thrown but createUser returned null', + ] + ); + return null; } catch (\Exception $e) { $this->_logger->error( @@ -703,6 +702,17 @@ private function assignUserGroups(\OCP\IUser $user, array $objectData, bool $isF $organizationType = $this->getOrganizationType(organizationId: (string) $organizationId); $roleGroup = $this->getRoleGroupByOrganizationType(organizationType: $organizationType); + if (empty($roleGroup) === true) { + $this->_logger->warning( + 'No role mapping found for organization type', + [ + 'username' => $user->getUID(), + 'organizationId' => $organizationId, + 'organizationType' => $organizationType, + ] + ); + } + if (empty($roleGroup) === false) { $this->addUserToGroupWithCheck(user: $user, groupName: $roleGroup, type: 'organization-type-role'); @@ -719,24 +729,13 @@ private function assignUserGroups(\OCP\IUser $user, array $objectData, bool $isF 'rollenEnumValue' => $assignedRole, ] ); - } else { - $this->_logger->warning( - 'No role mapping found for organization type', - [ - 'username' => $user->getUID(), - 'organizationId' => $organizationId, - 'organizationType' => $organizationType, - ] - ); }//end if }//end if // Users are now tied to organisation entities in OpenRegister. // No need to add to organization-specific groups. - if ($isFirstContact === true) { - $organizationAdminGroupsValue = ($organizationAdminGroups ?? []); - } else { $organizationAdminGroupsValue = []; + if ($isFirstContact === true) { } $this->_logger->info( @@ -878,17 +877,7 @@ private function addUserToGroupWithCheck(\OCP\IUser $user, string $groupName, st return; } - if ($group->inGroup($user) === false) { - $group->addUser($user); - $this->_logger->info( - 'Added user to existing group', - [ - 'username' => $user->getUID(), - 'groupName' => $groupName, - 'type' => $type, - ] - ); - } else { + if ($group->inGroup($user) === true) { $this->_logger->debug( 'User already in group', [ @@ -897,7 +886,18 @@ private function addUserToGroupWithCheck(\OCP\IUser $user, string $groupName, st 'type' => $type, ] ); + return; } + + $group->addUser($user); + $this->_logger->info( + 'Added user to existing group', + [ + 'username' => $user->getUID(), + 'groupName' => $groupName, + 'type' => $type, + ] + ); } catch (\Exception $e) { $this->_logger->error( 'Failed to add user to group with check: '.$e->getMessage(), @@ -1015,15 +1015,17 @@ public function updateUserGroupsFromRoles(\OCP\IUser $user, array $newRoles, arr // For backward compatibility, try to find the user's contact data and update based on organization type. try { $contactObject = $this->findContactpersoonByUsername(username: $user->getUID()); - if (empty($contactObject) === false) { - $contactData = $contactObject->getObject(); - $this->updateUserGroupsFromContactData(user: $user, contactData: $contactData); - } else { + if (empty($contactObject) === true) { $this->_logger->warning( 'Could not find contact person data for user - cannot update groups', ['username' => $user->getUID()] ); } + + if (empty($contactObject) === false) { + $contactData = $contactObject->getObject(); + $this->updateUserGroupsFromContactData(user: $user, contactData: $contactData); + } } catch (\Exception $e) { $this->_logger->error( 'Failed to update user groups via legacy method: '.$e->getMessage(), @@ -1032,7 +1034,7 @@ public function updateUserGroupsFromRoles(\OCP\IUser $user, array $newRoles, arr 'exception' => $e, ] ); - } + }//end try }//end updateUserGroupsFromRoles() /** @@ -1247,10 +1249,9 @@ private function getDisplayNameFromContactData(array $contactData): string $fullName = implode(' ', $parts); if (empty($fullName) === false) { - return $fullName; - } else { - return ($contactData['email'] ?? $contactData['e-mailadres'] ?? 'Unknown User'); } + + return ($contactData['email'] ?? $contactData['e-mailadres'] ?? 'Unknown User'); }//end getDisplayNameFromContactData() /** @@ -1298,10 +1299,7 @@ public function storeContactNameFields(\OCP\IUser $user, array $contactData): vo // Try to set the role property. $roleProperty = $account->getProperty(\OCP\Accounts\IAccountManager::PROPERTY_ROLE); - if ($roleProperty !== null) { - $roleProperty->setValue($functie); - $accountManager->updateAccount($account); - } else { + if ($roleProperty === null) { // Property doesn't exist, create it. $account->setProperty( \OCP\Accounts\IAccountManager::PROPERTY_ROLE, @@ -1311,6 +1309,11 @@ public function storeContactNameFields(\OCP\IUser $user, array $contactData): vo ); $accountManager->updateAccount($account); } + + if ($roleProperty !== null) { + $roleProperty->setValue($functie); + $accountManager->updateAccount($account); + } } catch (\Exception $e) { // Fallback: store functie in user config if AccountManager fails. $this->config->setUserValue($userId, 'core', 'functie', $functie); @@ -1617,10 +1620,9 @@ public function getUserManager(string $username): ?string ); if (empty($manager) === false) { - return $manager; - } else { - return null; } + + return null; } catch (\Exception $e) { $this->_logger->error( 'Failed to get user manager: '.$e->getMessage(), @@ -1818,7 +1820,9 @@ private function sendUserCreationEmail(\OCP\IUser $user, array $objectData): voi 'email' => $user->getEMailAddress(), ] ); - } else { + } + + if ($success !== true) { $this->_logger->warning( 'Failed to send user creation email', [ @@ -1997,18 +2001,7 @@ public function setUserInactive(string $username): bool try { $user = $this->_userManager->get($username); - if (empty($user) === false) { - $user->setEnabled(false); - - $this->_logger->info( - 'Set user account to inactive', - [ - 'username' => $username, - ] - ); - - return true; - } else { + if (empty($user) === true) { $this->_logger->warning( 'User not found when trying to set inactive', [ @@ -2017,7 +2010,18 @@ public function setUserInactive(string $username): bool ); return false; - }//end if + } + + $user->setEnabled(false); + + $this->_logger->info( + 'Set user account to inactive', + [ + 'username' => $username, + ] + ); + + return true; } catch (\Exception $e) { $this->_logger->error( 'Failed to set user inactive: '.$e->getMessage(), @@ -2043,18 +2047,7 @@ public function setUserActive(string $username): bool try { $user = $this->_userManager->get($username); - if (empty($user) === false) { - $user->setEnabled(true); - - $this->_logger->info( - 'Set user account to active', - [ - 'username' => $username, - ] - ); - - return true; - } else { + if (empty($user) === true) { $this->_logger->warning( 'User not found when trying to set active', [ @@ -2063,7 +2056,18 @@ public function setUserActive(string $username): bool ); return false; - }//end if + } + + $user->setEnabled(true); + + $this->_logger->info( + 'Set user account to active', + [ + 'username' => $username, + ] + ); + + return true; } catch (\Exception $e) { $this->_logger->error( 'Failed to set user active: '.$e->getMessage(), diff --git a/lib/Service/SoftwareCatalogue/HierarchyHandler.php b/lib/Service/SoftwareCatalogue/HierarchyHandler.php index bd63b15b..7f3ec036 100644 --- a/lib/Service/SoftwareCatalogue/HierarchyHandler.php +++ b/lib/Service/SoftwareCatalogue/HierarchyHandler.php @@ -32,7 +32,6 @@ * @version GIT: * @link https://github.com/ConductionNL/SoftwareCatalog * - * @SuppressWarnings(PHPMD.ElseExpression) * @SuppressWarnings(PHPMD.CyclomaticComplexity) * @SuppressWarnings(PHPMD.NPathComplexity) * @SuppressWarnings(PHPMD.ExcessiveMethodLength) diff --git a/lib/Service/SoftwareCatalogue/OrganizationHandler.php b/lib/Service/SoftwareCatalogue/OrganizationHandler.php index 968a6517..64cfb02b 100644 --- a/lib/Service/SoftwareCatalogue/OrganizationHandler.php +++ b/lib/Service/SoftwareCatalogue/OrganizationHandler.php @@ -37,7 +37,6 @@ * @link https://github.com/ConductionNL/SoftwareCatalog * * @SuppressWarnings(PHPMD.ExcessiveClassComplexity) - * @SuppressWarnings(PHPMD.ElseExpression) * @SuppressWarnings(PHPMD.CyclomaticComplexity) * @SuppressWarnings(PHPMD.NPathComplexity) * @SuppressWarnings(PHPMD.ExcessiveMethodLength) @@ -186,15 +185,7 @@ public function ensureOrganizationGroup(object $organizationObject, array &$obje $registerId = $settingsService->getVoorzieningenRegisterId(); $organizationSchemaId = $settingsService->getSchemaIdForObjectType('organisatie'); - if ($registerId !== null && $organizationSchemaId !== null) { - $objectService->saveObject( - object: $organizationObject, - extend: [], - register: (int) $registerId, - schema: (int) $organizationSchemaId, - uuid: $organizationObject->getUuid() - ); - } else { + if ($registerId === null || $organizationSchemaId === null) { $this->_logger->warning( 'Missing register or schema ID for organization, using fallback save method', [ @@ -205,6 +196,16 @@ public function ensureOrganizationGroup(object $organizationObject, array &$obje $objectService->saveObject($organizationObject); } + if ($registerId !== null && $organizationSchemaId !== null) { + $objectService->saveObject( + object: $organizationObject, + extend: [], + register: (int) $registerId, + schema: (int) $organizationSchemaId, + uuid: $organizationObject->getUuid() + ); + } + $this->_logger->info( 'Created and assigned unique group to organization', [ @@ -353,16 +354,12 @@ public function processContactpersonen(object $organizationObject): array contactgegevensSchemaId: $contactgegevensSchemaId ); - if ($existingContactgegevens !== null) { - $logMessage = 'Updating existing contactgegevens object'; - } else { $logMessage = 'Creating new contactgegevens object'; + if ($existingContactgegevens !== null) { } - if ($existingContactgegevens !== null) { - $existingId = $existingContactgegevens->getUuid(); - } else { $existingId = null; + if ($existingContactgegevens !== null) { } $this->_logger->info( @@ -385,10 +382,8 @@ public function processContactpersonen(object $organizationObject): array ] ); - if (empty($titleParts) === false) { - $title = implode(' ', $titleParts); - } else { $title = $contactpersoon['email'] ?? 'Contact Person'; + if (empty($titleParts) === false) { } // Create contactgegevens object with proper schema. @@ -420,6 +415,13 @@ public function processContactpersonen(object $organizationObject): array } // Create or update the contactgegevens object via ObjectService. + // Create new contactgegevens object. + $contactgegevensObject = $objectService->saveObject( + object: $contactgegevensData, + extend: [], + register: $registerId, + schema: $contactgegevensSchemaId + ); if ($existingContactgegevens !== null) { // Update existing contactgegevens object. $contactgegevensObject = $objectService->saveObject( @@ -429,25 +431,16 @@ public function processContactpersonen(object $organizationObject): array schema: $contactgegevensSchemaId, uuid: $existingContactgegevens->getUuid() ); - } else { - // Create new contactgegevens object. - $contactgegevensObject = $objectService->saveObject( - object: $contactgegevensData, - extend: [], - register: $registerId, - schema: $contactgegevensSchemaId - ); - }//end if + } if ($contactgegevensObject !== null) { $processedContacts[] = $contactgegevensObject; + $actionLogMessage = 'Created new contactgegevens from contactpersoon'; + $actionValue = 'create'; if ($existingContactgegevens !== null) { $actionLogMessage = 'Updated existing contactgegevens from contactpersoon'; $actionValue = 'update'; - } else { - $actionLogMessage = 'Created new contactgegevens from contactpersoon'; - $actionValue = 'create'; } $this->_logger->info( @@ -695,26 +688,18 @@ function ($a, $b) { $userB = $this->_userManager->get($b); // Get user creation timestamps (fallback to 0 if not available). + $timeA = 0; if ($userA !== null) { $lastLoginA = $userA->getLastLogin(); if ($lastLoginA !== 0 && $lastLoginA !== null && $lastLoginA !== false) { - $timeA = $lastLoginA; - } else { - $timeA = 0; } - } else { - $timeA = 0; } + $timeB = 0; if ($userB !== null) { $lastLoginB = $userB->getLastLogin(); if ($lastLoginB !== 0 && $lastLoginB !== null && $lastLoginB !== false) { - $timeB = $lastLoginB; - } else { - $timeB = 0; } - } else { - $timeB = 0; } return $timeA <=> $timeB; diff --git a/lib/Service/SoftwareCatalogueService.php b/lib/Service/SoftwareCatalogueService.php index 53cce37e..4d1b3a96 100644 --- a/lib/Service/SoftwareCatalogueService.php +++ b/lib/Service/SoftwareCatalogueService.php @@ -43,7 +43,6 @@ * @SuppressWarnings(PHPMD.CouplingBetweenObjects) * @SuppressWarnings(PHPMD.TooManyMethods) * @SuppressWarnings(PHPMD.TooManyPublicMethods) - * @SuppressWarnings(PHPMD.ElseExpression) * @SuppressWarnings(PHPMD.CyclomaticComplexity) * @SuppressWarnings(PHPMD.NPathComplexity) * @SuppressWarnings(PHPMD.ExcessiveMethodLength) @@ -661,10 +660,8 @@ public function handleOrganizationUpdate(object $organizationObject, object $old if ($newBeoordeling === 'actief') { $becameActive = ($oldBeoordeling !== 'actief'); - if ($becameActive === true) { - $activeMessage = 'Organization became active, activating users'; - } else { $activeMessage = 'Organization is active'; + if ($becameActive === true) { } $this->_logger->info( @@ -721,10 +718,8 @@ public function handleOrganizationUpdate(object $organizationObject, object $old if ($newBeoordeling === 'inactief' || $newBeoordeling === 'deactief') { $becameInactive = ($oldBeoordeling === 'actief'); - if ($becameInactive === true) { - $inactiveMessage = 'Organization became inactive, deactivating users'; - } else { $inactiveMessage = 'Organization is inactive'; + if ($becameInactive === true) { } $this->_logger->info( @@ -1089,11 +1084,9 @@ public function handleContactpersoonUpdate(object $contactpersoonObject, object ); // Get current and old data for comparison. - $newData = $contactpersoonObject->getObject(); - if ($oldContactpersoonObject !== null) { - $oldData = $oldContactpersoonObject->getObject(); - } else { + $newData = $contactpersoonObject->getObject(); $oldData = []; + if ($oldContactpersoonObject !== null) { } $newRoles = $newData['roles'] ?? []; @@ -1517,10 +1510,8 @@ private function createOrganisationInOpenRegisterInternal( $userSession = \OC::$server->getUserSession(); $currentUser = $userSession->getUser(); - if ($currentUser !== null) { - $currentUserValue = $currentUser->getUID(); - } else { $currentUserValue = 'null'; + if ($currentUser !== null) { } $this->_logger->info( @@ -1649,9 +1640,8 @@ private function createOrganisationInOpenRegisterInternal( ] ); } + }//end if - return $savedOrganisation; - } else { $this->_logger->info( 'SoftwareCatalogueService: STEP 4A - Auth path: User logged in, creating org via mapper', [ @@ -1704,49 +1694,49 @@ private function createOrganisationInOpenRegisterInternal( ); $this->_logger->info('SoftwareCatalogueService: STEP 4F - Calling organisationMapper->createWithUuid()'); - try { - // Debug: Log the exact parameters being passed. - $this->_logger->info( - 'SoftwareCatalogueService: STEP 4F_DEBUG - Parameters for createWithUuid', - [ - 'name' => $mappedData['naam'] ?? 'Unknown Organization', - 'description' => $mappedData['website'] ?? '', - 'uuid' => $organizationUuid, - 'owner' => $currentUser->getUID(), - 'users' => $allUsernames, - 'isDefault' => false, - 'uuidLength' => strlen($organizationUuid), - 'uuidIsEmpty' => empty($organizationUuid) === true, - ] - ); + try { + // Debug: Log the exact parameters being passed. + $this->_logger->info( + 'SoftwareCatalogueService: STEP 4F_DEBUG - Parameters for createWithUuid', + [ + 'name' => $mappedData['naam'] ?? 'Unknown Organization', + 'description' => $mappedData['website'] ?? '', + 'uuid' => $organizationUuid, + 'owner' => $currentUser->getUID(), + 'users' => $allUsernames, + 'isDefault' => false, + 'uuidLength' => strlen($organizationUuid), + 'uuidIsEmpty' => empty($organizationUuid) === true, + ] + ); - $organisation = $organisationMapper->createWithUuid( - $mappedData['naam'] ?? 'Unknown Organization', - $mappedData['website'] ?? '', - // Use website as description. - $organizationUuid, - // Pass the original UUID. - $currentUser->getUID(), - // Set current user as owner. - $allUsernames, - // Add all users including contact persons. - false - // Not default. - ); - $this->_logger->info( - 'SoftwareCatalogueService: STEP 4G - organisationMapper->createWithUuid() completed' - ); - } catch (\Exception $e) { - $this->_logger->error( - 'SoftwareCatalogueService: STEP 4G - organisationMapper->createWithUuid() failed', - [ - 'error' => $e->getMessage(), - 'errorClass' => get_class($e), - 'trace' => $e->getTraceAsString(), - ] - ); - throw $e; - }//end try + $organisation = $organisationMapper->createWithUuid( + $mappedData['naam'] ?? 'Unknown Organization', + $mappedData['website'] ?? '', + // Use website as description. + $organizationUuid, + // Pass the original UUID. + $currentUser->getUID(), + // Set current user as owner. + $allUsernames, + // Add all users including contact persons. + false + // Not default. + ); + $this->_logger->info( + 'SoftwareCatalogueService: STEP 4G - organisationMapper->createWithUuid() completed' + ); + } catch (\Exception $e) { + $this->_logger->error( + 'SoftwareCatalogueService: STEP 4G - organisationMapper->createWithUuid() failed', + [ + 'error' => $e->getMessage(), + 'errorClass' => get_class($e), + 'trace' => $e->getTraceAsString(), + ] + ); + throw $e; + }//end try // Note: OpenRegister Organisation entity doesn't have status or type fields. // These are managed in the SoftwareCatalog object, not in the OpenRegister organisation. @@ -1761,7 +1751,6 @@ private function createOrganisationInOpenRegisterInternal( ); return $organisation; - }//end if }//end createOrganisationInOpenRegisterInternal() /** @@ -2851,9 +2840,8 @@ public function addContactpersoonToOrganization(object $contactpersoonObject): b 'updatedUsers' => $organizationUsers, ] ); + }//end if - return true; - } else { $this->_logger->debug( 'SoftwareCatalogueService: Contactpersoon already in organization', [ @@ -2863,7 +2851,6 @@ public function addContactpersoonToOrganization(object $contactpersoonObject): b ); return true; // Already there, consider it successful. - }//end if } catch (\OCP\AppFramework\Db\DoesNotExistException $e) { $this->_logger->error( 'SoftwareCatalogueService: Organization not found for contactpersoon', @@ -2972,8 +2959,8 @@ private function handleOwnershipAssignment(object $organizationObject): void ] ); sleep($retryDelay); - continue; - } else { + } + $this->_logger->warning( 'SoftwareCatalogueService: Primary contact person still has no username after retries', [ @@ -2982,7 +2969,6 @@ private function handleOwnershipAssignment(object $organizationObject): void ] ); return; - }//end if }//end if // Get the organization entity UUID - use the same UUID as the organization object. @@ -3125,8 +3111,8 @@ private function handleOwnershipAssignment(object $organizationObject): void ] ); sleep($retryDelay); - continue; - } else { + } + $this->_logger->error( 'SoftwareCatalogueService: Primary contact person not found after retries', [ @@ -3135,7 +3121,6 @@ private function handleOwnershipAssignment(object $organizationObject): void ] ); return; - }//end if }//end try }//end for } catch (\Exception $e) { diff --git a/lib/Service/SymfonyEmailService.php b/lib/Service/SymfonyEmailService.php index 3035307a..74267946 100644 --- a/lib/Service/SymfonyEmailService.php +++ b/lib/Service/SymfonyEmailService.php @@ -42,7 +42,6 @@ * * @SuppressWarnings(PHPMD.ExcessiveClassLength) * @SuppressWarnings(PHPMD.ExcessiveClassComplexity) - * @SuppressWarnings(PHPMD.ElseExpression) * @SuppressWarnings(PHPMD.CyclomaticComplexity) * @SuppressWarnings(PHPMD.NPathComplexity) * @SuppressWarnings(PHPMD.ExcessiveMethodLength) @@ -762,10 +761,8 @@ public function sendUserCreationEmail(array $user, array $organization=[]): bool ); // Prepare template data. - if (empty($userName) === false) { - $displayName = $userName; - } else { $displayName = 'Gebruiker'; + if (empty($userName) === false) { } $templateData = [ @@ -878,10 +875,8 @@ public function sendUserUpdateEmail(array $user, array $organization=[]): bool ); // Prepare template data. - if (empty($userName) === false) { - $displayName = $userName; - } else { $displayName = 'Gebruiker'; + if (empty($userName) === false) { } $templateData = [ @@ -995,10 +990,8 @@ public function sendUserPasswordEmail(array $user, string $password, array $orga ); // Prepare template data. - if (empty($userName) === false) { - $displayName = $userName; - } else { $displayName = 'Gebruiker'; + if (empty($userName) === false) { } $templateData = [ @@ -1559,13 +1552,12 @@ public function isEmailSystemConfigured(): array $configured = ($hasCredentials === true && $hasTemplates === true); + $reason = $this->getConfigurationIssues( + hasCredentials: $hasCredentials, + hasTemplates: $hasTemplates + ); if ($configured === true) { $reason = 'Email system fully configured'; - } else { - $reason = $this->getConfigurationIssues( - hasCredentials: $hasCredentials, - hasTemplates: $hasTemplates - ); } return [ diff --git a/lib/Service/ViewService.php b/lib/Service/ViewService.php index 2fd7ed76..4c6ebe01 100644 --- a/lib/Service/ViewService.php +++ b/lib/Service/ViewService.php @@ -42,7 +42,6 @@ * * @SuppressWarnings(PHPMD.ExcessiveClassLength) * @SuppressWarnings(PHPMD.ExcessiveClassComplexity) - * @SuppressWarnings(PHPMD.ElseExpression) * @SuppressWarnings(PHPMD.CyclomaticComplexity) * @SuppressWarnings(PHPMD.NPathComplexity) * @SuppressWarnings(PHPMD.ExcessiveMethodLength) @@ -1515,19 +1514,18 @@ private function transformViewRelationships(array $viewRelationships): array $transformedRelationship['identifier'] = $relationship['viewRelationshipId'] ?? null; // Add properties if available (check for relationship properties). + // Default: create properties array with relationship name if available. + $properties = []; + if (isset($relationship['label']) === true) { + $properties[] = [ + 'propertyDefinitionRef' => 'propid-62', + 'value' => $relationship['label'], + ]; + } + + $transformedRelationship['properties'] = $properties; if (isset($relationship['properties']) === true) { $transformedRelationship['properties'] = $relationship['properties']; - } else { - // Create properties array with relationship name if available. - $properties = []; - if (isset($relationship['label']) === true) { - $properties[] = [ - 'propertyDefinitionRef' => 'propid-62', - 'value' => $relationship['label'], - ]; - } - - $transformedRelationship['properties'] = $properties; } // Ensure bendpoints are properly formatted. diff --git a/src/components/GenericObjectTable.vue b/src/components/GenericObjectTable.vue deleted file mode 100644 index 067604ab..00000000 --- a/src/components/GenericObjectTable.vue +++ /dev/null @@ -1,1419 +0,0 @@ -/** - * GenericObjectTable.vue - * Generic component for displaying objects with cards and table view - * @category Components - * @package opencatalogi - * @author Ruben Linde - * @copyright 2024 - * @license AGPL-3.0-or-later - * @version 1.0.0 - * @link https://github.com/opencatalogi/opencatalogi - */ - - - - - - - {{ action.label }} - - - - -
-
- - -
-
- - -
- - {{ t('softwarecatalog', 'Cards') }} - - - {{ t('softwarecatalog', 'Table') }} - -
- - - - - - {{ action.label }} - - - - - - - - - - - {{ meta.label }} - - - - - - {{ prop.label }} - - - - - - - - - - - - -
- - -
- - - - - - - - - - - - diff --git a/src/components/SelectedObjectsList.vue b/src/components/SelectedObjectsList.vue index 30e11df5..cab0f0d9 100644 --- a/src/components/SelectedObjectsList.vue +++ b/src/components/SelectedObjectsList.vue @@ -8,7 +8,6 @@ */ diff --git a/src/modals/object/ChangeOrganisatieStatusDialog.vue b/src/modals/object/ChangeOrganisatieStatusDialog.vue index 2139181c..563b55aa 100644 --- a/src/modals/object/ChangeOrganisatieStatusDialog.vue +++ b/src/modals/object/ChangeOrganisatieStatusDialog.vue @@ -11,7 +11,6 @@ */ diff --git a/src/modals/object/DeleteObject.vue b/src/modals/object/DeleteObject.vue index 3830bd7b..9be4c52b 100644 --- a/src/modals/object/DeleteObject.vue +++ b/src/modals/object/DeleteObject.vue @@ -1,5 +1,4 @@ diff --git a/src/modals/object/DownloadObject.vue b/src/modals/object/DownloadObject.vue index 3c1d4001..a0747dd4 100644 --- a/src/modals/object/DownloadObject.vue +++ b/src/modals/object/DownloadObject.vue @@ -1,5 +1,4 @@ diff --git a/src/modals/object/LockObject.vue b/src/modals/object/LockObject.vue index 0354189c..d62e48ee 100644 --- a/src/modals/object/LockObject.vue +++ b/src/modals/object/LockObject.vue @@ -1,5 +1,4 @@ diff --git a/src/modals/object/MassDeleteObject.vue b/src/modals/object/MassDeleteObject.vue index c83dae22..9ccd1dd2 100644 --- a/src/modals/object/MassDeleteObject.vue +++ b/src/modals/object/MassDeleteObject.vue @@ -8,7 +8,6 @@ */ @@ -206,7 +205,7 @@ export default { } - - - - - -