Completed
Pull Request — master (#452)
by Jonas
03:17
created

Config::getMarketplaceUrl()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 8
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 4
nc 2
nop 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\Components;
9
10
use Shopware\Components\Plugin\CachedConfigReader;
11
use ShopwarePlugins\Connect\Components\Marketplace\MarketplaceSettings;
12
use Shopware\Components\Model\ModelManager;
13
use Shopware\CustomModels\Connect\Config as ConfigModel;
14
use Shopware\Connect\Gateway\PDO;
15
16
/**
17
 * @category  Shopware
18
 * @package   Shopware\Plugins\SwagConnect
19
 */
20
class Config
21
{
22
    const UPDATE_MANUAL = 0;
23
    const UPDATE_AUTO = 1;
24
    const UPDATE_CRON_JOB = 2;
25
    const MARKETPLACE_URL = 'sn.connect.shopware.com';
26
27
    /**
28
     * @var ModelManager
29
     */
30
    private $manager;
31
32
    /**
33
     * @var \Shopware\CustomModels\Connect\ConfigRepository
34
     */
35
    private $repository;
36
37
    /** @var \Shopware\Models\Shop\Shop */
38
    private $shopRepository;
39
40
    private $customerGroupRepository;
41
42
    private $priceGateway;
43
44
    private $connectGateway;
45
46
    /** @var CachedConfigReader */
47
    private $configReader;
48
49
    /**
50
     * @var TriggerService
51
     */
52
    private $triggerService;
53
    /**
54
     * @param ModelManager $manager
55
     * @param CachedConfigReader $configReader
56
     */
57
    public function __construct(ModelManager $manager, CachedConfigReader $configReader)
58
    {
59
        $this->manager = $manager;
60
        $this->configReader = $configReader;
61
    }
62
63
    /**
64
     * @param $name
65
     * @param null $default
66
     * @param null $shopId
67
     * @return null
68
     */
69
    public function getConfig($name, $default = null, $shopId = null)
70
    {
71
        $result = $this->getPluginConfig($name);
72
        if (!empty($result)) {
73
            return $result;
74
        }
75
76
        if (is_null($shopId)) {
77
            return $this->getMainConfig($name, $default);
78
        }
79
        $query = $this->getConfigRepository()->getConfigsQuery($name, $shopId);
80
        $query->setMaxResults(1);
81
        $result = $query->getResult();
82
83
        if (count($result) > 0 && $model = reset($result)) {
84
            $decodedString = json_decode($model->getValue(), true);
85
            if ($decodedString !== null) {
86
                return $decodedString;
87
            }
88
89
            return $model->getValue();
90
        }
91
92
        $shop = $this->getShopRepository()->find($shopId);
93
        if (!$shop) {
94
            return $this->getMainConfig($name, $default);
95
        }
96
97
        $mainShop = $shop->getMain();
98
        if ($mainShop) {
99
            $mainShopId = $mainShop->getId();
100
            $query = $this->getConfigRepository()->getConfigsQuery($name, $mainShopId);
101
            $query->setMaxResults(1);
102
            $result = $query->getResult();
103
            $model = $result[0];
104
105
            if ($model) {
106
                $decodedString = json_decode($model->getValue(), true);
107
                if ($decodedString !== null) {
108
                    return $decodedString;
109
                }
110
111
                return $model->getValue();
112
            }
113
        }
114
115
        return $this->getMainConfig($name, $default);
116
    }
117
118
    /**
119
     * @return bool
120
     */
121
    public function hasSsl()
122
    {
123
        $builder = $this->manager->getConnection()->createQueryBuilder();
124
        $builder->select('cs.secure')
125
            ->from('s_core_shops', 'cs')
126
            ->where('cs.default = :default')
127
            ->setParameter('default', true);
128
129
        return (bool) $builder->execute()->fetchColumn();
130
    }
131
132
    /**
133
     * @return bool
134
     */
135
    public function isCronActive()
136
    {
137
        if ($this->isCronPluginActive() && $this->isDynamicStreamCronActive()) {
138
            return true;
139
        }
140
141
        return false;
142
    }
143
144
    /**
145
     * @return bool
146
     */
147
    public function isCronPluginActive()
148
    {
149
        $builder = $this->manager->getConnection()->createQueryBuilder();
150
        $builder->select('cp.active')
151
            ->from('s_core_plugins', 'cp')
152
            ->where('cp.namespace = :namespace')
153
            ->andWhere('cp.name = :name')
154
            ->setParameter('namespace', 'Core')
155
            ->setParameter('name', 'Cron');
156
157
        return (bool) $builder->execute()->fetchColumn();
158
    }
159
160
    /**
161
     * @return bool
162
     */
163
    public function isDynamicStreamCronActive()
164
    {
165
        $builder = $this->manager->getConnection()->createQueryBuilder();
166
        $builder->select('cron.active')
167
            ->from('s_crontab', 'cron')
168
            ->where('cron.action LIKE :action')
169
            ->setParameter('action', '%ConnectExportDynamicStreams');
170
171
        return (bool) $builder->execute()->fetchColumn();
172
    }
173
174
    /**
175
     * @param $name
176
     * @param null $default
177
     * @return mixed
178
     */
179
    private function getPluginConfig($name, $default = null)
180
    {
181
        $config = $this->configReader->getByPluginName('SwagConnect');
182
183
        return array_key_exists($name, $config) ? $config[$name] : $default;
184
    }
185
186
    /**
187
     * @param $name
188
     * @param null $default
189
     * @return null
190
     */
191
    private function getMainConfig($name, $default = null)
192
    {
193
        $query = $this->getConfigRepository()->getConfigsQuery($name);
194
        $query->setMaxResults(1);
195
        $result = $query->getResult();
196
        if (count($result) === 0) {
197
            return $default;
198
        }
199
200
        $decodedString = json_decode($result[0]->getValue(), true);
201
        if ($decodedString !== null) {
202
            return $decodedString;
203
        }
204
205
        return $result[0]->getValue();
206
    }
207
208
    /**
209
     * @param null $name
210
     * @param null $shopId
211
     * @param null $groupName
212
     * @return array
213
     */
214
    public function getConfigs($name = null, $shopId = null, $groupName = null)
215
    {
216
        $query = $this->getConfigRepository()->getConfigsQuery($name, $shopId, $groupName);
217
218
        return $query->getResult();
219
    }
220
221
    /**
222
     * @param $name
223
     * @param $value
224
     * @param null $shopId
225
     * @param null $groupName
226
     */
227
    public function setConfig($name, $value, $shopId = null, $groupName = null)
228
    {
229
        $model = $this->getConfigRepository()->findOneBy(['name' => $name]);
230
231
        if (!$model) {
232
            $model = new ConfigModel();
233
            $this->manager->persist($model);
234
        }
235
236
        $model->setName($name);
237
238
        if (is_array($value)) {
239
            $model->setValue(json_encode($value));
240
        } else {
241
            $model->setValue($value);
242
        }
243
244
        $model->setShopId($shopId);
245
        $model->setGroupName($groupName);
246
247
        $this->manager->flush();
248
    }
249
250
    public function deleteConfig($name, $shopId = null)
251
    {
252
        $whereClause = ['name' => $name];
253
        if ($shopId > 0) {
254
            $whereClause['shopId'] = $shopId;
255
        }
256
        $model = $this->getConfigRepository()->findOneBy($whereClause);
257
        if (!$model) {
258
            throw new \Exception(sprintf(
259
                'Config entity %s not found!',
260
                $name
261
            ));
262
        }
263
264
        $this->getConfigRepository()->remove($model);
265
    }
266
267
    /**
268
     * Helper function which returns general configuration
269
     * for each shop.
270
     *
271
     * @return array
272
     */
273
    public function getGeneralConfig()
274
    {
275
        $query = "SELECT `name`, `value` FROM s_plugin_connect_config
276
        WHERE `shopId` IS NULL AND `groupName` = 'general'";
277
278
        $result = Shopware()->Db()->fetchPairs($query);
279
        $result['shopId'] = $this->getConnectPDOGateway()->getShopId();
280
281
        return [$result];
282
    }
283
284
    /**
285
     * Stores data general config
286
     * data into database.
287
     *
288
     * @param array $data
289
     */
290
    public function setGeneralConfigs($data)
291
    {
292
        // shopware must not be overwritten in config table
293
        // it can be set only during login/register
294
        unset($data['shopwareId']);
295
        // do not store shopId in plugin config table
296
        unset($data['shopId']);
297
298
        foreach ($data as $key => $configItem) {
299
300
            /** @var \Shopware\CustomModels\Connect\Config $model */
301
            $model = $this->getConfigRepository()->findOneBy([
302
                'name' => $key,
303
                'groupName' => 'general'
304
            ]);
305
306
            if (is_null($model)) {
307
                $model = new ConfigModel();
308
                $model->setName($key);
309
                $model->setGroupName('general');
310
            }
311
312
            if (is_array($configItem)) {
313
                $model->setValue(json_encode($configItem));
314
            } else {
315
                $model->setValue($configItem);
316
            }
317
318
            $this->manager->persist($model);
319
        }
320
321
        $this->manager->flush();
322
    }
323
324
    /**
325
     * Helper function which returns import configuration.
326
     *
327
     * @return array
328
     */
329
    public function getImportConfig()
330
    {
331
        $query = "SELECT `name`, `value` FROM s_plugin_connect_config
332
        WHERE `shopId` IS NULL AND `groupName` = 'import'";
333
334
        $result = Shopware()->Db()->fetchPairs($query);
335
336
        return $result;
337
    }
338
339
    /**
340
     * Stores data import config
341
     * data into database.
342
     *
343
     * @param array $data
344
     */
345
    public function setImportConfigs($data)
346
    {
347
        foreach ($data as $config) {
348
            unset($config['id']);
349
            foreach ($config as $key => $configValue) {
350
                /** @var \Shopware\CustomModels\Connect\Config $model */
351
                $model = $this->getConfigRepository()->findOneBy([
352
                    'name' => $key,
353
                    'shopId' => null,
354
                    'groupName' => 'import'
355
                ]);
356
                if (is_null($model)) {
357
                    $model = new ConfigModel();
358
                    $model->setName($key);
359
                    $model->setGroupName('import');
360
                    $model->setShopId(null);
361
                }
362
363
                if (is_array($configValue)) {
364
                    $model->setValue(json_encode($configValue));
365
                } else {
366
                    $model->setValue($configValue);
367
                }
368
                $this->manager->persist($model);
369
370
                if ($key === 'importImagesOnFirstImport') {
371
                    if ($configValue == 0) {
372
                        $this->activateConnectCronJob('ShopwareConnectImportImages', 1);
373
                    } else {
374
                        $this->activateConnectCronJob('ShopwareConnectImportImages', 0);
375
                    }
376
                }
377
            }
378
        }
379
380
        $this->manager->flush();
381
    }
382
383
    /**
384
     * Helper function which returns export configuration.
385
     *
386
     * @return array
387
     */
388
    public function getExportConfig()
389
    {
390
        $query = "SELECT `name`, `value` FROM s_plugin_connect_config
391
        WHERE `shopId` IS NULL AND `groupName` = 'export'";
392
393
        $result = Shopware()->Db()->fetchPairs($query);
394
395
        foreach ($result as $key => $value) {
396
            $decodedString = json_decode($value, true);
397
            if ($decodedString !== null) {
398
                $result[$key] = $decodedString;
399
            }
400
        }
401
402
        return $result;
403
    }
404
405
    public function setExportConfigs($data)
406
    {
407
        foreach ($data as $config) {
408
            unset($config['id']);
409
            foreach ($config as $key => $configValue) {
410
                /** @var \Shopware\CustomModels\Connect\Config $model */
411
                $model = $this->getConfigRepository()->findOneBy([
412
                    'name' => $key,
413
                    'shopId' => null,
414
                    'groupName' => 'export'
415
                ]);
416
                if (is_null($model)) {
417
                    $model = new ConfigModel();
418
                    $model->setName($key);
419
                    $model->setGroupName('export');
420
                    $model->setShopId(null);
421
                }
422
423
                if (is_array($configValue)) {
424
                    $model->setValue(json_encode($configValue));
425
                } else {
426
                    $model->setValue($configValue);
427
                }
428
429
                $this->manager->persist($model);
430
431
                if ($key === 'autoUpdateProducts') {
432
                    if ($configValue == self::UPDATE_CRON_JOB) {
433
                        $this->activateConnectCronJob('ShopwareConnectUpdateProducts', 1);
434
                    } else {
435
                        $this->activateConnectCronJob('ShopwareConnectUpdateProducts', 0);
436
                    }
437
                }
438
                if ($key === 'useTriggers' && $this->hasTriggerConfigChanged($configValue)) {
439
                    $this->processTriggerChange($configValue);
440
                }
441
            }
442
        }
443
444
        $this->manager->flush();
445
    }
446
447
    /**
448
     * @param string $configValue
449
     */
450
    private function processTriggerChange($configValue)
451
    {
452
        $triggerService = $this->getTriggerService();
453
        if ($configValue == '1') {
454
            $triggerService->activateTriggers();
455
        } else {
456
            $triggerService->deactivateTriggers();
457
        }
458
    }
459
460
    /**
461
     * @return \ShopwarePlugins\Connect\Components\TriggerService
462
     */
463
    private function getTriggerService()
464
    {
465
        if (!$this->triggerService) {
466
            $this->triggerService = new \ShopwarePlugins\Connect\Components\TriggerService(Shopware()->Models()->getConnection());
467
        }
468
469
        return $this->triggerService;
470
    }
471
472
    /**
473
     * Stores units mapping
474
     * data into database.
475
     * @param $units
476
     */
477
    public function setUnitsMapping($units)
478
    {
479
        foreach ($units as $unit) {
480
            /** @var \Shopware\CustomModels\Connect\Config $model */
481
            $model = $this->getConfigRepository()->findOneBy([
482
                'name' => $unit['connectUnit'],
483
                'shopId' => null,
484
                'groupName' => 'units'
485
            ]);
486
487
            if (!$model) {
488
                continue;
489
            }
490
491
            $model->setValue($unit['shopwareUnitKey']);
492
            $this->manager->persist($model);
493
        }
494
495
        $this->manager->flush();
496
    }
497
498
    /**
499
     * Returns units mapping from Connect config table
500
     *
501
     * @return array
502
     */
503
    public function getUnitsMappings()
504
    {
505
        $query = "SELECT `name`, `value` FROM s_plugin_connect_config
506
        WHERE `shopId` IS NULL AND `groupName` = 'units'";
507
508
        return Shopware()->Db()->fetchPairs($query);
509
    }
510
511
    /**
512
     * Compare given export price configuration
513
     * and current export price configuration
514
     * @param array $config
515
     * @return bool
516
     */
517
    public function compareExportConfiguration($config)
518
    {
519
        $currentConfig = $this->getExportConfig();
520
        if ($currentConfig['priceGroupForPriceExport'] != $config['priceGroupForPriceExport']) {
521
            return true;
522
        } elseif ($currentConfig['priceFieldForPriceExport'] != $config['priceFieldForPriceExport']) {
523
            return true;
524
        } elseif ($currentConfig['priceGroupForPurchasePriceExport'] != $config['priceGroupForPurchasePriceExport']) {
525
            return true;
526
        } elseif ($currentConfig['priceFieldForPurchasePriceExport'] != $config['priceFieldForPurchasePriceExport']) {
527
            return true;
528
        } elseif ($currentConfig['exportPriceMode'] != $config['exportPriceMode']) {
529
            return true;
530
        }
531
532
        return false;
533
    }
534
535
    /**
536
     * Compare given Trigger configuration
537
     * and current Trigger configuration
538
     * @param string $configValue
539
     * @return bool
540
     */
541
    private function hasTriggerConfigChanged($configValue)
542
    {
543
        $currentConfig = $this->getExportConfig();
544
        if (isset($currentConfig['useTriggers']) && $currentConfig['useTriggers'] != $configValue) {
545
            return true;
546
        }
547
548
        return false;
549
    }
550
551
    /**
552
     * @param $priceExportMode
553
     * @param $customerGroupKey
554
     * @return array
555
     */
556
    public function collectExportPrice($priceExportMode, $customerGroupKey)
557
    {
558
        $exportConfigArray = $this->getExportConfig();
559
        $postfix = 'ForPriceExport';
560
561
        if ($priceExportMode == 'purchasePrice') {
562
            $postfix = 'ForPurchasePriceExport';
563
        }
564
565
        $group = 'priceGroup' . $postfix;
566
        $price = 'priceField' . $postfix;
567
568
        $allowGroup = isset($exportConfigArray[$group]) && $exportConfigArray[$group] == $customerGroupKey;
569
570
        $customerGroup = $this->getCustomerGroupRepository()->findOneBy(['key' => $customerGroupKey]);
571
572
        $productCount = $this->getPriceGateway()->countProducts($customerGroup);
573
        $priceConfiguredProducts = $this->getPriceGateway()->countProductsWithConfiguredPrice($customerGroup, 'price');
574
        $basePriceConfiguredProducts = $this->getPriceGateway()->countProductsWithConfiguredPrice($customerGroup, 'baseprice');
575
        $pseudoPriceConfiguredProducts = $this->getPriceGateway()->countProductsWithConfiguredPrice($customerGroup, 'pseudoprice');
576
577
        return [
578
            'price' => $allowGroup && $exportConfigArray[$price] == 'price' ? true : false,
579
            'priceAvailable' => false,
580
            'priceConfiguredProducts' => $priceConfiguredProducts,
581
            'basePrice' =>$allowGroup && $exportConfigArray[$price] == 'basePrice' ? true : false,
582
            'basePriceAvailable' => false,
583
            'basePriceConfiguredProducts' => $basePriceConfiguredProducts,
584
            'pseudoPrice' =>$allowGroup && $exportConfigArray[$price] == 'pseudoPrice' ? true : false,
585
            'pseudoPriceAvailable' => false,
586
            'pseudoPriceConfiguredProducts' => $pseudoPriceConfiguredProducts,
587
            'productCount' => $productCount
588
        ];
589
    }
590
591
    /**
592
     * Returns config entity by value
593
     * @param $value
594
     * @return \Shopware\CustomModels\Connect\Config
595
     */
596
    public function getConfigByValue($value)
597
    {
598
        $model = $this->getConfigRepository()->findOneBy(['value' => $value, 'groupName' => 'units']);
599
600
        return $model;
601
    }
602
603
    /**
604
     * Saves array with marketplace settings to config table
605
     *
606
     * @param MarketplaceSettings $settings
607
     */
608
    public function setMarketplaceSettings(MarketplaceSettings $settings)
609
    {
610
        $settings = (array) $settings;
611
        foreach ($settings as $settingName => $settingValue) {
612
            $this->setConfig($settingName, $settingValue, null, 'marketplace');
613
        }
614
    }
615
616
    public function getMarketplaceUrl()
617
    {
618
        if ($this->getConfig('marketplaceNetworkUrl')) {
619
            return $this->getConfig('marketplaceNetworkUrl');
620
        }
621
622
        return self::MARKETPLACE_URL;
623
    }
624
625
    /**
626
     * @return int
627
     */
628 View Code Duplication
    public function getDefaultShopId()
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...
629
    {
630
        $builder = $this->manager->getConnection()->createQueryBuilder();
631
        $builder->select('cs.id')
632
            ->from('s_core_shops', 'cs')
633
            ->where('cs.default = :default')
634
            ->setParameter('default', true);
635
636
        return (int) $builder->execute()->fetchColumn();
637
    }
638
639
    /**
640
     * @return \Shopware\Models\Category\Category
641
     */
642 View Code Duplication
    public function getDefaultShopCategory()
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...
643
    {
644
        $builder = $this->manager->getConnection()->createQueryBuilder();
645
        $builder->select('cs.category_id')
646
            ->from('s_core_shops', 'cs')
647
            ->where('cs.default = :default')
648
            ->setParameter('default', true);
649
650
        $categoryId = (int) $builder->execute()->fetchColumn();
651
652
        return $this->manager->find('Shopware\Models\Category\Category', $categoryId);
653
    }
654
655
    /**
656
     * @return \Shopware\Components\Model\ModelRepository|\Shopware\CustomModels\Connect\ConfigRepository
657
     */
658
    private function getConfigRepository()
659
    {
660
        if (!$this->repository) {
661
            $this->repository = $this->manager->getRepository('Shopware\CustomModels\Connect\Config');
662
        }
663
664
        return $this->repository;
665
    }
666
667
    /**
668
     * @return \Shopware\Components\Model\ModelRepository|\Shopware\Models\Shop\Shop
669
     */
670
    private function getShopRepository()
671
    {
672
        if (!$this->shopRepository) {
673
            $this->shopRepository = $this->manager->getRepository('Shopware\Models\Shop\Shop');
674
        }
675
676
        return $this->shopRepository;
677
    }
678
679
    private function getPriceGateway()
680
    {
681
        if (!$this->priceGateway) {
682
            $this->priceGateway = new \ShopwarePlugins\Connect\Components\PriceGateway(
683
                Shopware()->Db()
684
            );
685
        }
686
687
        return $this->priceGateway;
688
    }
689
690
    /**
691
     * @return \Shopware\Components\Model\ModelRepository
692
     */
693
    private function getCustomerGroupRepository()
694
    {
695
        if (!$this->customerGroupRepository) {
696
            $this->customerGroupRepository = $this->manager->getRepository('Shopware\Models\Customer\Group');
697
        }
698
699
        return $this->customerGroupRepository;
700
    }
701
702
    /**
703
     * @return \Shopware\Connect\Gateway\PDO
704
     */
705 View Code Duplication
    private function getConnectPDOGateway()
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...
706
    {
707
        if (!$this->connectGateway) {
708
            $this->connectGateway = new PDO(Shopware()->Db()->getConnection());
709
        }
710
711
        return $this->connectGateway;
712
    }
713
714
    /**
715
     * @param string $action
716
     * @param int $active
717
     */
718
    private function activateConnectCronJob($action, $active)
719
    {
720
        $this->manager->getConnection()->executeUpdate('UPDATE `s_crontab` SET `active` = ? WHERE `action` = ? OR `action` = ?',
721
            [$active, $action, "Shopware_CronJob_$action"]);
722
    }
723
}
724