Completed
Push — master ( c6f8d8...15d0ed )
by Tim
02:10
created

CalMigrationUpdate   B

Complexity

Total Complexity 49

Size/Duplication

Total Lines 1014
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 6

Importance

Changes 0
Metric Value
wmc 49
lcom 1
cbo 6
dl 0
loc 1014
rs 8.0239
c 0
b 0
f 0

22 Methods

Rating   Name   Duplication   Size   Complexity  
A checkForUpdate() 0 12 4
A performUpdate() 0 12 1
B performCalEventUpdate() 0 61 2
A performExceptionEventUpdate() 0 41 2
B performLinkEventToConfigurationGroup() 0 56 3
A performSysFileReferenceUpdate() 0 47 3
A performLinkEventToCategory() 0 42 2
A updateEventWithConfiguration() 0 28 2
A addValueToCsv() 0 14 2
A addConfigurationIdToEvent() 0 11 2
A updateEvent() 0 27 1
A findEventByImportId() 0 23 1
A findEventExcludeConfiguration() 0 31 2
B getExceptionConfigurationForExceptionGroup() 0 75 5
A mapFrequency() 0 16 2
B performSysCategoryUpdate() 0 85 3
A getSysCategoryParentUid() 0 18 1
A getCalendarizeEventUid() 0 25 1
A getCalendarizeCategoryUid() 0 25 1
A buildConfigurations() 0 52 1
A migrateDate() 0 11 2
B getNonMigratedCalIds() 0 63 6

How to fix   Complexity   

Complex Class

Complex classes like CalMigrationUpdate often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use CalMigrationUpdate, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
/**
4
 * CalMigrationUpdate.
5
 */
6
declare(strict_types=1);
7
8
namespace HDNET\Calendarize\Updates;
9
10
use HDNET\Calendarize\Service\IndexerService;
11
use HDNET\Calendarize\Utility\HelperUtility;
12
use TYPO3\CMS\Core\Database\Query\Restriction\DeletedRestriction;
13
use TYPO3\CMS\Core\Utility\ExtensionManagementUtility;
14
use TYPO3\CMS\Core\Utility\GeneralUtility;
15
use TYPO3\CMS\Install\Updates\AbstractUpdate;
16
17
/**
18
 * CalMigrationUpdate.
19
 *
20
 * If using the slots please use the m with func_get_args!
21
 * Example:
22
 * /**
23
 *  * @signalClass \HDNET\Calendarize\Updates\CalMigrationUpdate
24
 *  * @signalName getCalendarizeEventUid
25
 *  *
26
 *
27
 *  *@return array
28
 *  *
29
 * public function getCalendarizeEventUid()
30
 * {
31
 *    $args = func_get_args();
32
 *    list($table, $dbQueries, $call) = $args;
33
 *
34
 *    $variables = [
35
 *        'table'     => self::EVENT_TABLE,
36
 *        'dbQueries' => $dbQueries
37
 *    ];
38
 *
39
 *    return $variables;
40
 * }
41
 */
