Completed
Pull Request — master (#418)
by Jonas
02:55
created

Config::collectExportPrice()   F

Complexity

Conditions 9
Paths 256

Size

Total Lines 34
Code Lines 24

Duplication

Lines 0
Ratio 0 %

Importance

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