Completed
Push — master ( f08ce5...e1afd8 )
by Sven
33s
created

Update::addConfigForBasketRemovals()   A

Complexity

Conditions 4
Paths 5

Size

Total Lines 16

Duplication

Lines 16
Ratio 100 %

Importance

Changes 0
Metric Value
cc 4
nc 5
nop 0
dl 16
loc 16
rs 9.7333
c 0
b 0
f 0
1
<?php
2
/**
3
 * (c) shopware AG <[email protected]>
4
 * For the full copyright and license information, please view the LICENSE
5
 * file that was distributed with this source code.
6
 */
7
8
namespace ShopwarePlugins\Connect\Bootstrap;
9
10
use Shopware\CustomModels\Connect\Attribute;
11
use Shopware\Components\Model\ModelManager;
12
use Enlight_Components_Db_Adapter_Pdo_Mysql as Pdo;
13
use Shopware\Models\Attribute\Configuration;
14
use Shopware\Models\Order\Status;
15
use ShopwarePlugins\Connect\Components\ProductQuery\BaseProductQuery;
16
use ShopwarePlugins\Connect\Components\Utils\ConnectOrderUtil;
17
use ShopwarePlugins\Connect\Components\Logger;
18
19
/**
20
 * Updates existing versions of the plugin
21
 *
22
 * Class Update
23
 * @package ShopwarePlugins\Connect\Bootstrap
24
 */
