Completed
Push — master ( 1eb698...b45135 )
by Jonas
03:26
created

Update::existsConfig()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 4

Duplication

Lines 3
Ratio 50 %

Importance

Changes 0
Metric Value
cc 1
eloc 4
nc 1
nop 1
dl 3
loc 6
rs 9.4285
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
104
        return true;
105
    }
106
107
    /**
108
     * Forces the SDK to re-verify the API key
109
     */
110
    public function reVerifySDK()
111
    {
112
        $this->db->query(
113
            'UPDATE sw_connect_shop_config
114
            SET s_config = ?
115
            WHERE s_shop = "_last_update_"
116
            LIMIT 1; ',
117
            [time() - 8 * 60 * 60 * 24]
118
        );
119
    }
120
121
    private function createExportedFlag()
122
    {
123
        if (version_compare($this->version, '1.0.1', '<=')) {
124
            $this->db->query(
125
                'ALTER TABLE `s_plugin_connect_items`
126
                ADD COLUMN `exported` TINYINT(1) DEFAULT 0'
127
            );
128
129
            $this->db->query(
130
                'UPDATE `s_plugin_connect_items`
131
                SET `exported` = 1
132
                WHERE (`export_status` = ? OR `export_status` = ? OR `export_status` = ?) AND `shop_id` IS NULL',
133
                [Attribute::STATUS_INSERT, Attribute::STATUS_UPDATE, Attribute::STATUS_SYNCED]
134
            );
135
        }
136
    }
137
138
    private function removeRedirectMenu()
139
    {
140
        if (version_compare($this->version, '1.0.4', '<=')) {
141
            $connectItem = $this->bootstrap->Menu()->findOneBy(['label' => 'Open Connect', 'action' => '']);
142
            if ($connectItem) {
143
                $this->modelManager->remove($connectItem);
144
                $this->modelManager->flush();
145
            }
146
        }
147
    }
148
149
    private function updateConnectAttribute()
