Completed
Push — 3.5.0 ( 6d2c82 )
by
unknown
24s
created
src/ZohoDatabaseCopier.php 1 patch
Spacing   +53 added lines, -53 removed lines patch added patch discarded remove patch
@@ -73,11 +73,11 @@  discard block
 block discarded – undo
73 73
     {
74 74
         $users = $this->fetchAllUsersFromZoho();
75 75
         $tableName = 'users';
76
-        $this->logger->info('Fetched ' . count($users) . ' records for table ' . $tableName);
76
+        $this->logger->info('Fetched '.count($users).' records for table '.$tableName);
77 77
 
78 78
         $table = $this->connection->getSchemaManager()->createSchema()->getTable($tableName);
79 79
 
80
-        $select = $this->connection->prepare('SELECT * FROM ' . $tableName . ' WHERE id = :id');
80
+        $select = $this->connection->prepare('SELECT * FROM '.$tableName.' WHERE id = :id');
81 81
 
82 82
         $this->connection->beginTransaction();
83 83
         foreach ($users as $user) {
@@ -152,12 +152,12 @@  discard block
 block discarded – undo
152 152
         while (true) {
153 153
             $oauthToken = $zohoClient->getZohoOAuthClient()->getAccessToken(ZOHO_CRM_CLIENT_CURRENT_USER_EMAIL);
154 154
 
155
-            $this->logger->info('Getting users for page ' . $page . '...');
156
-            $response = $client->request('GET', 'https://' . (ZOHO_CRM_SANDBOX === 'true' ? 'sandbox' : 'www') . '.zohoapis.com/crm/v2/users', [
155
+            $this->logger->info('Getting users for page '.$page.'...');
156
+            $response = $client->request('GET', 'https://'.(ZOHO_CRM_SANDBOX === 'true' ? 'sandbox' : 'www').'.zohoapis.com/crm/v2/users', [
157 157
                 'http_errors' => false,
158 158
                 'verify' => false,
159 159
                 'headers' => [
160
-                    'Authorization' => 'Zoho-oauthtoken ' . $oauthToken,
160
+                    'Authorization' => 'Zoho-oauthtoken '.$oauthToken,
161 161
                 ],
162 162
                 'query' => [
163 163
                     'type' => 'AllUsers',
@@ -182,11 +182,11 @@  discard block
 block discarded – undo
182 182
                     break;
183 183
                 }
184 184
             } else {
185
-                $this->logger->error('Cannot get users for page ' . $page . ': status: ' . $response->getStatusCode() . '. Error: ' . $response->getBody()->getContents());
185
+                $this->logger->error('Cannot get users for page '.$page.': status: '.$response->getStatusCode().'. Error: '.$response->getBody()->getContents());
186 186
                 break;
187 187
             }
188 188
         }
189
-        $this->logger->notice('Finished fetching ' . $totalUsers . ' users from Zoho.');
189
+        $this->logger->notice('Finished fetching '.$totalUsers.' users from Zoho.');
190 190
 
191 191
         return $finalUsers;
192 192
     }
@@ -243,7 +243,7 @@  discard block
 block discarded – undo
243 243
                         $lastPageInConfig = '1';
244 244
                     }
245 245
                     $dateModifiedSince = new \DateTime($lastDateInConfig, new \DateTimeZone($dao->getZohoClient()->getTimezone()));
246
-                    $recordsPage = (int)$lastPageInConfig;
246
+                    $recordsPage = (int) $lastPageInConfig;
247 247
                 } else {
248 248
                     $findDateByModifiedTime = true;
249 249
                 }
@@ -258,10 +258,10 @@  discard block
 block discarded – undo
258 258
                 } else {
259 259
                     $latestDateValue = null;
260 260
                     if ($tableHasColumnModifiedTime) {
261
-                        $latestDateValue = $this->connection->fetchColumn('SELECT MAX(modifiedTime) FROM ' . $tableName);
261
+                        $latestDateValue = $this->connection->fetchColumn('SELECT MAX(modifiedTime) FROM '.$tableName);
262 262
                     }
263 263
                     if (!$latestDateValue && $tableHasColumnCreatedTime) {
264
-                        $latestDateValue = $this->connection->fetchColumn('SELECT MAX(createdTime) FROM ' . $tableName);
264
+                        $latestDateValue = $this->connection->fetchColumn('SELECT MAX(createdTime) FROM '.$tableName);
265 265
                     }
266 266
 
267 267
                     if ($latestDateValue !== null) {
@@ -314,7 +314,7 @@  discard block
 block discarded – undo
314 314
             try {
315 315
                 $records = $dao->getRecords(null, $sortColumn, $sortOrder, $dateModifiedSince, $recordsPage, 200, $stopAndhasMoreResults);
316 316
             } catch (ZCRMException $exception) {
317
-                $this->logger->error('Error when getting updated records for module ' . $dao->getPluralModuleName() . ' and page ' . $recordsPage . ': ' . $exception->getMessage(), [
317
+                $this->logger->error('Error when getting updated records for module '.$dao->getPluralModuleName().' and page '.$recordsPage.': '.$exception->getMessage(), [
318 318
                     'exception' => $exception,
319 319
                 ]);
320 320
                 if ($throwErrors) {
@@ -327,17 +327,17 @@  discard block
 block discarded – undo
327 327
                 if ($zohoSyncConfigTableExists) {
328 328
                     $lastDate = $dateModifiedSince ? $dateModifiedSince->format('Y-m-d H:i:s') : $currentDateTime->format('Y-m-d H:i:s');
329 329
                     $this->upsertZohoConfig('FETCH_RECORDS_MODIFIED_SINCE__DATE', $tableName, $lastDate);
330
-                    $this->upsertZohoConfig('FETCH_RECORDS_MODIFIED_SINCE__PAGE', $tableName, (string)$recordsPage);
330
+                    $this->upsertZohoConfig('FETCH_RECORDS_MODIFIED_SINCE__PAGE', $tableName, (string) $recordsPage);
331 331
                 }
332 332
                 $recordsPage++;
333 333
             } else {
334 334
                 if ($zohoSyncConfigTableExists) {
335 335
                     $latestDateToSave = $currentDateTime->format('Y-m-d H:i:s');
336 336
                     if ($tableHasColumnModifiedTime) {
337
-                        $latestDateToSave = $this->connection->fetchColumn('SELECT MAX(modifiedTime) FROM ' . $tableName);
337
+                        $latestDateToSave = $this->connection->fetchColumn('SELECT MAX(modifiedTime) FROM '.$tableName);
338 338
                     }
339 339
                     if (!$latestDateToSave && $tableHasColumnCreatedTime) {
340
-                        $latestDateToSave = $this->connection->fetchColumn('SELECT MAX(createdTime) FROM ' . $tableName);
340
+                        $latestDateToSave = $this->connection->fetchColumn('SELECT MAX(createdTime) FROM '.$tableName);
341 341
                     }
342 342
                     if (!$latestDateToSave) {
343 343
                         $latestDateToSave = $currentDateTime->format('Y-m-d H:i:s');
@@ -347,13 +347,13 @@  discard block
 block discarded – undo
347 347
                 }
348 348
             }
349 349
             $totalRecords = count($records);
350
-            $this->logger->debug($totalRecords . ' records fetched.');
350
+            $this->logger->debug($totalRecords.' records fetched.');
351 351
 
352 352
             // Save of the records in db
353 353
             $this->logger->info(sprintf('Inserting/updating %s records into table %s...', $totalRecords, $tableName));
354
-            $select = $this->connection->prepare('SELECT * FROM ' . $tableName . ' WHERE id = :id');
354
+            $select = $this->connection->prepare('SELECT * FROM '.$tableName.' WHERE id = :id');
355 355
             $this->connection->beginTransaction();
356
-            $logOffset = (int)ceil($totalRecords / 4);
356
+            $logOffset = (int) ceil($totalRecords / 4);
357 357
             $processedRecords = 0;
358 358
             $dataInsertedInDb = 0;
359 359
             $dataUpdatedInDb = 0;
@@ -421,7 +421,7 @@  discard block
 block discarded – undo
421 421
 
422 422
                         // If there is some columns updated in local_update, we skip them to avoid Zoho values to overide them
423 423
                         if ($localUpdateTableExists && $result['uid']) {
424
-                            $selectRecordInLocalUpdate = $this->connection->prepare('SELECT field_name FROM local_update WHERE table_name = "' . $tableName . '" AND uid = :uid');
424
+                            $selectRecordInLocalUpdate = $this->connection->prepare('SELECT field_name FROM local_update WHERE table_name = "'.$tableName.'" AND uid = :uid');
425 425
                             $selectRecordInLocalUpdate->execute(['uid' => $result['uid']]);
426 426
                             $resultsInLocalUpdate = $selectRecordInLocalUpdate->fetchAll(\PDO::FETCH_ASSOC);
427 427
                             $fieldsUpdated = [];
@@ -468,7 +468,7 @@  discard block
 block discarded – undo
468 468
             try {
469 469
                 $deletedRecords = $dao->getDeletedRecordIds($dateModifiedSince, $recordsDeletedPage, 200, $stopAndhasMoreResults);
470 470
             } catch (ZCRMException $exception) {
471
-                $this->logger->error('Error when getting deleted records for module ' . $dao->getPluralModuleName() . ' and page ' . $recordsDeletedPage . ': ' . $exception->getMessage(), [
471
+                $this->logger->error('Error when getting deleted records for module '.$dao->getPluralModuleName().' and page '.$recordsDeletedPage.': '.$exception->getMessage(), [
472 472
                     'exception' => $exception,
473 473
                 ]);
474 474
                 if ($throwErrors) {
@@ -481,13 +481,13 @@  discard block
 block discarded – undo
481 481
                 ++$recordsDeletedPage;
482 482
             }
483 483
             $totalRecordsDeleted = count($deletedRecords);
484
-            $this->logger->debug($totalRecordsDeleted . ' records fetched.');
484
+            $this->logger->debug($totalRecordsDeleted.' records fetched.');
485 485
 
486 486
             $this->logger->info(sprintf('Deleting %d records from table %s...', $totalRecordsDeleted, $tableName));
487 487
             $this->connection->beginTransaction();
488
-            $sqlStatementUid = 'select uid from ' . $this->connection->quoteIdentifier($tableName) . ' where id = :id';
488
+            $sqlStatementUid = 'select uid from '.$this->connection->quoteIdentifier($tableName).' where id = :id';
489 489
             $processedRecords = 0;
490
-            $logOffset = (int)ceil($totalRecordsDeleted / 4);
490
+            $logOffset = (int) ceil($totalRecordsDeleted / 4);
491 491
             $dataDeletedInDb = 0;
492 492
             if ($totalRecordsDeleted) {
493 493
                 foreach ($deletedRecords as $deletedRecord) {
@@ -535,7 +535,7 @@  discard block
 block discarded – undo
535 535
         $table = $this->connection->getSchemaManager()->createSchema()->getTable($tableName);
536 536
         $apiModuleName = $dao->getPluralModuleName();
537 537
 
538
-        $this->logger->notice('Starting bulk fetch for module ' . $apiModuleName . '...');
538
+        $this->logger->notice('Starting bulk fetch for module '.$apiModuleName.'...');
539 539
 
540 540
         $zohoClient = new ZohoClient([
541 541
             'client_id' => ZOHO_CRM_CLIENT_ID,
@@ -554,11 +554,11 @@  discard block
 block discarded – undo
554 554
             $oauthToken = $zohoClient->getZohoOAuthClient()->getAccessToken(ZOHO_CRM_CLIENT_CURRENT_USER_EMAIL);
555 555
 
556 556
             // Step 1: Create a bulk read job
557
-            $this->logger->info('Creating read job for module ' . $apiModuleName . ' and page ' . $page . '...');
558
-            $response = $client->request('POST', 'https://' . (ZOHO_CRM_SANDBOX === 'true' ? 'sandbox' : 'www') . '.zohoapis.com/crm/bulk/v2/read', [
557
+            $this->logger->info('Creating read job for module '.$apiModuleName.' and page '.$page.'...');
558
+            $response = $client->request('POST', 'https://'.(ZOHO_CRM_SANDBOX === 'true' ? 'sandbox' : 'www').'.zohoapis.com/crm/bulk/v2/read', [
559 559
                 'http_errors' => false,
560 560
                 'headers' => [
561
-                    'Authorization' => 'Zoho-oauthtoken ' . $oauthToken,
561
+                    'Authorization' => 'Zoho-oauthtoken '.$oauthToken,
562 562
                 ],
563 563
                 'json' => [
564 564
                     'query' => [
@@ -575,23 +575,23 @@  discard block
 block discarded – undo
575 575
                 $jobId = $json['data'][0]['details']['id'];
576 576
                 // We don't care about the job status right now, it will be checked later
577 577
             } else {
578
-                $this->logger->error('Cannot create bulk read query for module ' . $apiModuleName . ': status: ' . $response->getStatusCode() . '. Status: ' . $response->getBody()->getContents());
578
+                $this->logger->error('Cannot create bulk read query for module '.$apiModuleName.': status: '.$response->getStatusCode().'. Status: '.$response->getBody()->getContents());
579 579
                 break;
580 580
             }
581 581
 
582 582
             if ($jobId === null) {
583
-                $this->logger->error('JobID cannot be null. json:' . $resultStr);
583
+                $this->logger->error('JobID cannot be null. json:'.$resultStr);
584 584
                 break;
585 585
             }
586 586
 
587 587
             // Step 2: Check job status
588 588
             $jobDetails = null;
589 589
             while (true) {
590
-                $this->logger->info('Checking job ' . $jobId . ' status for module ' . $apiModuleName . ' and page ' . $page . '...');
591
-                $response = $client->request('GET', 'https://' . (ZOHO_CRM_SANDBOX === 'true' ? 'sandbox' : 'www') . '.zohoapis.com/crm/bulk/v2/read/' . $jobId, [
590
+                $this->logger->info('Checking job '.$jobId.' status for module '.$apiModuleName.' and page '.$page.'...');
591
+                $response = $client->request('GET', 'https://'.(ZOHO_CRM_SANDBOX === 'true' ? 'sandbox' : 'www').'.zohoapis.com/crm/bulk/v2/read/'.$jobId, [
592 592
                     'http_errors' => false,
593 593
                     'headers' => [
594
-                        'Authorization' => 'Zoho-oauthtoken ' . $oauthToken,
594
+                        'Authorization' => 'Zoho-oauthtoken '.$oauthToken,
595 595
                     ],
596 596
                 ]);
597 597
                 if ($response->getStatusCode() >= 200 && $response->getStatusCode() < 300) {
@@ -609,15 +609,15 @@  discard block
 block discarded – undo
609 609
                             $jobDetails = $json;
610 610
                             break;
611 611
                         } else {
612
-                            $this->logger->info('Unsupported job status: ' . $resultStr);
612
+                            $this->logger->info('Unsupported job status: '.$resultStr);
613 613
                             break;
614 614
                         }
615 615
                     } else {
616
-                        $this->logger->error('Unsupported response: ' . $resultStr);
616
+                        $this->logger->error('Unsupported response: '.$resultStr);
617 617
                         break;
618 618
                     }
619 619
                 } else {
620
-                    $this->logger->error('Cannot get bulk job status query for module ' . $apiModuleName . ': status: ' . $response->getStatusCode() . '. Status: ' . $response->getBody()->getContents());
620
+                    $this->logger->error('Cannot get bulk job status query for module '.$apiModuleName.': status: '.$response->getStatusCode().'. Status: '.$response->getBody()->getContents());
621 621
                     break;
622 622
                 }
623 623
                 sleep(15);
@@ -625,31 +625,31 @@  discard block
 block discarded – undo
625 625
 
626 626
             // Step 3: Download the result
627 627
             if ($jobDetails === null) {
628
-                $this->logger->error('JobDetails cannot be empty. json:' . $resultStr);
628
+                $this->logger->error('JobDetails cannot be empty. json:'.$resultStr);
629 629
                 break;
630 630
             }
631 631
             $this->logger->debug(json_encode($jobDetails));
632
-            $this->logger->info('Downloading zip file for module ' . $apiModuleName . ' and page ' . $page . '...');
633
-            $jobZipFile = '/tmp/job_' . $dao->getZCRMModule()->getAPIName() . '_' . $jobDetails['data'][0]['id'] . '.zip';
632
+            $this->logger->info('Downloading zip file for module '.$apiModuleName.' and page '.$page.'...');
633
+            $jobZipFile = '/tmp/job_'.$dao->getZCRMModule()->getAPIName().'_'.$jobDetails['data'][0]['id'].'.zip';
634 634
             $jobCsvPath = '/tmp/job_extract';
635
-            $jobCsvFile = '/tmp/job_extract/' . $jobDetails['data'][0]['id'] . '.csv';
635
+            $jobCsvFile = '/tmp/job_extract/'.$jobDetails['data'][0]['id'].'.csv';
636 636
             $canProcessCsv = false;
637 637
 
638
-            $response = $client->request('GET', 'https://' . (ZOHO_CRM_SANDBOX === 'true' ? 'sandbox' : 'www') . '.zohoapis.com/crm/bulk/v2/read/' . $jobId . '/result', [
638
+            $response = $client->request('GET', 'https://'.(ZOHO_CRM_SANDBOX === 'true' ? 'sandbox' : 'www').'.zohoapis.com/crm/bulk/v2/read/'.$jobId.'/result', [
639 639
                 'http_errors' => false,
640 640
                 'headers' => [
641
-                    'Authorization' => 'Zoho-oauthtoken ' . $oauthToken,
641
+                    'Authorization' => 'Zoho-oauthtoken '.$oauthToken,
642 642
                 ],
643 643
                 'sink' => $jobZipFile,
644 644
             ]);
645 645
             if ($response->getStatusCode() >= 200 && $response->getStatusCode() < 300) {
646
-                $this->logger->info('Extracting ' . $jobZipFile . ' file for module ' . $apiModuleName . ' and page ' . $page . '...');
646
+                $this->logger->info('Extracting '.$jobZipFile.' file for module '.$apiModuleName.' and page '.$page.'...');
647 647
                 $zip = new ZipArchive();
648 648
                 $res = $zip->open($jobZipFile);
649 649
                 if ($res === true) {
650 650
                     $zip->extractTo($jobCsvPath);
651 651
                     $zip->close();
652
-                    $this->logger->info('File extracted in ' . $jobCsvFile);
652
+                    $this->logger->info('File extracted in '.$jobCsvFile);
653 653
                     $canProcessCsv = true;
654 654
                 } else {
655 655
                     switch ($res) {
@@ -681,11 +681,11 @@  discard block
 block discarded – undo
681 681
                             $zipErrorMessage = "Unknow (Code $res)";
682 682
                             break;
683 683
                     }
684
-                    $this->logger->error('Error when extracting zip file: ' . $zipErrorMessage);
684
+                    $this->logger->error('Error when extracting zip file: '.$zipErrorMessage);
685 685
                     break;
686 686
                 }
687 687
             } else {
688
-                $this->logger->error('Cannot download results for module ' . $apiModuleName . ': status: ' . $response->getStatusCode() . '. Status: ' . $response->getBody()->getContents());
688
+                $this->logger->error('Cannot download results for module '.$apiModuleName.': status: '.$response->getStatusCode().'. Status: '.$response->getBody()->getContents());
689 689
                 break;
690 690
             }
691 691
 
@@ -706,7 +706,7 @@  discard block
 block discarded – undo
706 706
             $this->logger->info('Saving records to db...');
707 707
             $nbRecords = $jobDetails['data'][0]['result']['count'];
708 708
             $whenToLog = ceil($nbRecords / 100);
709
-            $this->logger->info($nbRecords . ' records to save');
709
+            $this->logger->info($nbRecords.' records to save');
710 710
             $nbSaved = 0;
711 711
             $handle = fopen($jobCsvFile, 'r');
712 712
             $fields = [];
@@ -724,30 +724,30 @@  discard block
 block discarded – undo
724 724
                             $recordDataToInsert[$decodedColumnName] = $value === '' ? null : $value;
725 725
                         } else {
726 726
                             if ($columnName === 'Owner' || $columnName === 'Created_By' || $columnName === 'Modified_By') {
727
-                                $recordDataToInsert[$decodedColumnName . '_OwnerID'] = $value === '' ? null : $value;
728
-                                $recordDataToInsert[$decodedColumnName . '_OwnerName'] = $users[$value] ?? null;
729
-                            } elseif ($table->hasColumn($decodedColumnName . '_ID')) {
730
-                                $recordDataToInsert[$decodedColumnName . '_ID'] = $value === '' ? null : $value;
727
+                                $recordDataToInsert[$decodedColumnName.'_OwnerID'] = $value === '' ? null : $value;
728
+                                $recordDataToInsert[$decodedColumnName.'_OwnerName'] = $users[$value] ?? null;
729
+                            } elseif ($table->hasColumn($decodedColumnName.'_ID')) {
730
+                                $recordDataToInsert[$decodedColumnName.'_ID'] = $value === '' ? null : $value;
731 731
                             }
732 732
                         }
733 733
                     }
734 734
                     $this->connection->insert($tableName, $recordDataToInsert);
735 735
                     ++$nbSaved;
736 736
                     if (($nbSaved % $whenToLog) === 0) {
737
-                        $this->logger->info($nbSaved . '/' . $nbRecords . ' records processed');
737
+                        $this->logger->info($nbSaved.'/'.$nbRecords.' records processed');
738 738
                     }
739 739
                 }
740
-                $this->logger->info($nbSaved . ' records saved for module ' . $apiModuleName . ' and page ' . $page);
740
+                $this->logger->info($nbSaved.' records saved for module '.$apiModuleName.' and page '.$page);
741 741
                 fclose($handle);
742 742
             }
743 743
 
744 744
             // Step 5: Check if there is more results
745 745
             $hasMoreRecords = $jobDetails['data'][0]['result']['more_records'];
746 746
             if (!$hasMoreRecords) {
747
-                $this->logger->info('No more records for the module ' . $apiModuleName);
747
+                $this->logger->info('No more records for the module '.$apiModuleName);
748 748
                 break;
749 749
             }
750
-            $this->logger->info('More records to fetch for the module ' . $apiModuleName);
750
+            $this->logger->info('More records to fetch for the module '.$apiModuleName);
751 751
             ++$page;
752 752
         }
753 753
     }
Please login to merge, or discard this patch.