25
class Update
26
{
27
    /**
28
     * @var \Shopware_Plugins_Backend_SwagConnect_Bootstrap
29
     */
30
    protected $bootstrap;
31
32
    /**
33
     * @var Pdo
34
     */
35
    protected $db;
36
37
    /**
38
     * @var ModelManager
39
     */
40
    protected $modelManager;
41
42
    /**
43
     * @var string
44
     */
45
    protected $version;
46
47
    /**
48
     * @var Logger
49
     */
50
    private $logger;
51
52
    /**
53
     * Setup constructor.
54
     * @param \Shopware_Plugins_Backend_SwagConnect_Bootstrap $bootstrap
55
     * @param ModelManager $modelManager
56
     * @param Pdo $db
57
     * @param $version
58
     * @param Logger|null $logger
59
     */
60
    public function __construct(
61
        \Shopware_Plugins_Backend_SwagConnect_Bootstrap $bootstrap,
62
        ModelManager $modelManager,
63
        Pdo $db,
64
        Logger $logger,
65
        $version
66
    ) {
67
        $this->bootstrap = $bootstrap;
68
        $this->modelManager = $modelManager;
69
        $this->db = $db;
70
        $this->logger = $logger;
71
        $this->version = $version;
72
    }
73
74
    public function run()
75
    {
76
        // Force an SDK re-verify
77
        $this->reVerifySDK();
78
79
        $this->createExportedFlag();
80
        $this->removeRedirectMenu();
81
        $this->updateConnectAttribute();
82
        $this->addConnectDescriptionElement();
83
        $this->updateProductDescriptionSetting();
84
        $this->createUpdateAdditionalDescriptionColumn();
85
        $this->createDynamicStreamTable();
86
        $this->addOrderStatus();
87
        $this->fixExportDescriptionSettings();
88
        $this->fixMarketplaceUrl();
89
        $this->addIndexToChangeTable();
90
        $this->removeDuplicatedMenuItems();
91
        $this->addConnectItemsIndex();
92
        $this->createRemoteToLocalCategoriesTable();
93
        $this->recreateRemoteCategoriesAndProductAssignments();
94
        $this->setDefaultConfigForUpdateOrderStatus();
95
        $this->addShopIdToConnectCategories();
96
        $this->addProductToCategoryIndex();
97
        $this->addStreamColumnToConnectToLocalCategories();
98
        $this->changeExportStatusToVarchar();
99
        $this->addArticleRelationsTable();
100
        $this->addOverwriteMainImage();
101
        $this->changeGroupNameImportSettings();
102
        $this->addArticleDetailsForeignKey();
103
        $this->addConfigForBasketRemovals();
104
105
        return true;
106
    }
107
108
    /**
109
     * Forces the SDK to re-verify the API key
110
     */
111
    public function reVerifySDK()
112
    {
113
        $this->db->query(
114
            'UPDATE sw_connect_shop_config
115
            SET s_config = ?
116
            WHERE s_shop = "_last_update_"
117
            LIMIT 1; ',
118
            [time() - 8 * 60 * 60 * 24]
119
        );
120
    }
121
122
    private function createExportedFlag()
123
    {
124
        if (version_compare($this->version, '1.0.1', '<=')) {
125
            $this->db->query(
126
                'ALTER TABLE `s_plugin_connect_items`
127
                ADD COLUMN `exported` TINYINT(1) DEFAULT 0'
128
            );
129
130
            $this->db->query(
131
                'UPDATE `s_plugin_connect_items`
132
                SET `exported` = 1
133
                WHERE (`export_status` = ? OR `export_status` = ? OR `export_status` = ?) AND `shop_id` IS NULL',
134
                [Attribute::STATUS_INSERT, Attribute::STATUS_UPDATE, Attribute::STATUS_SYNCED]
135
            );
136
        }
137
    }
138
139
    private function removeRedirectMenu()
140
    {
141
        if (version_compare($this->version, '1.0.4', '<=')) {
142
            $connectItem = $this->bootstrap->Menu()->findOneBy(['label' => 'Open Connect', 'action' => '']);
143
            if ($connectItem) {
144
                $this->modelManager->remove($connectItem);
145
                $this->modelManager->flush();
146
            }
147
        }
148
    }
149
150
    private function updateConnectAttribute()
151
    {
152
        if (version_compare($this->version, '1.0.6', '<=')) {
153
            $result = $this->db->query("SELECT value FROM s_plugin_connect_config WHERE name = 'connectAttribute'");
154
            $row = $result->fetch();
155
            $attr = 19;
156
            if ($row) {
157
                $attr = $row['value'];
158
            }
159
160
            $this->db->query('
161
                    UPDATE `s_articles_attributes` 
162
                    SET `connect_reference` = `attr' . $attr . '` 
163
                    WHERE connect_reference IS NULL;
164
                ');
165
166
            $this->db->query("DELETE FROM s_plugin_connect_config WHERE name = 'connectAttribute'");
167
        }
168
    }
169
170
    private function addConnectDescriptionElement()
171
    {
172
        if (version_compare($this->version, '1.0.9', '<=')) {
173
            $tableName = $this->modelManager->getClassMetadata('Shopware\Models\Attribute\Article')->getTableName();
174
            $columnName = 'connect_product_description';
175
176
            $repo = $this->modelManager->getRepository('Shopware\Models\Attribute\Configuration');
177
            $element = $repo->findOneBy([
178
                'tableName' => $tableName,
179
                'columnName' => $columnName,
180
            ]);
181
182
            if (!$element) {
183
                $element = new Configuration();
184
                $element->setTableName($tableName);
185
                $element->setColumnName($columnName);
186
            }
187
188
            $element->setColumnType('html');
189
            $element->setTranslatable(true);
190
            $element->setLabel('Connect Beschreibung');
191
            $element->setDisplayInBackend(true);
192
193
            $this->modelManager->persist($element);
194
            $this->modelManager->flush();
195
        }
196
    }
197
198
    private function updateProductDescriptionSetting()
199
    {
200
        if (version_compare($this->version, '1.0.9', '<=')) {
201
            //migrates to the new export settings
202
            $result = $this->db->query("SELECT `value` FROM s_plugin_connect_config WHERE name = 'alternateDescriptionField'");
203
            $row = $result->fetch();
204
205
            if ($row) {
206
                $mapper = [
207
                    'a.description' => BaseProductQuery::SHORT_DESCRIPTION_FIELD,
208
                    'a.descriptionLong' => BaseProductQuery::LONG_DESCRIPTION_FIELD,
209
                    'attribute.connectProductDescription' => BaseProductQuery::CONNECT_DESCRIPTION_FIELD,
210
                ];
211
212
                if ($name = $mapper[$row['value']]) {
213
                    $result = $this->db->query("SELECT `id` FROM s_plugin_connect_config WHERE name = '$name'");
214
                    $row = $result->fetch();
215
216
                    $id = null;
217
                    if (isset($row['id'])) {
218
                        $id = $row['id'];
219
                    }
220
221
                    $this->db->query(
222
                        "REPLACE INTO `s_plugin_connect_config`
223
                        (`id`, `name`, `value`, `shopId`, `groupName`)
224
                        VALUES
225
                        (?, ?, 1, null, 'export')",
226
                        [$id, $name]
227
                    );
228
                }
229
            }
230
231
            $this->db->query("
232
                ALTER TABLE `s_plugin_connect_items`
233
                ADD `update_additional_description` VARCHAR(255) NULL DEFAULT 'inherit' AFTER `update_short_description`;
234
            ");
235
        }
236
    }
237
238
    private function createUpdateAdditionalDescriptionColumn()
239
    {
240
        // for some reason update_additional_description column is missing in 1.0.11
241
        if (version_compare($this->version, '1.0.11', '<=')) {
242
            try {
243
                $this->db->query("
244
                        ALTER TABLE `s_plugin_connect_items`
245
                        ADD `update_additional_description` VARCHAR(255) NULL DEFAULT 'inherit' AFTER `update_short_description`;
246
                    ");
247
            } catch (\Exception $e) {
248
                // ignore it if the column already exists
249
            }
250
        }
251
    }
252
253
    private function createDynamicStreamTable()
254
    {
255
        if (version_compare($this->version, '1.0.12', '<=')) {
256
            $query = "CREATE TABLE IF NOT EXISTS `s_plugin_connect_streams_relation` (
257
                `stream_id` int(11) unsigned NOT NULL,
258
                `article_id` int(11) unsigned NOT NULL,
259
                `deleted` int(1) NOT NULL DEFAULT '0',
260
                UNIQUE KEY `stream_id` (`stream_id`,`article_id`),
261
                CONSTRAINT s_plugin_connect_streams_selection_fk_stream_id FOREIGN KEY (stream_id) REFERENCES s_product_streams (id) ON DELETE CASCADE,
262
                CONSTRAINT s_plugin_connect_streams_selection_fk_article_id FOREIGN KEY (article_id) REFERENCES s_articles (id) ON DELETE CASCADE
263
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;";
264
265
            $this->db->exec($query);
266
        }
267
    }
268
269
    private function addOrderStatus()
270
    {
271
        if (version_compare($this->version, '1.0.12', '<=')) {
272
            $query = $this->modelManager->getRepository('Shopware\Models\Order\Status')->createQueryBuilder('s');
273
            $query->select('MAX(s.id)');
274
            $result = $query->getQuery()->getOneOrNullResult();
275
276
            if (count($result) > 0) {
277
                $currentId = (int) reset($result);
278
            } else {
279
                $currentId = 0;
280
            }
281
282
            $name = ConnectOrderUtil::ORDER_STATUS_ERROR;
283
            $group = Status::GROUP_STATE;
284
285
            $isExists = $this->db->query(
286
                'SELECT `id` FROM `s_core_states`
287
                WHERE `name` = ? AND `group` = ?',
288
                [$name, $group]
289
            )->fetch();
290
291
            if ($isExists) {
292
                return;
293
            }
294
295
            ++$currentId;
296
            $this->db->query(
297
                'INSERT INTO `s_core_states`
298
                (`id`, `name`, `description`, `position`, `group`, `mail`)
299
                VALUES (?, ?, ?, ?, ?, ?)',
300
                [$currentId, $name, 'SC error', $currentId, $group, 0]
301
            );
302
        }
303
    }
304
305
    /**
306
     * Replace longDescriptionField and shortDescription values,
307
     * because of wrong snippets in previous versions.
308
     *
309
     * ExtJs view show longDescription label, but the value was stored as shortDescription
310
     */
311
    private function fixExportDescriptionSettings()
312
    {
313
        if (version_compare($this->version, '1.0.12', '<=')) {
314
            $rows = $this->db->fetchPairs(
315
                'SELECT `name`, `value` FROM s_plugin_connect_config WHERE name = ? OR name = ?',
316
                ['longDescriptionField', 'shortDescriptionField']
317
            );
318
319
            if (!array_key_exists('longDescriptionField', $rows) || !array_key_exists('shortDescriptionField', $rows)) {
320
                return;
321
            }
322
323
            if (($rows['longDescriptionField'] == 1 && $rows['shortDescriptionField'] == 1)
324
                || ($rows['longDescriptionField'] == 0 && $rows['shortDescriptionField'] == 0)) {
325
                return;
326
            }
327
328
            $newValues = [
329
                'longDescriptionField' => $rows['shortDescriptionField'],
330
                'shortDescriptionField' => $rows['longDescriptionField'],
331
            ];
332
333
            $this->db->query(
334
                'UPDATE `s_plugin_connect_config`
335
                SET `value` = ?
336
                WHERE `name` = ?',
337
                [$newValues['longDescriptionField'], 'longDescriptionField']
338
            );
339
340
            $this->db->query(
341
                'UPDATE `s_plugin_connect_config`
342
                SET `value` = ?
343
                WHERE `name` = ?',
344
                [$newValues['shortDescriptionField'], 'shortDescriptionField']
345
            );
346
        }
347
    }
348
349
    private function fixMarketplaceUrl()
350
    {
351
        if (version_compare($this->version, '1.0.12', '<=')) {
352
            $repo = $this->modelManager->getRepository('Shopware\Models\Config\Form');
353
            /** @var \Shopware\Models\Config\Form $form */
354
            $form = $repo->findOneBy([
355
                'name' => 'SwagConnect',
356
            ]);
357
358
            if (!$form) {
359
                return;
360
            }
361
362
            /** @var \Shopware\Models\Config\Element $element */
363
            foreach ($form->getElements() as $element) {
364
                if ($element->getName() != 'connectDebugHost') {
365
                    continue;
366
                }
367
368 View Code Duplication
                if (strlen($element->getValue()) > 0 && strpos($element->getValue(), 'sn.') === false) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
369
                    $element->setValue('sn.' . $element->getValue());
370
                    $this->modelManager->persist($element);
371
                }
372
373
                $values = $element->getValues();
374
                if (count($values) > 0) {
375
                    /** @var \Shopware\Models\Config\Value $element */
376
                    $value = $values[0];
377 View Code Duplication
                    if (strlen($value->getValue()) > 0 && strpos($value->getValue(), 'sn.') === false) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
378
                        $value->setValue('sn.' . $value->getValue());
379
                        $this->modelManager->persist($value);
380
                    }
381
                }
382
383
                $this->modelManager->flush();
384
            }
385
        }
386
    }
387
388
    private function addIndexToChangeTable()
389
    {
390
        if (version_compare($this->version, '1.0.16', '<=')) {
391
            $this->db->query('
392
              ALTER TABLE `sw_connect_change`
393
              ADD INDEX `c_operation` (`c_operation`)
394
             ');
395
        }
396
    }
397
398
    /**
399
     * In some cases Connect main menu was duplicated
400
     * when shop is connected to SEM project. All not needed menu items must be removed.
401
     */
402
    private function removeDuplicatedMenuItems()
403
    {
404
        if (version_compare($this->version, '1.0.16', '<=')) {
405
            $mainMenuItems = $this->bootstrap->Menu()->findBy([
406
                'class' => Menu::CONNECT_CLASS,
407
                'parent' => null,
408
            ], ['id' => 'ASC']);
409
410
            foreach (array_slice($mainMenuItems, 1) as $menuItem) {
411
                foreach ($menuItem->getChildren() as $children) {
412
                    $this->modelManager->remove($children);
413
                }
414
415
                $this->modelManager->remove($menuItem);
416
            }
417
            $this->modelManager->flush();
418
        }
419
    }
420
421
    /**
422
     * Create most used indexes in s_plugin_connect_items table.
423
     */
424
    private function addConnectItemsIndex()
425
    {
426
        if (version_compare($this->version, '1.1.1', '<=')) {
427
            try {
428
                $this->db->query('ALTER TABLE s_plugin_connect_items ADD INDEX stream(shop_id, stream)');
429
                $this->db->query('ALTER TABLE s_plugin_connect_items MODIFY group_id VARCHAR(64)');
430
                $this->db->query('ALTER TABLE s_plugin_connect_items ADD INDEX source_id (source_id, shop_id)');
431
                $this->db->query('ALTER TABLE s_plugin_connect_items ADD INDEX group_id (group_id, shop_id)');
432
            } catch (\Exception $e) {
433
                // ignore it if exists
434
                $this->logger->write(
435
                    true,
436
                    sprintf('An error occurred during update to version %s stacktrace: %s', $this->version, $e->getTraceAsString()),
437
                    $e->getMessage()
438
                );
439
            }
440
        }
441
    }
442
443
    /**
444
     * Create the mapping table between connect remote categories and local categories.
445
     */
446
    private function createRemoteToLocalCategoriesTable()
447
    {
448
        if (version_compare($this->version, '1.1.3', '<=')) {
449
            try {
450
                $this->db->query(
451
                    'CREATE TABLE IF NOT EXISTS `s_plugin_connect_categories_to_local_categories` (
452
                  `remote_category_id` int(11) NOT NULL,
453
                  `local_category_id` int(11) unsigned NOT NULL,
454
                  PRIMARY KEY (`remote_category_id`, `local_category_id`),
455
                  CONSTRAINT s_plugin_connect_remote_categories_fk_remote_category_id FOREIGN KEY (remote_category_id) REFERENCES s_plugin_connect_categories (id) ON DELETE CASCADE,
456
                  CONSTRAINT s_plugin_connect_remote_categories_fk_local_category_id FOREIGN KEY (local_category_id) REFERENCES s_categories (id) ON DELETE CASCADE
457
                  ) ENGINE = InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;'
458
                );
459
                $result = $this->db->query('SELECT pcc.id, pcc.local_category_id
460
                                FROM s_plugin_connect_categories pcc
461
                                WHERE pcc.local_category_id IS NOT NULL');
462
463
                while ($row = $result->fetch()) {
464
                    $this->db->query(
465
                        'INSERT INTO `s_plugin_connect_categories_to_local_categories`
466
                        (`remote_category_id`, `local_category_id`)
467
                        VALUES (?, ?)',
468
                        [$row['id'],$row['local_category_id']]
469
                    );
470
                }
471
            } catch (\Exception $e) {
472
                // ignore it if exists
473
                $this->logger->write(
474
                    true,
475
                    sprintf('An error occurred during update to version %s stacktrace: %s', $this->version, $e->getTraceAsString()),
476
                    $e->getMessage()
477
                );
478
            }
479
        }
480
    }
481
482 View Code Duplication
    private function recreateRemoteCategoriesAndProductAssignments()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
483
    {
484
        if (version_compare($this->version, '1.1.4', '<=')) {
485
            try {
486
                if (!$this->existsConfig('recreateConnectCategories')) {
487
                    $this->db->query('INSERT INTO `s_plugin_connect_config` (`name`, `value`) VALUES ("recreateConnectCategories", "0")');
488
                }
489
            } catch (\Exception $e) {
490
                // ignore it if exists
491
                $this->logger->write(
492
                    true,
493
                    sprintf('An error occurred during update to version %s stacktrace: %s', $this->version, $e->getTraceAsString()),
494
                    $e->getMessage()
495
                );
496
            }
497
        }
498
    }
499
500 View Code Duplication
    private function setDefaultConfigForUpdateOrderStatus()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
501
    {
502
        if (version_compare($this->version, '1.1.7', '<=')) {
503
            try {
504
                if (!$this->existsConfig('updateOrderStatus')) {
505
                    $this->db->query('INSERT INTO `s_plugin_connect_config` (`name`, `value`, `groupName`) VALUES ("updateOrderStatus", "0", "import")');
506
                }
507
            } catch (\Exception $e) {
508
                // ignore it if exists
509
                $this->logger->write(
510
                    true,
511
                    sprintf('An error occurred during update to version %s stacktrace: %s', $this->version, $e->getTraceAsString()),
512
                    $e->getMessage()
513
                );
514
            }
515
        }
516
    }
517
518
    /**
519
      * Create index by articleID in s_plugin_connect_product_to_categories table.
520
      */
521
    private function addProductToCategoryIndex()
522
    {
523
        if (version_compare($this->version, '1.1.7', '<=')) {
524
            try {
525
                $this->db->query('ALTER TABLE s_plugin_connect_product_to_categories ADD INDEX article_id(articleID)');
526
            } catch (\Exception $e) {
527
                // ignore it if exists
528
                $this->logger->write(
529
                    true,
530
                    sprintf('An error occurred during update to version %s stacktrace: %s', $this->version, $e->getTraceAsString()),
531
                    $e->getMessage()
532
                );
533
            }
534
        }
535
    }
536
537
    private function addShopIdToConnectCategories()
538
    {
539
        if (version_compare($this->version, '1.1.7', '<=')) {
540
            try {
541
                if (!$this->existsConfig('addShopIdToConnectCategories')) {
542
                    $this->db->query('INSERT INTO `s_plugin_connect_config` (`name`, `value`) VALUES ("addShopIdToConnectCategories", "0")');
543
                }
544
                $this->db->query('ALTER TABLE s_plugin_connect_categories ADD COLUMN `shop_id` int(11) NULL');
545
                $this->db->query('ALTER TABLE s_plugin_connect_categories DROP INDEX scuk_category_key');
546
                $this->db->query('ALTER TABLE s_plugin_connect_categories ADD UNIQUE KEY `scuk_connect_category_for_shop_id` (`category_key`,`shop_id`)');
547
            } catch (\Exception $e) {
548
                // ignore it if exists
549
                $this->logger->write(
550
                    true,
551
                    sprintf('An error occurred during update to version %s stacktrace: %s', $this->version, $e->getTraceAsString()),
552
                    $e->getMessage()
553
                );
554
            }
555
        }
556
    }
557
558
    private function addStreamColumnToConnectToLocalCategories()
559
    {
560
        if (version_compare($this->version, '1.1.8', '<=')) {
561
            try {
562
                $this->db->query('ALTER TABLE s_plugin_connect_categories_to_local_categories DROP FOREIGN KEY s_plugin_connect_remote_categories_fk_remote_category_id');
563
                $this->db->query('ALTER TABLE s_plugin_connect_categories_to_local_categories DROP FOREIGN KEY s_plugin_connect_remote_categories_fk_local_category_id');
564
                $this->db->query('ALTER TABLE s_plugin_connect_categories_to_local_categories DROP PRIMARY KEY');
565
                $this->db->query('ALTER TABLE s_plugin_connect_categories_to_local_categories ADD COLUMN `id` int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST');
566
                $this->db->query('ALTER TABLE s_plugin_connect_categories_to_local_categories ADD COLUMN `stream` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL');
567
                $this->db->query('ALTER TABLE s_plugin_connect_categories_to_local_categories ADD CONSTRAINT s_plugin_connect_remote_categories_fk_remote_category_id FOREIGN KEY (remote_category_id) REFERENCES s_plugin_connect_categories (id) ON DELETE CASCADE');
568
                $this->db->query('ALTER TABLE s_plugin_connect_categories_to_local_categories ADD CONSTRAINT s_plugin_connect_remote_categories_fk_local_category_id FOREIGN KEY (local_category_id) REFERENCES s_categories (id) ON DELETE CASCADE');
569
            } catch (\Exception $e) {
570
                // ignore it if exists
571
                $this->logger->write(
572
                    true,
573
                    sprintf('An error occurred during update to version %s stacktrace: %s', $this->version, $e->getTraceAsString()),
574
                    $e->getMessage()
575
                );
576
            }
577
        }
578
    }
579
580 View Code Duplication
    private function changeExportStatusToVarchar()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
581
    {
582
        if (version_compare($this->version, '1.1.8', '<=')) {
583
            try {
584
                $this->db->query('ALTER TABLE s_plugin_connect_items MODIFY export_status varchar(255)');
585
                $this->db->query('ALTER TABLE s_plugin_connect_items ADD INDEX IDX_revision (revision)');
586
                $this->db->query('ALTER TABLE s_plugin_connect_items ADD INDEX IDX_status (export_status)');
587
            } catch (\Exception $e) {
588
                // ignore it if exists
589
                $this->logger->write(
590
                    true,
591
                    sprintf('An error occurred during update to version %s stacktrace: %s', $this->version, $e->getTraceAsString()),
592
                    $e->getMessage()
593
                );
594
            }
595
        }
596
    }
597
598
    private function addArticleRelationsTable()
599
    {
600
        if (version_compare($this->version, '1.1.8', '<=')) {
601
            try {
602
                $this->db->query(
603
                    'CREATE TABLE IF NOT EXISTS `s_plugin_connect_article_relations` (
604
                  `id` int(11) NOT NULL AUTO_INCREMENT,
605
                  `article_id` int(11) unsigned NOT NULL,
606
                  `shop_id` int(11) NOT NULL,
607
                  `related_article_local_id` int(11) NOT NULL,
608
                  `relationship_type` varchar(32) COLLATE utf8_unicode_ci NOT NULL,
609
                  PRIMARY KEY (`id`),
610
                  UNIQUE KEY `relations` (`article_id`, `shop_id`, `related_article_local_id`, `relationship_type`),
611
                  CONSTRAINT s_plugin_connect_article_relations_fk_article_id FOREIGN KEY (article_id) REFERENCES s_articles (id) ON DELETE CASCADE
612
                  ) ENGINE = InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;'
613
                );
614
            } catch (\Exception $e) {
615
                // ignore it if exists
616
                $this->logger->write(
617
                    true,
618
                    sprintf('An error occurred during update to version %s stacktrace: %s', $this->version, $e->getTraceAsString()),
619
                    $e->getMessage()
620
                );
621
            }
622
        }
623
    }
624
625 View Code Duplication
    private function addOverwriteMainImage()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
626
    {
627
        if (version_compare($this->version, '1.1.8', '<=')) {
628
            try {
629
                if (!$this->existsConfig('overwriteProductMainImage')) {
630
                    $this->db->query('INSERT INTO `s_plugin_connect_config` (`name`, `value`, `groupName`) VALUES ("overwriteProductMainImage", "1", "import")');
631
                }
632
                $this->db->query('ALTER TABLE `s_plugin_connect_items` ADD COLUMN `update_main_image` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL');
633
            } catch (\Exception $e) {
634
                // ignore it if exists
635
                $this->logger->write(
636
                    true,
637
                    sprintf('An error occurred during update to version %s stacktrace: %s', $this->version, $e->getTraceAsString()),
638
                    $e->getMessage()
639
                );
640
            }
641
        }
642
    }
643
644
    private function changeGroupNameImportSettings()
645
    {
646
        if (version_compare($this->version, '1.1.11', '<=')) {
647
            try {
648
                $this->db->query('UPDATE `s_plugin_connect_config` SET `groupName` = "import" WHERE `groupName` = "general" AND `name` IN ("createCategoriesAutomatically", "activateProductsAutomatically", "createUnitsAutomatically",
649
                                            "detailShopInfo", "checkoutShopInfo", "showShippingCostsSeparately")');
650
            } catch (\Exception $e) {
651
                $this->logger->write(
652
                    true,
653
                    sprintf('An error occurred during update to version %s stacktrace: %s', $this->version, $e->getTraceAsString()),
654
                    $e->getMessage()
655
                );
656
            }
657
        }
658
    }
659
660
    private function addArticleDetailsForeignKey()
661
    {
662
        if (version_compare($this->version, '1.1.11', '<=')) {
663
            try {
664
                $this->db->query('
665
                ALTER TABLE s_plugin_connect_items
666
                ADD FOREIGN KEY (`article_detail_id`) REFERENCES s_articles_details (id) ON DELETE SET NULL
667
                ');
668
            } catch (\Exception $e) {
669
                $this->logger->write(
670
                    true,
671
                    sprintf('An error occurred during update to version %s stacktrace: %s', $this->version, $e->getTraceAsString()),
672
                    $e->getMessage()
673
                );
674
            }
675
        }
676
    }
677
678 View Code Duplication
    private function addConfigForBasketRemovals()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
679
    {
680
        if (version_compare($this->version, '1.1.18', '<=')) {
681
            try {
682
                if (!$this->existsConfig('removeBasketAdditions')) {
683
                    $this->db->query('INSERT INTO `s_plugin_connect_config` (`name`, `value`, `groupName`) VALUES ("removeBasketAdditions", "1", "import")');
684
                }
685
            } catch (\Exception $e) {
686
                $this->logger->write(
687
                    true,
688
                    sprintf('An error occurred during update to version %s stacktrace: %s', $this->version, $e->getTraceAsString()),
689
                    $e->getMessage()
690
                );
691
            }
692
        }
693
    }
694
695
    /**
696
     * @param string $configName
697
     * @return bool
698
     */
699
    private function existsConfig($configName) {
700
        $stmt = $this->db->prepare('SELECT * FROM s_plugin_connect_config WHERE `name` = ?');
701
        $stmt->execute([$configName]);
702
703
        return $stmt->fetch() !== false;
704
    }
705
}
706