150
    {
151
        if (version_compare($this->version, '1.0.6', '<=')) {
152
            $result = $this->db->query("SELECT value FROM s_plugin_connect_config WHERE name = 'connectAttribute'");
153
            $row = $result->fetch();
154
            $attr = 19;
155
            if ($row) {
156
                $attr = $row['value'];
157
            }
158
159
            $this->db->query('
160
                    UPDATE `s_articles_attributes` 
161
                    SET `connect_reference` = `attr' . $attr . '` 
162
                    WHERE connect_reference IS NULL;
163
                ');
164
165
            $this->db->query("DELETE FROM s_plugin_connect_config WHERE name = 'connectAttribute'");
166
        }
167
    }
168
169
    private function addConnectDescriptionElement()
170
    {
171
        if (version_compare($this->version, '1.0.9', '<=')) {
172
            $tableName = $this->modelManager->getClassMetadata('Shopware\Models\Attribute\Article')->getTableName();
173
            $columnName = 'connect_product_description';
174
175
            $repo = $this->modelManager->getRepository('Shopware\Models\Attribute\Configuration');
176
            $element = $repo->findOneBy([
177
                'tableName' => $tableName,
178
                'columnName' => $columnName,
179
            ]);
180
181
            if (!$element) {
182
                $element = new Configuration();
183
                $element->setTableName($tableName);
184
                $element->setColumnName($columnName);
185
            }
186
187
            $element->setColumnType('html');
188
            $element->setTranslatable(true);
189
            $element->setLabel('Connect Beschreibung');
190
            $element->setDisplayInBackend(true);
191
192
            $this->modelManager->persist($element);
193
            $this->modelManager->flush();
194
        }
195
    }
196
197
    private function updateProductDescriptionSetting()
198
    {
199
        if (version_compare($this->version, '1.0.9', '<=')) {
200
            //migrates to the new export settings
201
            $result = $this->db->query("SELECT `value` FROM s_plugin_connect_config WHERE name = 'alternateDescriptionField'");
202
            $row = $result->fetch();
203
204
            if ($row) {
205
                $mapper = [
206
                    'a.description' => BaseProductQuery::SHORT_DESCRIPTION_FIELD,
207
                    'a.descriptionLong' => BaseProductQuery::LONG_DESCRIPTION_FIELD,
208
                    'attribute.connectProductDescription' => BaseProductQuery::CONNECT_DESCRIPTION_FIELD,
209
                ];
210
211
                if ($name = $mapper[$row['value']]) {
212
                    $result = $this->db->query("SELECT `id` FROM s_plugin_connect_config WHERE name = '$name'");
213
                    $row = $result->fetch();
214
215
                    $id = null;
216
                    if (isset($row['id'])) {
217
                        $id = $row['id'];
218
                    }
219
220
                    $this->db->query(
221
                        "REPLACE INTO `s_plugin_connect_config`
222
                        (`id`, `name`, `value`, `shopId`, `groupName`)
223
                        VALUES
224
                        (?, ?, 1, null, 'export')",
225
                        [$id, $name]
226
                    );
227
                }
228
            }
229
230
            $this->db->query("
231
                ALTER TABLE `s_plugin_connect_items`
232
                ADD `update_additional_description` VARCHAR(255) NULL DEFAULT 'inherit' AFTER `update_short_description`;
233
            ");
234
        }
235
    }
236
237
    private function createUpdateAdditionalDescriptionColumn()
238
    {
239
        // for some reason update_additional_description column is missing in 1.0.11
240
        if (version_compare($this->version, '1.0.11', '<=')) {
241
            try {
242
                $this->db->query("
243
                        ALTER TABLE `s_plugin_connect_items`
244
                        ADD `update_additional_description` VARCHAR(255) NULL DEFAULT 'inherit' AFTER `update_short_description`;
245
                    ");
246
            } catch (\Exception $e) {
247
                // ignore it if the column already exists
248
            }
249
        }
250
    }
251
252
    private function createDynamicStreamTable()
253
    {
254
        if (version_compare($this->version, '1.0.12', '<=')) {
255
            $query = "CREATE TABLE IF NOT EXISTS `s_plugin_connect_streams_relation` (
256
                `stream_id` int(11) unsigned NOT NULL,
257
                `article_id` int(11) unsigned NOT NULL,
258
                `deleted` int(1) NOT NULL DEFAULT '0',
259
                UNIQUE KEY `stream_id` (`stream_id`,`article_id`),
260
                CONSTRAINT s_plugin_connect_streams_selection_fk_stream_id FOREIGN KEY (stream_id) REFERENCES s_product_streams (id) ON DELETE CASCADE,
261
                CONSTRAINT s_plugin_connect_streams_selection_fk_article_id FOREIGN KEY (article_id) REFERENCES s_articles (id) ON DELETE CASCADE
262
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;";
263
264
            $this->db->exec($query);
265
        }
266
    }
267
268
    private function addOrderStatus()
269
    {
270
        if (version_compare($this->version, '1.0.12', '<=')) {
271
            $query = $this->modelManager->getRepository('Shopware\Models\Order\Status')->createQueryBuilder('s');
272
            $query->select('MAX(s.id)');
273
            $result = $query->getQuery()->getOneOrNullResult();
274
275
            if (count($result) > 0) {
276
                $currentId = (int) reset($result);
277
            } else {
278
                $currentId = 0;
279
            }
280
281
            $name = ConnectOrderUtil::ORDER_STATUS_ERROR;
282
            $group = Status::GROUP_STATE;
283
284
            $isExists = $this->db->query(
285
                'SELECT `id` FROM `s_core_states`
286
                WHERE `name` = ? AND `group` = ?',
287
                [$name, $group]
288
            )->fetch();
289
290
            if ($isExists) {
291
                return;
292
            }
293
294
            ++$currentId;
295
            $this->db->query(
296
                'INSERT INTO `s_core_states`
297
                (`id`, `name`, `description`, `position`, `group`, `mail`)
298
                VALUES (?, ?, ?, ?, ?, ?)',
299
                [$currentId, $name, 'SC error', $currentId, $group, 0]
300
            );
301
        }
302
    }
303
304
    /**
305
     * Replace longDescriptionField and shortDescription values,
306
     * because of wrong snippets in previous versions.
307
     *
308
     * ExtJs view show longDescription label, but the value was stored as shortDescription
309
     */
310
    private function fixExportDescriptionSettings()
311
    {
312
        if (version_compare($this->version, '1.0.12', '<=')) {
313
            $rows = $this->db->fetchPairs(
314
                'SELECT `name`, `value` FROM s_plugin_connect_config WHERE name = ? OR name = ?',
315
                ['longDescriptionField', 'shortDescriptionField']
316
            );
317
318
            if (!array_key_exists('longDescriptionField', $rows) || !array_key_exists('shortDescriptionField', $rows)) {
319
                return;
320
            }
321
322
            if (($rows['longDescriptionField'] == 1 && $rows['shortDescriptionField'] == 1)
323
                || ($rows['longDescriptionField'] == 0 && $rows['shortDescriptionField'] == 0)) {
324
                return;
325
            }
326
327
            $newValues = [
328
                'longDescriptionField' => $rows['shortDescriptionField'],
329
                'shortDescriptionField' => $rows['longDescriptionField'],
330
            ];
331
332
            $this->db->query(
333
                'UPDATE `s_plugin_connect_config`
334
                SET `value` = ?
335
                WHERE `name` = ?',
336
                [$newValues['longDescriptionField'], 'longDescriptionField']
337
            );
338
339
            $this->db->query(
340
                'UPDATE `s_plugin_connect_config`
341
                SET `value` = ?
342
                WHERE `name` = ?',
343
                [$newValues['shortDescriptionField'], 'shortDescriptionField']
344
            );
345
        }
346
    }
347
348
    private function fixMarketplaceUrl()
349
    {
350
        if (version_compare($this->version, '1.0.12', '<=')) {
351
            $repo = $this->modelManager->getRepository('Shopware\Models\Config\Form');
352
            /** @var \Shopware\Models\Config\Form $form */
353
            $form = $repo->findOneBy([
354
                'name' => 'SwagConnect',
355
            ]);
356
357
            if (!$form) {
358
                return;
359
            }
360
361
            /** @var \Shopware\Models\Config\Element $element */
362
            foreach ($form->getElements() as $element) {
363
                if ($element->getName() != 'connectDebugHost') {
364
                    continue;
365
                }
366
367 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...
368
                    $element->setValue('sn.' . $element->getValue());
369
                    $this->modelManager->persist($element);
370
                }
371
372
                $values = $element->getValues();
373
                if (count($values) > 0) {
374
                    /** @var \Shopware\Models\Config\Value $element */
375
                    $value = $values[0];
376 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...
377
                        $value->setValue('sn.' . $value->getValue());
378
                        $this->modelManager->persist($value);
379
                    }
380
                }
381
382
                $this->modelManager->flush();
383
            }
384
        }
385
    }
386
387
    private function addIndexToChangeTable()
388
    {
389
        if (version_compare($this->version, '1.0.16', '<=')) {
390
            $this->db->query('
391
              ALTER TABLE `sw_connect_change`
392
              ADD INDEX `c_operation` (`c_operation`)
393
             ');
394
        }
395
    }
396
397
    /**
398
     * In some cases Connect main menu was duplicated
399
     * when shop is connected to SEM project. All not needed menu items must be removed.
400
     */
401
    private function removeDuplicatedMenuItems()
402
    {
403
        if (version_compare($this->version, '1.0.16', '<=')) {
404
            $mainMenuItems = $this->bootstrap->Menu()->findBy([
405
                'class' => Menu::CONNECT_CLASS,
406
                'parent' => null,
407
            ], ['id' => 'ASC']);
408
409
            foreach (array_slice($mainMenuItems, 1) as $menuItem) {
410
                foreach ($menuItem->getChildren() as $children) {
411
                    $this->modelManager->remove($children);
412
                }
413
414
                $this->modelManager->remove($menuItem);
415
            }
416
            $this->modelManager->flush();
417
        }
418
    }
419
420
    /**
421
     * Create most used indexes in s_plugin_connect_items table.
422
     */
423 View Code Duplication
    private function addConnectItemsIndex()
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...
424
    {
425
        if (version_compare($this->version, '1.1.1', '<=')) {
426
            try {
427
                $this->db->query('ALTER TABLE s_plugin_connect_items ADD INDEX stream(shop_id, stream)');
428
                $this->db->query('ALTER TABLE s_plugin_connect_items MODIFY group_id VARCHAR(64)');
429
                $this->db->query('ALTER TABLE s_plugin_connect_items ADD INDEX source_id (source_id, shop_id)');
430
                $this->db->query('ALTER TABLE s_plugin_connect_items ADD INDEX group_id (group_id, shop_id)');
431
            } catch (\Exception $e) {
432
                // ignore it if exists
433
                $this->logger->write(
434
                    true,
435
                    sprintf('An error occurred during update to version %s stacktrace: %s', $this->version, $e->getTraceAsString()),
436
                    $e->getMessage()
437
                );
438
            }
439
        }
440
    }
441
442
    /**
443
     * Create the mapping table between connect remote categories and local categories.
444
     */
445
    private function createRemoteToLocalCategoriesTable()
446
    {
447
        if (version_compare($this->version, '1.1.3', '<=')) {
448
            try {
449
                $this->db->query(
450
                    'CREATE TABLE IF NOT EXISTS `s_plugin_connect_categories_to_local_categories` (
451
                  `remote_category_id` int(11) NOT NULL,
452
                  `local_category_id` int(11) unsigned NOT NULL,
453
                  PRIMARY KEY (`remote_category_id`, `local_category_id`),
454
                  CONSTRAINT s_plugin_connect_remote_categories_fk_remote_category_id FOREIGN KEY (remote_category_id) REFERENCES s_plugin_connect_categories (id) ON DELETE CASCADE,
455
                  CONSTRAINT s_plugin_connect_remote_categories_fk_local_category_id FOREIGN KEY (local_category_id) REFERENCES s_categories (id) ON DELETE CASCADE
456
                  ) ENGINE = InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;'
457
                );
458
                $result = $this->db->query('SELECT pcc.id, pcc.local_category_id
459
                                FROM s_plugin_connect_categories pcc
460
                                WHERE pcc.local_category_id IS NOT NULL');
461
462
                while ($row = $result->fetch()) {
463
                    $this->db->query(
464
                        'INSERT INTO `s_plugin_connect_categories_to_local_categories`
465
                        (`remote_category_id`, `local_category_id`)
466
                        VALUES (?, ?)',
467
                        [$row['id'],$row['local_category_id']]
468
                    );
469
                }
470
            } catch (\Exception $e) {
471
                // ignore it if exists
472
                $this->logger->write(
473
                    true,
474
                    sprintf('An error occurred during update to version %s stacktrace: %s', $this->version, $e->getTraceAsString()),
475
                    $e->getMessage()
476
                );
477
            }
478
        }
479
    }
480
481
    private function recreateRemoteCategoriesAndProductAssignments()
482
    {
483
        if (version_compare($this->version, '1.1.4', '<=')) {
484
            try {
485
                if (!$this->existsConfig('recreateConnectCategories')) {
486
                    $this->db->query('INSERT INTO `s_plugin_connect_config` (`name`, `value`) VALUES ("recreateConnectCategories", "0")');
487
                }
488
            } catch (\Exception $e) {
489
                // ignore it if exists
490
                $this->logger->write(
491
                    true,
492
                    sprintf('An error occurred during update to version %s stacktrace: %s', $this->version, $e->getTraceAsString()),
493
                    $e->getMessage()
494
                );
495
            }
496
        }
497
    }
498
499
    private function setDefaultConfigForUpdateOrderStatus()
500
    {
501
        if (version_compare($this->version, '1.1.7', '<=')) {
502
            try {
503
                if (!$this->existsConfig('updateOrderStatus')) {
504
                    $this->db->query('INSERT INTO `s_plugin_connect_config` (`name`, `value`, `groupName`) VALUES ("updateOrderStatus", "0", "import")');
505
                }
506
            } catch (\Exception $e) {
507
                // ignore it if exists
508
                $this->logger->write(
509
                    true,
510
                    sprintf('An error occurred during update to version %s stacktrace: %s', $this->version, $e->getTraceAsString()),
511
                    $e->getMessage()
512
                );
513
            }
514
        }
515
    }
516
517
    /**
518
      * Create index by articleID in s_plugin_connect_product_to_categories table.
519
      */
520 View Code Duplication
    private function addProductToCategoryIndex()
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...
521
    {
522
        if (version_compare($this->version, '1.1.7', '<=')) {
523
            try {
524
                $this->db->query('ALTER TABLE s_plugin_connect_product_to_categories ADD INDEX article_id(articleID)');
525
            } catch (\Exception $e) {
526
                // ignore it if exists
527
                $this->logger->write(
528
                    true,
529
                    sprintf('An error occurred during update to version %s stacktrace: %s', $this->version, $e->getTraceAsString()),
530
                    $e->getMessage()
531
                );
532
            }
533
        }
534
    }
535
536 View Code Duplication
    private function addShopIdToConnectCategories()
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...
537
    {
538
        if (version_compare($this->version, '1.1.7', '<=')) {
539
            try {
540
                if (!$this->existsConfig('addShopIdToConnectCategories')) {
541
                    $this->db->query('INSERT INTO `s_plugin_connect_config` (`name`, `value`) VALUES ("addShopIdToConnectCategories", "0")');
542
                }
543
                $this->db->query('ALTER TABLE s_plugin_connect_categories ADD COLUMN `shop_id` int(11) NULL');
544
                $this->db->query('ALTER TABLE s_plugin_connect_categories DROP INDEX scuk_category_key');
545
                $this->db->query('ALTER TABLE s_plugin_connect_categories ADD UNIQUE KEY `scuk_connect_category_for_shop_id` (`category_key`,`shop_id`)');
546
            } catch (\Exception $e) {
547
                // ignore it if exists
548
                $this->logger->write(
549
                    true,
550
                    sprintf('An error occurred during update to version %s stacktrace: %s', $this->version, $e->getTraceAsString()),
551
                    $e->getMessage()
552
                );
553
            }
554
        }
555
    }
556
557
    private function addStreamColumnToConnectToLocalCategories()
558
    {
559
        if (version_compare($this->version, '1.1.8', '<=')) {
560
            try {
561
                $this->db->query('ALTER TABLE s_plugin_connect_categories_to_local_categories DROP FOREIGN KEY s_plugin_connect_remote_categories_fk_remote_category_id');
562
                $this->db->query('ALTER TABLE s_plugin_connect_categories_to_local_categories DROP FOREIGN KEY s_plugin_connect_remote_categories_fk_local_category_id');
563
                $this->db->query('ALTER TABLE s_plugin_connect_categories_to_local_categories DROP PRIMARY KEY');
564
                $this->db->query('ALTER TABLE s_plugin_connect_categories_to_local_categories ADD COLUMN `id` int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST');
565
                $this->db->query('ALTER TABLE s_plugin_connect_categories_to_local_categories ADD COLUMN `stream` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL');
566
                $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');
567
                $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');
568
            } catch (\Exception $e) {
569
                // ignore it if exists
570
                $this->logger->write(
571
                    true,
572
                    sprintf('An error occurred during update to version %s stacktrace: %s', $this->version, $e->getTraceAsString()),
573
                    $e->getMessage()
574
                );
575
            }
576
        }
577
    }
578
579 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...
580
    {
581
        if (version_compare($this->version, '1.1.8', '<=')) {
582
            try {
583
                $this->db->query('ALTER TABLE s_plugin_connect_items MODIFY export_status varchar(255)');
584
                $this->db->query('ALTER TABLE s_plugin_connect_items ADD INDEX IDX_revision (revision)');
585
                $this->db->query('ALTER TABLE s_plugin_connect_items ADD INDEX IDX_status (export_status)');
586
            } catch (\Exception $e) {
587
                // ignore it if exists
588
                $this->logger->write(
589
                    true,
590
                    sprintf('An error occurred during update to version %s stacktrace: %s', $this->version, $e->getTraceAsString()),
591
                    $e->getMessage()
592
                );
593
            }
594
        }
595
    }
596
597 View Code Duplication
    private function addArticleRelationsTable()
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...
598
    {
599
        if (version_compare($this->version, '1.1.8', '<=')) {
600
            try {
601
                $this->db->query(
602
                    'CREATE TABLE IF NOT EXISTS `s_plugin_connect_article_relations` (
603
                  `id` int(11) NOT NULL AUTO_INCREMENT,
604
                  `article_id` int(11) unsigned NOT NULL,
605
                  `shop_id` int(11) NOT NULL,
606
                  `related_article_local_id` int(11) NOT NULL,
607
                  `relationship_type` varchar(32) COLLATE utf8_unicode_ci NOT NULL,
608
                  PRIMARY KEY (`id`),
609
                  UNIQUE KEY `relations` (`article_id`, `shop_id`, `related_article_local_id`, `relationship_type`),
610
                  CONSTRAINT s_plugin_connect_article_relations_fk_article_id FOREIGN KEY (article_id) REFERENCES s_articles (id) ON DELETE CASCADE
611
                  ) ENGINE = InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;'
612
                );
613
            } catch (\Exception $e) {
614
                // ignore it if exists
615
                $this->logger->write(
616
                    true,
617
                    sprintf('An error occurred during update to version %s stacktrace: %s', $this->version, $e->getTraceAsString()),
618
                    $e->getMessage()
619
                );
620
            }
621
        }
622
    }
623
624 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...
625
    {
626
        if (version_compare($this->version, '1.1.8', '<=')) {
627
            try {
628
                if (!$this->existsConfig('overwriteProductMainImage')) {
629
                    $this->db->query('INSERT INTO `s_plugin_connect_config` (`name`, `value`, `groupName`) VALUES ("overwriteProductMainImage", "1", "import")');
630
                }
631
                $this->db->query('ALTER TABLE `s_plugin_connect_items` ADD COLUMN `update_main_image` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL');
632
            } catch (\Exception $e) {
633
                // ignore it if exists
634
                $this->logger->write(
635
                    true,
636
                    sprintf('An error occurred during update to version %s stacktrace: %s', $this->version, $e->getTraceAsString()),
637
                    $e->getMessage()
638
                );
639
            }
640
        }
641
    }
642
643 View Code Duplication
    private function changeGroupNameImportSettings()
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...
644
    {
645
        if (version_compare($this->version, '1.1.11', '<=')) {
646
            try {
647
                $this->db->query('UPDATE `s_plugin_connect_config` SET `groupName` = "import" WHERE `groupName` = "general" AND `name` IN ("createCategoriesAutomatically", "activateProductsAutomatically", "createUnitsAutomatically",
648
                                            "detailShopInfo", "checkoutShopInfo", "showShippingCostsSeparately")');
649
            } catch (\Exception $e) {
650
                $this->logger->write(
651
                    true,
652
                    sprintf('An error occurred during update to version %s stacktrace: %s', $this->version, $e->getTraceAsString()),
653
                    $e->getMessage()
654
                );
655
            }
656
        }
657
    }
658
659 View Code Duplication
    private function addArticleDetailsForeignKey()
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...
660
    {
661
        if (version_compare($this->version, '1.1.11', '<=')) {
662
            try {
663
                $this->db->query('
664
                ALTER TABLE s_plugin_connect_items
665
                ADD FOREIGN KEY (`article_detail_id`) REFERENCES s_articles_details (id) ON DELETE SET NULL
666
                ');
667
            } catch (\Exception $e) {
668
                $this->logger->write(
669
                    true,
670
                    sprintf('An error occurred during update to version %s stacktrace: %s', $this->version, $e->getTraceAsString()),
671
                    $e->getMessage()
672
                );
673
            }
674
        }
675
    }
676
677
    /**
678
     * @param string $configName
679
     * @return bool
680
     */
681
    private function existsConfig($configName) {
682
        $stmt = $this->db->prepare('SELECT * FROM s_plugin_connect_config WHERE `name` = ?');
683
        $stmt->execute([$configName]);
684
685
        return $stmt->fetch() !== false;
686
    }
687
}
688