Completed
Pull Request — master (#333)
by Simon
04:47
created

Config::getExportConfig()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 16
Code Lines 8

Duplication

Lines 6
Ratio 37.5 %

Importance

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