42
class CalMigrationUpdate extends AbstractUpdate
43
{
44
    /**
45
     * Import prefix.
46
     */
47
    const IMPORT_PREFIX = 'calMigration:';
48
49
    /**
50
     * Event table.
51
     */
52
    const EVENT_TABLE = 'tx_calendarize_domain_model_event';
53
54
    /**
55
     * Configuration table.
56
     */
57
    const CONFIGURATION_TABLE = 'tx_calendarize_domain_model_configuration';
58
59
    /**
60
     * ConfigurationGroup table.
61
     */
62
    const CONFIGURATION_GROUP_TABLE = 'tx_calendarize_domain_model_configurationgroup';
63
64
    /**
65
     * The human-readable title of the upgrade wizard.
66
     *
67
     * @var string
68
     */
69
    protected $title = 'Migrate cal event structures to the new calendarize event structures. 
70
    Try to migrate all cal information and place the new calendarize event models in the same folder 
71
    as the cal-records. Please note: the migration will be create calendarize default models.';
72
73
    /**
74
     * Checks whether updates are required.
75
     *
76
     * @param string &$description The description for the update
77
     *
78
     * @return bool Whether an update is required (TRUE) or not (FALSE)
79
     */
80
    public function checkForUpdate(&$description)
81
    {
82
        $nonMigratedCalIds = $this->getNonMigratedCalIds();
83
        $count = \count($nonMigratedCalIds);
84
        if (0 === $count) {
85
            return false;
86
        }
87
        $description = 'There ' . ($count > 1 ? 'are ' . $count : 'is ' . $count) . ' non migrated EXT:cal event
88
        ' . ($count > 1 ? 's' : '') . '. Run the update process to migrate the events to EXT:calendarize events.';
89
90
        return true;
91
    }
92
93
    /**
94
     * Performs the accordant updates.
95
     *
96
     * @param array &$dbQueries      Queries done in this update
97
     * @param mixed &$customMessages Custom messages
98
     *
99
     * @return bool Whether everything went smoothly or not
100
     */
101
    public function performUpdate(array &$dbQueries, &$customMessages)
102
    {
103
        $calIds = $this->getNonMigratedCalIds();
104
        $this->performSysCategoryUpdate($calIds, $dbQueries, $customMessages);
105
        $this->performSysFileReferenceUpdate($calIds, $dbQueries, $customMessages);
106
        $this->performExceptionEventUpdate($calIds, $dbQueries, $customMessages);
107
        $this->performCalEventUpdate($calIds, $dbQueries, $customMessages);
108
        $this->performLinkEventToCategory($calIds, $dbQueries, $customMessages);
109
        $this->performLinkEventToConfigurationGroup($calIds, $dbQueries, $customMessages);
110
111
        return true;
112
    }
113
114
    /**
115
     * Perform CAL event update.
116
     *
117
     * @param       $calIds
118
     * @param array $dbQueries
119
     * @param       $customMessages
120
     *
121
     * @return bool
122
     */
123
    public function performCalEventUpdate($calIds, array &$dbQueries, &$customMessages)
124
    {
125
        $table = 'tx_cal_event';
126
        $db = HelperUtility::getDatabaseConnection($table);
127
        $q = $db->createQueryBuilder();
128
129
        $events = $q->select('*')->from($table)->where(
130
            $q->expr()->in('uid', $calIds)
131
        )->execute()->fetchAll();
132
133
        foreach ($events as $event) {
134
            $calendarizeEventRecord = [
135
                'pid' => $event['pid'],
136
                'import_id' => self::IMPORT_PREFIX . (int) $event['uid'],
137
                'tstamp' => $event['tstamp'],
138
                'crdate' => $event['crdate'],
139
                'hidden' => $event['hidden'],
140
                'starttime' => $event['starttime'],
141
                'endtime' => $event['endtime'],
142
                'title' => $event['title'],
143
                'organizer' => $event['organizer'],
144
                'location' => $event['location'],
145
                'abstract' => $event['teaser'],
146
                'description' => $event['description'],
147
                'images' => $event['image'],
148
                'downloads' => $event['attachment'],
149
                'calendarize' => $this->buildConfigurations($event, $dbQueries),
150
            ];
151
152
            $variables = [
153
                'calendarizeEventRecord' => $calendarizeEventRecord,
154
                'event' => $event,
155
                'table' => self::EVENT_TABLE,
156
                'dbQueries' => $dbQueries,
157
            ];
158
159
            $dispatcher = HelperUtility::getSignalSlotDispatcher();
160
            $variables = $dispatcher->dispatch(__CLASS__, __FUNCTION__ . 'PreInsert', $variables);
161
162
            $q->insert($variables['table'])->values($variables['calendarizeEventRecord']);
163
            $dbQueries[] = $q->getSQL();
164
165
            $q->execute();
166
167
            $variablesPostInsert = [
168
                'calendarizeEventRecord' => $calendarizeEventRecord,
169
                'event' => $event,
170
                'table' => $variables['table'],
171
                'recordId' => $db->lastInsertId($variables['table']),
172
                'dbQueries' => $dbQueries,
173
            ];
174
175
            $dispatcher = HelperUtility::getSignalSlotDispatcher();
176
            $dispatcher->dispatch(__CLASS__, __FUNCTION__ . 'PostInsert', $variablesPostInsert);
177
        }
178
179
        $indexer = GeneralUtility::makeInstance(IndexerService::class);
180
        $indexer->reindexAll();
181
182
        return true;
183
    }
184
185
    /**
186
     * Perform exception event update.
187
     *
188
     * @param       $calIds
189
     * @param array $dbQueries
190
     * @param array $customMessages
191
     *
192
     * @return bool
193
     */
194
    public function performExceptionEventUpdate($calIds, &$dbQueries, &$customMessages)
195
    {
196
        $table = 'tx_cal_exception_event_group';
197
        // ConfigurationGroup für jede ExceptionGroup
198
        $db = HelperUtility::getDatabaseConnection($table);
199
        $q = $db->createQueryBuilder();
200
        $variables = [
201
            'table' => $table,
202
            'dbQueries' => $dbQueries,
203
            'calIds' => $calIds,
204
        ];
205
206
        $q->getRestrictions()
207
            ->removeAll()
208
            ->add(GeneralUtility::makeInstance(DeletedRestriction::class));
209
210
        $q->select('*')->from($variables['table']);
211
212
        $selectResults = $q->execute()->fetchAll();
213
        $dbQueries[] = $q->getSQL();
214
215
        foreach ($selectResults as $selectResult) {
216
            $group = [
217
                'pid' => $selectResult['pid'],
218
                'tstamp' => $selectResult['tstamp'],
219
                'crdate' => $selectResult['crdate'],
220
                'cruser_id' => $selectResult['cruser_id'],
221
                'title' => $selectResult['title'],
222
                'configurations' => $this->getExceptionConfigurationForExceptionGroup($selectResult['uid']), // get Configuration
223
                'hidden' => $selectResult['hidden'],
224
                'import_id' => self::IMPORT_PREFIX . $selectResult['uid'],
225
            ];
226
227
            $q->insert(self::CONFIGURATION_GROUP_TABLE)->values($group);
228
            $dbQueries[] = $q->getSQL();
229
230
            $q->execute();
231
        }
232
233
        return true;
234
    }
235
236
    /**
237
     * Perform link event to configuration group.
238
     *
239
     * @param $calIds
240
     * @param $dbQueries
241
     * @param $customMessages
242
     *
243
     * @return bool
244
     */
245
    public function performLinkEventToConfigurationGroup($calIds, &$dbQueries, &$customMessages)
246
    {
247
        $db = HelperUtility::getDatabaseConnection(self::CONFIGURATION_GROUP_TABLE);
248
        $q = $db->createQueryBuilder();
249
        $now = new \DateTime();
250
251
        $variables = [
252
            'table' => self::CONFIGURATION_GROUP_TABLE,
253
            'dbQueries' => $dbQueries,
254
            'calIds' => $calIds,
255
        ];
256
257
        $selectResults = $q->select('*')->from($variables['table'])->execute()->fetchAll();
258
        $dbQueries[] = $q->getSQL();
259
260
        foreach ($selectResults as $group) {
261
            $importId = \explode(':', $group['import_id']);
262
            $groupId = (int) $importId[1];
263
264
            $variables = [
265
                'table' => 'tx_cal_exception_event_mm',
266
                'dbQueries' => $dbQueries,
267
                'calIds' => $calIds,
268
            ];
269
270
            $q->resetQueryParts()->resetRestrictions();
271
272
            $q->select('uid_local')
273
                ->from($variables['table'])
274
                ->where(
275
                    $q->expr()->andX(
276
                        $q->expr()->eq('tablenames', 'tx_cal_exception_event_group'),
277
                        $q->expr()->eq('uid_foreign', $q->createNamedParameter((int) $groupId, \PDO::PARAM_INT))
278
                    )
279
                );
280
281
            $dbQueries[] = $q->getSQL();
282
            $selectResults = $q->execute()->fetchAll();
283
284
            foreach ($selectResults as $eventUid) {
285
                $eventImportId = self::IMPORT_PREFIX . (int) $eventUid['uid_local'];
286
                $configurationRow = [
287
                    'pid' => (int) $group['pid'],
288
                    'tstamp' => $now->getTimestamp(),
289
                    'crdate' => $now->getTimestamp(),
290
                    'type' => 'group',
291
                    'handling' => 'exclude',
292
                    'groups' => $group['uid'],
293
                ];
294
295
                $this->updateEventWithConfiguration($eventImportId, $configurationRow, $dbQueries, $customMessages);
296
            }
297
        }
298
299
        return true;
300
    }
301
302
    /**
303
     * Migrate the 'sys_file_reference' entries from 'tx_cal_event' to 'tx_calendarize_domain_model_event'.
304
     * Mark the imported entries with the import-id.
305
     *
306
     * @param       $calIds
307
     * @param array $dbQueries
308
     * @param       $customMessages
309
     */
310
    public function performSysFileReferenceUpdate($calIds, array &$dbQueries, &$customMessages)
311
    {
312
        $db = HelperUtility::getDatabaseConnection('tx_cal_event');
313
        $q = $db->createQueryBuilder();
314
315
        $variables = [
316
            'table' => 'tx_cal_event',
317
            'fieldnames' => ['image', 'attachment'],
318
            'dbQueries' => $dbQueries,
319
            'calIds' => $calIds,
320
        ];
321
322
        // select all not migrated entries
323
        $fieldnames = 'fieldname = \'' . \implode('\' OR fieldname = \'', $variables['fieldnames']) . '\'';
324
        $selectWhere = 'tablenames = \'' . $variables['table'] . '\' AND (' . $fieldnames . ')';
325
        $selectWhere .= ' AND NOT EXISTS (SELECT NULL FROM sys_file_reference sfr2 WHERE sfr2.import_id = CONCAT(\'' . self::IMPORT_PREFIX . '\', sfr1.uid))';
326
327
        $q->select('*')
328
            ->from('sys_file_reference', 'sfr1')
329
            ->where($selectWhere);
330
331
        $dbQueries[] = $q->getSQL();
332
        $selectResults = $q->execute()->fetchAll();
333
334
        $variables = [
335
            'table' => self::EVENT_TABLE,
336
            'fieldnames' => $variables['fieldnames'],
337
            'dbQueries' => $dbQueries,
338
            'calIds' => $calIds,
339
            'selectResults' => $selectResults,
340
        ];
341
342
        // create new entry with import_id
343
        foreach ($variables['selectResults'] as $selectResult) {
344
            $selectResult['tablenames'] = $variables['table'];
345
            $selectResult['import_id'] = self::IMPORT_PREFIX . $selectResult['uid'];
346
            $selectResult['fieldname'] = ('image' === $selectResult['fieldname']) ? 'images' : 'downloads';
347
            unset($selectResult['uid_foreign'], $selectResult['uid']);
348
349
            $q->resetQueryParts()->resetRestrictions();
350
            $q->insert('sys_file_reference')->values($selectResult);
351
352
            $dbQueries[] = $q->getSQL();
353
354
            $q->execute();
355
        }
356
    }
357
358
    /**
359
     * Link the Events to the migrated Categories.
360
     * This build up the 'sys_category_record_mm' table on base of the 'tx_cal_event_category_mm' table.
361
     *
362
     * @param       $calIds
363
     * @param array $dbQueries
364
     * @param array $customMessages
365
     */
366
    public function performLinkEventToCategory($calIds, &$dbQueries, &$customMessages)
367
    {
368
        $table = 'tx_cal_event_category_mm';
369
370
        $db = HelperUtility::getDatabaseConnection($table);
371
        $q = $db->createQueryBuilder();
372
373
        $q->select('*')->from($table);
374
        $dbQueries[] = $q->getSQL();
375
376
        $selectResults = $q->execute()->fetchAll();
377
378
        $variables = [
379
            'tablenames' => self::EVENT_TABLE,
380
            'fieldname' => 'categories',
381
            'dbQueries' => $dbQueries,
382
        ];
383
384
        $dispatcher = HelperUtility::getSignalSlotDispatcher();
385
        $variables = $dispatcher->dispatch(__CLASS__, __FUNCTION__, $variables);
386
387
        foreach ($selectResults as $mm) {
388
            $eventUid = $this->getCalendarizeEventUid(self::IMPORT_PREFIX . $mm['uid_local'], $dbQueries, $customMessages);
389
            $categoryUid = $this->getCalendarizeCategoryUid(
390
                self::IMPORT_PREFIX . $mm['uid_foreign'],
391
                $dbQueries,
392
                $customMessages
393
            );
394
395
            $insertValues = [
396
                'uid_local' => $categoryUid,
397
                'uid_foreign' => $eventUid,
398
                'tablenames' => $variables['tablenames'],
399
                'fieldname' => $variables['fieldname'],
400
            ];
401
402
            $q->insert('sys_category_record_mm')->values($insertValues);
403
            $dbQueries[] = $q->getSQL();
404
405
            $q->execute();
406
        }
407
    }
408
409
    /**
410
     * Update event with configuration.
411
     *
412
     * @param $eventImportId
413
     * @param $configuration
414
     * @param $dbQueries
415
     * @param $customMessages
416
     *
417
     * @return array
418
     */
419
    protected function updateEventWithConfiguration($eventImportId, $configuration, &$dbQueries, &$customMessages)
420
    {
421
        $db = HelperUtility::getDatabaseConnection(self::CONFIGURATION_TABLE);
422
        $q = $db->createQueryBuilder();
423
424
        $configurationRow = $this->findEventExcludeConfiguration($eventImportId, $dbQueries, $customMessages);
425
        if ($configurationRow) {
426
            $configurationRow['groups'] = $this->addValueToCsv($configurationRow['groups'], $configuration['groups']);
427
428
            unset($configurationRow['uid']);
429
430
            $q->update(self::CONFIGURATION_GROUP_TABLE)
431
                ->where('uid', $q->createNamedParameter((int) $configuration['uid'], \PDO::PARAM_INT))
432
                ->values($configurationRow);
433
434
            $dbQueries[] = $q->getSQL();
435
            $results = $q->execute();
436
        } else {
437
            $q->insert(self::CONFIGURATION_TABLE)->values($configuration);
438
            $dbQueries[] = $q->getSQL();
439
440
            $configurationId = $db->lastInsertId(self::CONFIGURATION_TABLE);
441
442
            $results = $this->addConfigurationIdToEvent($eventImportId, $configurationId, $dbQueries, $customMessages);
443
        }
444
445
        return $results;
446
    }
447
448
    /**
449
     * Add Value to CSV.
450
     *
451
     * @param string $csv
452
     * @param string $value
453
     *
454
     * @return string
455
     */
456
    protected function addValueToCsv($csv, $value)
457
    {
458
        $csvArray = GeneralUtility::trimExplode(',', $csv);
459
460
        // check for doubles
461
        $values = \array_flip($csvArray);
462
        if (isset($values[$value])) {
463
            return $csv;
464
        }
465
        $csvArray[] = $value;
466
        $csv = \implode(',', $csvArray);
467
468
        return $csv;
469
    }
470
471
    /**
472
     * Add configuration ID to event.
473
     *
474
     * @param string $eventImportId
475
     * @param int    $configurationId
476
     * @param array  $dbQueries
477
     * @param array  $customMessages
478
     *
479
     * @return array|bool
480
     */
481
    protected function addConfigurationIdToEvent($eventImportId, $configurationId, &$dbQueries, &$customMessages)
482
    {
483
        $event = $this->findEventByImportId($eventImportId, $dbQueries, $customMessages);
484
        if (!$event) {
485
            return false;
486
        }
487
488
        $event['calendarize'] = $this->addValueToCsv($event['calendarize'], $configurationId);
489
490
        return $this->updateEvent($event['uid'], $event, $dbQueries, $customMessages);
491
    }
492
493
    /**
494
     * Update event.
495
     *
496
     * @param int   $eventId
497
     * @param array $values
498
     * @param array $dbQueries
499
     * @param array $customMessages
500
     *
501
     * @return array
502
     */
503
    protected function updateEvent($eventId, $values, &$dbQueries, &$customMessages)
504
    {
505
        $db = HelperUtility::getDatabaseConnection(self::EVENT_TABLE);
506
        $q = $db->createQueryBuilder();
507
508
        $variables = [
509
            'table' => self::EVENT_TABLE,
510
            'eventId' => (int) $eventId,
511
            'values' => $values,
512
            'dbQueries' => $dbQueries,
513
        ];
514
515
        $dispatcher = HelperUtility::getSignalSlotDispatcher();
516
        $variables = $dispatcher->dispatch(__CLASS__, __FUNCTION__, $variables);
517
518
        $q->update($variables['table'])
519
            ->where(
520
                $q->expr()->eq('uid', $q->createNamedParameter((int) $eventId, \PDO::PARAM_INT))
521
            )
522
            ->values($variables['values']);
523
524
        unset($values['uid']);
525
526
        $dbQueries[] = $q->getSQL();
527
528
        return $q->execute()->fetchAll();
529
    }
530
531
    /**
532
     * Find event by import ID.
533
     *
534
     * @param $eventImportId
535
     * @param $dbQueries
536
     * @param $customMessages
537
     *
538
     * @return array|bool
539
     */
540
    protected function findEventByImportId($eventImportId, &$dbQueries, &$customMessages)
541
    {
542
        $db = HelperUtility::getDatabaseConnection(self::EVENT_TABLE);
543
        $q = $db->createQueryBuilder();
544
545
        $variables = [
546
            'table' => self::EVENT_TABLE,
547
            'dbQueries' => $dbQueries,
548
            'eventImportId' => $eventImportId,
549
        ];
550
551
        $dispatcher = HelperUtility::getSignalSlotDispatcher();
552
        $variables = $dispatcher->dispatch(__CLASS__, __FUNCTION__, $variables);
553
554
        $q->select('*')->from($variables['table'])
555
            ->where(
556
                $q->expr()->eq('import_id', $q->createNamedParameter($eventImportId))
557
            );
558
559
        $dbQueries[] = $q->getSQL();
560
561
        return $q->execute()->fetchAll();
562
    }
563
564
    /**
565
     * Find event exclude configuration.
566
     *
567
     * @param string $eventImportId
568
     * @param array  $dbQueries
569
     * @param array  $customMessages
570
     *
571
     * @return array|bool
572
     */
573
    protected function findEventExcludeConfiguration($eventImportId, &$dbQueries, &$customMessages)
574
    {
575
        $event = $this->findEventByImportId($eventImportId, $dbQueries, $customMessages);
576
577
        if (!$event) {
578
            return false;
579
        }
580
581
        $variables = [
582
            'table' => self::CONFIGURATION_TABLE,
583
            'dbQueries' => $dbQueries,
584
            'event' => $event,
585
        ];
586
587
        $db = HelperUtility::getDatabaseConnection($variables['table']);
588
        $q = $db->createQueryBuilder();
589
590
        $q->select('*')
591
            ->from($variables['table'])
592
            ->where(
593
                $q->expr()->andX(
594
                    $q->expr()->eq('type', 'group'),
595
                    $q->expr()->eq('handling', 'exclude'),
596
                    $q->expr()->in('uid', $variables['event']['calendarize'])
597
                )
598
            );
599
600
        $dbQueries[] = $q->getSQL();
601
602
        return $q->execute()->fetchAll();
603
    }
604
605
    /**
606
     * Get exception configuration for exception group.
607
     *
608
     * @param       $groupId
609
     * @param array $dbQueries
610
     * @param array $customMessages
611
     *
612
     * @return string
613
     */
614
    protected function getExceptionConfigurationForExceptionGroup($groupId, &$dbQueries, &$customMessages)
615
    {
616
        $recordIds = [];
617
        $variables = [
618
            'table' => ' tx_cal_exception_event_group_mm',
619
            'dbQueries' => $dbQueries,
620
        ];
621
622
        $db = HelperUtility::getDatabaseConnection($variables['table']);
623
        $q = $db->createQueryBuilder();
624
625
        $q->select('*')
626
            ->from($variables['table'])
627
            ->where('uid_local', $q->createNamedParameter((int) $groupId, \PDO::PARAM_INT));
628
629
        $dbQueries[] = $q->getSQL();
630
631
        $mmResults = $q->execute()->fetchAll();
632
        foreach ($mmResults as $mmResult) {
633
            $variables = [
634
                'table' => ' tx_cal_exception_event',
635
                'dbQueries' => $dbQueries,
636
            ];
637
638
            $q->resetQueryParts()->resetRestrictions();
639
            $q->select('*')
640
                ->from($variables['table'])
641
                ->where(
642
                    $q->expr()->eq('uid', $q->createNamedParameter((int) $mmResult['uid_foreign'], \PDO::PARAM_INT))
643
                );
644
645
            $dbQueries[] = $q->getSQL();
646
647
            $selectResults = $q->execute()->fetchAll();
648
649
            foreach ($selectResults as $selectResult) {
650
                $configurationRow = [
651
                    'pid' => $selectResult['pid'],
652
                    'tstamp' => $selectResult['tstamp'],
653
                    'crdate' => $selectResult['crdate'],
654
                    'type' => 'time',
655
                    'handling' => 'include',
656
                    'start_date' => $this->migrateDate($selectResult['start_date']),
657
                    'end_date' => $this->migrateDate($selectResult['end_date']),
658
                    'start_time' => (int) $selectResult['start_time'],
659
                    'end_time' => (int) $selectResult['end_time'],
660
                    'all_day' => (null === $selectResult['start_time'] && null === $selectResult['end_time']) ? 1 : 0,
661
                    'frequency' => $this->mapFrequency($selectResult['freq']),
662
                    'till_date' => $this->migrateDate($selectResult['until']),
663
                    'counter_amount' => (int) $selectResult['cnt'],
664
                    'counter_interval' => (int) $selectResult['interval'],
665
                    'import_id' => self::IMPORT_PREFIX . $selectResult['uid'],
666
                ];
667
668
                $variables = [
669
                    'table' => self::CONFIGURATION_TABLE,
670
                    'configurationRow' => $configurationRow,
671
                ];
672
673
                $dispatcher = HelperUtility::getSignalSlotDispatcher();
674
                $variables = $dispatcher->dispatch(__CLASS__, __FUNCTION__ . 'PreInsert', $variables);
675
676
                $q->resetQueryParts()->resetRestrictions();
677
                $q->insert($variables['table'])->values($variables['configurationRow']);
678
679
                $dbQueries[] = $q->getSQL();
680
681
                $q->execute();
682
683
                $recordIds[] = $db->lastInsertId($variables['table']);
684
            }
685
        }
686
687
        return \implode(',', $recordIds);
688
    }
689
690
    /**
691
     * Map frequency.
692
     *
693
     * @param string $calFrequency
694
     *
695
     * @return string
696
     */
697
    protected function mapFrequency($calFrequency)
698
    {
699
        $freq = [
700
            'none' => null,
701
            'day' => 'daily',
702
            'week' => 'weekly',
703
            'month' => 'monthly',
704
            'year' => 'yearly',
705
        ];
706
707
        if (!isset($freq[$calFrequency])) {
708
            return '';
709
        }
710
711
        return $freq[$calFrequency];
712
    }
713
714
    /**
715
     * Migrate the 'tx_cal_category' table to the 'sys_category' table.
716
     *
717
     * @param       $calIds
718
     * @param array $dbQueries
719
     * @param       $customMessages
720
     */
721
    protected function performSysCategoryUpdate($calIds, array &$dbQueries, &$customMessages)
722
    {
723
        // first migrate from tx_cal_category to sys_category
724
        $variables = [
725
            'table' => 'tx_cal_category',
726
            'dbQueries' => $dbQueries,
727
            'calIds' => $calIds,
728
        ];
729
730
        $db = HelperUtility::getDatabaseConnection($variables['table']);
731
        $q = $db->createQueryBuilder();
732
        $q->getRestrictions()
733
            ->removeAll()
734
            ->add(GeneralUtility::makeInstance(DeletedRestriction::class));
735
736
        $q->select('*')
737
            ->from($variables['table']);
738
739
        $dbQueries[] = $q->getSQL();
740
741
        $selectResults = $q->execute()->fetchAll();
742
743
        foreach ($selectResults as $category) {
744
            $sysCategoryRecord = [
745
                'pid' => $category['pid'],
746
                'tstamp' => $category['tstamp'],
747
                'crdate' => $category['crdate'],
748
                'cruser_id' => $category['cruser_id'],
749
                'deleted' => $category['deleted'],
750
                'hidden' => $category['hidden'],
751
                'starttime' => $category['starttime'],
752
                'endtime' => $category['endtime'],
753
                'sys_language_uid' => $category['sys_language_uid'],
754
                'l10n_parent' => $category['l18n_parent'],
755
                'l10n_diffsource' => $category['l18n_diffsource'],
756
                'title' => $category['title'],
757
                'parent' => (int) $category['parent_category'],
758
                'import_id' => self::IMPORT_PREFIX . (int) $category['uid'],
759
                'sorting' => $category['sorting'],
760
            ];
761
762
            $q->resetQueryParts()->resetRestrictions();
763
764
            $q->insert('sys_category')->values($sysCategoryRecord);
765
            $dbQueries[] = $q->getSQL();
766
767
            $q->execute();
768
        }
769
770
        // second rewrite the tree
771
        $variables = [
772
            'table' => 'sys_category',
773
            'dbQueries' => $dbQueries,
774
            'calIds' => $calIds,
775
        ];
776
777
        $q->resetQueryParts()->resetRestrictions();
778
779
        $q->select('*')
780
            ->from($variables['table'])
781
            ->where(
782
                $q->expr()->neq('import_id', '')
783
            );
784
785
        $dbQueries[] = $q->getSQL();
786
        $selectResults = $q->execute()->fetchAll();
787
788
        foreach ($selectResults as $sysCategory) {
789
            // update parent, because there are just the old uids
790
            $updateRecord = [
791
                'parent' => $this->getSysCategoryParentUid(self::IMPORT_PREFIX . (int) $sysCategory['parent']),
792
            ];
793
794
            $q->resetQueryParts()->resetRestrictions();
795
            $q->update('sys_category')
796
                ->where(
797
                    $q->expr()->eq('uid', $q->createNamedParameter((int) $sysCategory['uid'], \PDO::PARAM_INT))
798
                )
799
                ->values($updateRecord);
800
801
            $dbQueries[] = $q->getSQL();
802
803
            $q->execute();
804
        }
805
    }
806
807
    /**
808
     * Return the parentUid for the 'sys_category' entry on base of the import_id.
809
     *
810
     * @param string $importId
811
     *
812
     * @return int
813
     */
814
    protected function getSysCategoryParentUid($importId)
815
    {
816
        $table = 'sys_category';
817
        $db = HelperUtility::getDatabaseConnection($table);
818
        $q = $db->createQueryBuilder();
819
820
        $q->select('uid')
821
            ->from($table)
822
            ->where(
823
                $q->expr()->eq('import_id', $q->createNamedParameter($importId))
824
            );
825
826
        $dbQueries[] = $q->getSQL();
0 ignored issues
show
Coding Style Comprehensibility introduced by
$dbQueries was never initialized. Although not strictly required by PHP, it is generally a good practice to add $dbQueries = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
827
828
        $result = $q->execute()->fetchAll();
829
830
        return (int) $result['uid'];
831
    }
832
833
    /**
834
     * Get the event uid on base of the given import_id.
835
     * The import_id is the original tx_cal_event id prefixed with the IMPORT_PREFIX.
836
     *
837
     * @param string $importId
838
     * @param array  $dbQueries
839
     * @param array  $customMessages
840
     *
841
     * @return int
842
     */
843
    protected function getCalendarizeEventUid($importId, &$dbQueries, &$customMessages)
844
    {
845
        $variables = [
846
            'table' => self::EVENT_TABLE,
847
            'dbQueries' => $dbQueries,
848
        ];
849
850
        $q = HelperUtility::getDatabaseConnection($variables['table'])->createQueryBuilder();
851
852
        $dispatcher = HelperUtility::getSignalSlotDispatcher();
853
        $variables = $dispatcher->dispatch(__CLASS__, __FUNCTION__, $variables);
854
855
        $q->select('uid')
856
            ->from($variables['table'])
857
            ->where(
858
                $q->expr()->eq('import_id', $q->createNamedParameter($importId))
859
            );
860
861
        $dbQueries[] = $q->getSQL();
862
863
        $result = $q->execute()->fetchAll();
864
        $uid = (int) $result['uid'];
865
866
        return $uid;
867
    }
868
869
    /**
870
     * Get the sys_category uid on base of the given import_id.
871
     * The import_id is the original tx_cal_category id prefixed with the IMPORT_PREFIX.
872
     *
873
     * @see CalMigrationUpdate::IMPORT_PREFIX
874
     *
875
     * @param string $importId
876
     * @param array  $dbQueries
877
     * @param array  $customMessages
878
     *
879
     * @return int
880
     */
881
    protected function getCalendarizeCategoryUid($importId, &$dbQueries, &$customMessages)
882
    {
883
        $variables = [
884
            'table' => 'sys_category',
885
            'dbQueries' => $dbQueries,
886
        ];
887
888
        $q = HelperUtility::getDatabaseConnection($variables['table'])->createQueryBuilder();
889
890
        $dispatcher = HelperUtility::getSignalSlotDispatcher();
891
        $variables = $dispatcher->dispatch(__CLASS__, __FUNCTION__, $variables);
892
893
        $q->select('uid')
894
            ->from($variables['table'])
895
            ->where(
896
                $q->expr()->eq('import_id', $q->createNamedParameter($importId))
897
            );
898
899
        $dbQueries[] = $q->getSQL();
900
901
        $result = $q->execute()->fetchAll();
902
        $uid = (int) $result['uid'];
903
904
        return $uid;
905
    }
906
907
    /**
908
     * Build configurations.
909
     *
910
     * @param $calEventRow
911
     * @param $dbQueries
912
     *
913
     * @return int
914
     */
915
    protected function buildConfigurations($calEventRow, &$dbQueries)
916
    {
917
        $configurationRow = [
918
            'pid' => $calEventRow['pid'],
919
            'tstamp' => $calEventRow['tstamp'],
920
            'crdate' => $calEventRow['crdate'],
921
            'type' => 'time',
922
            'handling' => 'include',
923
            'start_date' => $this->migrateDate($calEventRow['start_date']),
924
            'end_date' => $this->migrateDate($calEventRow['end_date']),
925
            'start_time' => $calEventRow['start_time'],
926
            'end_time' => $calEventRow['end_time'],
927
            'all_day' => $calEventRow['allday'],
928
            'frequency' => $this->mapFrequency($calEventRow['freq']),
929
            'till_date' => $this->migrateDate($calEventRow['until']),
930
            'counter_amount' => (int) $calEventRow['cnt'],
931
            'counter_interval' => (int) $calEventRow['interval'],
932
        ];
933
934
        $variables = [
935
            'table' => self::CONFIGURATION_TABLE,
936
            'configurationRow' => $configurationRow,
937
            'calEventRow' => $calEventRow,
938
            'dbQueries' => $dbQueries,
939
        ];
940
941
        $db = HelperUtility::getDatabaseConnection($variables['table']);
942
        $q = $db->createQueryBuilder();
943
944
        $dispatcher = HelperUtility::getSignalSlotDispatcher();
945
        $variables = $dispatcher->dispatch(__CLASS__, __FUNCTION__ . 'PreInsert', $variables);
946
947
        $q->insert($variables['table'])
948
            ->values($variables['configurationRow']);
949
950
        $dbQueries[] = $q->getSQL();
951
        $q->execute();
952
        $recordId = $db->lastInsertId($variables['table']);
953
954
        $variables = [
955
            'table' => $variables['table'],
956
            'configurationRow' => $configurationRow,
957
            'calEventRow' => $calEventRow,
958
            'recordId' => $recordId,
959
            'dbQueries' => $dbQueries,
960
        ];
961
962
        $dispatcher = HelperUtility::getSignalSlotDispatcher();
963
        $variables = $dispatcher->dispatch(__CLASS__, __FUNCTION__ . 'PostInsert', $variables);
964
965
        return $variables['recordId'];
966
    }
967
968
    /**
969
     * Migrate date.
970
     *
971
     * @param $oldFormat
972
     *
973
     * @return int|string
974
     */
975
    protected function migrateDate($oldFormat)
976
    {
977
        try {
978
            $date = new \DateTime($oldFormat);
979
980
            return $date->getTimestamp();
981
        } catch (\Exception $e) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
982
        }
983
984
        return '';
985
    }
