Completed
Pull Request — master (#417)
by Jonas
03:09
created

Config::getUnitsMappings()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 7
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 3
nc 1
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
     * @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
        }
367
368
        $this->manager->flush();
369
    }
370
371
    /**
372
     * Helper function which returns export configuration.
373
     *
374
     * @return array
375
     */
376
    public function getExportConfig()
377
    {
378
        $query = "SELECT `name`, `value` FROM s_plugin_connect_config
379
        WHERE `shopId` IS NULL AND `groupName` = 'export'";
380
381
        $result = Shopware()->Db()->fetchPairs($query);
382
383
        foreach ($result as $key => $value) {
384
            $decodedString = json_decode($value, true);
385
            if ($decodedString !== null) {
386
                $result[$key] = $decodedString;
387
            }
388
        }
389
390
        return $result;
391
    }
392
393 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...
394
    {
395
        foreach ($data as $config) {
396
            unset($config['id']);
397
            foreach ($config as $key => $configValue) {
398
                /** @var \Shopware\CustomModels\Connect\Config $model */
399
                $model = $this->getConfigRepository()->findOneBy([
400
                    'name' => $key,
401
                    'shopId' => null,
402
                    'groupName' => 'export'
403
                ]);
404
                if (is_null($model)) {
405
                    $model = new ConfigModel();
406
                    $model->setName($key);
407
                    $model->setGroupName('export');
408
                    $model->setShopId(null);
409
                }
410
411
                if (is_array($configValue)) {
412
                    $model->setValue(json_encode($configValue));
413
                } else {
414
                    $model->setValue($configValue);
415
                }
416
417
                $this->manager->persist($model);
418
            }
419
        }
420
421
        $this->manager->flush();
422
    }
423
424
    /**
425
     * Stores units mapping
426
     * data into database.
427
     * @param $units
428
     */
429
    public function setUnitsMapping($units)
430
    {
431
        foreach ($units as $unit) {
432
            /** @var \Shopware\CustomModels\Connect\Config $model */
433
            $model = $this->getConfigRepository()->findOneBy([
434
                'name' => $unit['connectUnit'],
435
                'shopId' => null,
436
                'groupName' => 'units'
437
            ]);
438
439
            if (!$model) {
440
                continue;
441
            }
442
443
            $model->setValue($unit['shopwareUnitKey']);
444
            $this->manager->persist($model);
445
        }
446
447
        $this->manager->flush();
448
    }
449
450
    /**
451
     * Returns units mapping from Connect config table
452
     *
453
     * @return array
454
     */
455
    public function getUnitsMappings()
456
    {
457
        $query = "SELECT `name`, `value` FROM s_plugin_connect_config
458
        WHERE `shopId` IS NULL AND `groupName` = 'units'";
459
460
        return Shopware()->Db()->fetchPairs($query);
461
    }
462
463
    /**
464
     * Compare given export price configuration
465
     * and current export price configuration
466
     * @param array $config
467
     * @return bool
468
     */
469
    public function compareExportConfiguration($config)
470
    {
471
        $currentConfig = $this->getExportConfig();
472
        if ($currentConfig['priceGroupForPriceExport'] != $config['priceGroupForPriceExport']) {
473
            return true;
474
        } elseif ($currentConfig['priceFieldForPriceExport'] != $config['priceFieldForPriceExport']) {
475
            return true;
476
        } elseif ($currentConfig['priceGroupForPurchasePriceExport'] != $config['priceGroupForPurchasePriceExport']) {
477
            return true;
478
        } elseif ($currentConfig['priceFieldForPurchasePriceExport'] != $config['priceFieldForPurchasePriceExport']) {
479
            return true;
480
        } elseif ($currentConfig['exportPriceMode'] != $config['exportPriceMode']) {
481
            return true;
482
        }
483
484
        return false;
485
    }
486
487
    /**
488
     * @param $priceExportMode
489
     * @param $customerGroupKey
490
     * @return array
491
     */
492
    public function collectExportPrice($priceExportMode, $customerGroupKey)
493
    {
494
        $exportConfigArray = $this->getExportConfig();
495
        $postfix = 'ForPriceExport';
496
497
        if ($priceExportMode == 'purchasePrice') {
498
            $postfix = 'ForPurchasePriceExport';
499
        }
500
501
        $group = 'priceGroup' . $postfix;
502
        $price = 'priceField' . $postfix;
503
504
        $allowGroup = isset($exportConfigArray[$group]) && $exportConfigArray[$group] == $customerGroupKey;
505
506
        $customerGroup = $this->getCustomerGroupRepository()->findOneBy(['key' => $customerGroupKey]);
507
508
        $productCount = $this->getPriceGateway()->countProducts($customerGroup);
509
        $priceConfiguredProducts = $this->getPriceGateway()->countProductsWithConfiguredPrice($customerGroup, 'price');
510
        $basePriceConfiguredProducts = $this->getPriceGateway()->countProductsWithConfiguredPrice($customerGroup, 'baseprice');
511
        $pseudoPriceConfiguredProducts = $this->getPriceGateway()->countProductsWithConfiguredPrice($customerGroup, 'pseudoprice');
512
513
        return [
514
            'price' => $allowGroup && $exportConfigArray[$price] == 'price' ? true : false,
515
            'priceAvailable' => false,
516
            'priceConfiguredProducts' => $priceConfiguredProducts,
517
            'basePrice' =>$allowGroup && $exportConfigArray[$price] == 'basePrice' ? true : false,
518
            'basePriceAvailable' => false,
519
            'basePriceConfiguredProducts' => $basePriceConfiguredProducts,
520
            'pseudoPrice' =>$allowGroup && $exportConfigArray[$price] == 'pseudoPrice' ? true : false,
521
            'pseudoPriceAvailable' => false,
522
            'pseudoPriceConfiguredProducts' => $pseudoPriceConfiguredProducts,
523
            'productCount' => $productCount
524
        ];
525
    }
526
527
    /**
528
     * Returns config entity by value
529
     * @param $value
530
     * @return \Shopware\CustomModels\Connect\Config
531
     */
532
    public function getConfigByValue($value)
533
    {
534
        $model = $this->getConfigRepository()->findOneBy(['value' => $value, 'groupName' => 'units']);
535
536
        return $model;
537
    }
538
539
    /**
540
     * Saves array with marketplace settings to config table
541
     *
542
     * @param MarketplaceSettings $settings
543
     */
544
    public function setMarketplaceSettings(MarketplaceSettings $settings)
545
    {
546
        $settings = (array) $settings;
547
        foreach ($settings as $settingName => $settingValue) {
548
            $this->setConfig($settingName, $settingValue, null, 'marketplace');
549
        }
550
    }
551
552
    public function getMarketplaceUrl()
553
    {
554
        if ($this->getConfig('marketplaceNetworkUrl')) {
555
            return $this->getConfig('marketplaceNetworkUrl');
556
        }
557
558
        return self::MARKETPLACE_URL;
559
    }
560
561
    /**
562
     * @return int
563
     */
564 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...
565
    {
566
        $builder = $this->manager->getConnection()->createQueryBuilder();
567
        $builder->select('cs.id')
568
            ->from('s_core_shops', 'cs')
569
            ->where('cs.default = :default')
570
            ->setParameter('default', true);
571
572
        return (int) $builder->execute()->fetchColumn();
573
    }
574
575
    /**
576
     * @return \Shopware\Models\Category\Category
577
     */
578 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...
579
    {
580
        $builder = $this->manager->getConnection()->createQueryBuilder();
581
        $builder->select('cs.category_id')
582
            ->from('s_core_shops', 'cs')
583
            ->where('cs.default = :default')
584
            ->setParameter('default', true);
585
586
        $categoryId = (int) $builder->execute()->fetchColumn();
587
588
        return $this->manager->find('Shopware\Models\Category\Category', $categoryId);
589
    }
590
591
    /**
592
     * @return \Shopware\Components\Model\ModelRepository|\Shopware\CustomModels\Connect\ConfigRepository
593
     */
594
    private function getConfigRepository()
595
    {
596
        if (!$this->repository) {
597
            $this->repository = $this->manager->getRepository('Shopware\CustomModels\Connect\Config');
598
        }
599
600
        return $this->repository;
601
    }
602
603
    /**
604
     * @return \Shopware\Components\Model\ModelRepository|\Shopware\Models\Shop\Shop
605
     */
606
    private function getShopRepository()
607
    {
608
        if (!$this->shopRepository) {
609
            $this->shopRepository = $this->manager->getRepository('Shopware\Models\Shop\Shop');
610
        }
611
612
        return $this->shopRepository;
613
    }
614
615
    private function getPriceGateway()
616
    {
617
        if (!$this->priceGateway) {
618
            $this->priceGateway = new \ShopwarePlugins\Connect\Components\PriceGateway(
619
                Shopware()->Db()
620
            );
621
        }
622
623
        return $this->priceGateway;
624
    }
625
626
    /**
627
     * @return \Shopware\Components\Model\ModelRepository
628
     */
629
    private function getCustomerGroupRepository()
630
    {
631
        if (!$this->customerGroupRepository) {
632
            $this->customerGroupRepository = $this->manager->getRepository('Shopware\Models\Customer\Group');
633
        }
634
635
        return $this->customerGroupRepository;
636
    }
637
638
    /**
639
     * @return \Shopware\Connect\Gateway\PDO
640
     */
641 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...
642
    {
643
        if (!$this->connectGateway) {
644
            $this->connectGateway = new PDO(Shopware()->Db()->getConnection());
645
        }
646
647
        return $this->connectGateway;
648
    }
649
}
650