986
987
    /**
988
     * Get the non migrated cal IDs.
989
     *
990
     * @return array
991
     */
992
    protected function getNonMigratedCalIds()
993
    {
994
        if (!ExtensionManagementUtility::isLoaded('cal')) {
995
            return [];
996
        }
997
998
        $checkImportIds = [];
999
        $nonMigrated = [];
1000
1001
        $table = 'tx_cal_event';
1002
        $q = HelperUtility::getDatabaseConnection($table)->createQueryBuilder();
1003
        $q->getRestrictions()
1004
            ->removeAll()
1005
            ->add(GeneralUtility::makeInstance(DeletedRestriction::class));
1006
1007
        $events = $q->select('uid')
1008
            ->from($table)
1009
            ->execute()
1010
            ->fetchAll();
1011
1012
        foreach ($events as $event) {
1013
            $checkImportIds[] = '"' . self::IMPORT_PREFIX . $event['uid'] . '"';
1014
            $nonMigrated[(int) $event['uid']] = (int) $event['uid'];
1015
        }
1016
1017
        $countOriginal = \count($checkImportIds);
1018
        if (0 === $countOriginal) {
1019
            return [];
1020
        }
1021
1022
        $variables = [
1023
            'table' => self::EVENT_TABLE,
1024
        ];
1025
1026
        $dispatcher = HelperUtility::getSignalSlotDispatcher();
1027
        $variables = $dispatcher->dispatch(__CLASS__, __FUNCTION__ . 'PreSelect', $variables);
1028
1029
        $q->resetQueryParts();
1030
1031
        $migratedRows = $q->select('uid', 'import_id')
1032
            ->from($variables['table'])
1033
            ->where(
1034
                $q->expr()->in('import_id', $checkImportIds)
1035
            );
1036
1037
        foreach ($migratedRows as $migratedRow) {
1038
            $importId = (int) \str_replace(self::IMPORT_PREFIX, '', $migratedRow['import_id']);
1039
            if (isset($nonMigrated[$importId])) {
1040
                unset($nonMigrated[$importId]);
1041
            }
1042
        }
1043
1044
        $variables = [
1045
            'table' => $variables['table'],
1046
            'migratedRows' => $migratedRows,
1047
            'nonMigrated' => $nonMigrated,
1048
        ];
1049
1050
        $dispatcher = HelperUtility::getSignalSlotDispatcher();
1051
        $variables = $dispatcher->dispatch(__CLASS__, __FUNCTION__ . 'ReadyParsed', $variables);
1052
1053
        return $variables['nonMigrated'];
1054
    }
1055
}
1056