calculateFinishTimeAction()   A
last analyzed

Complexity

Conditions 3
Paths 4

Size

Total Lines 24

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
nc 4
nop 0
dl 0
loc 24
rs 9.536
c 0
b 0
f 0
1
<?php
2
/**
3
 * (c) shopware AG <[email protected]>
4
 * For the full copyright and license information, please view the LICENSE
5
 * file that was distributed with this source code.
6
 */
7
use Shopware\Connect\Units;
8
use ShopwarePlugins\Connect\Components\ConnectExport;
9
use ShopwarePlugins\Connect\Components\Validator\ProductAttributesValidator\ProductsAttributesValidator;
10
use ShopwarePlugins\Connect\Components\Utils\UnitMapper;
11
use ShopwarePlugins\Connect\Components\Logger;
12
use ShopwarePlugins\Connect\Components\SnHttpClient;
13
use ShopwarePlugins\Connect\Components\ErrorHandler;
14
use Shopware\Connect\Gateway\ChangeGateway;
15
use ShopwarePlugins\Connect\Components\ProductQuery\BaseProductQuery;
16
use ShopwarePlugins\Connect\Components\ConfigFactory;
17
use Shopware\Models\Plugin\Plugin;
18
19
/**
20
 * @category  Shopware
21
 * @package   Shopware\Plugins\SwagConnect
22
 * @copyright Copyright (c) 2013, shopware AG (http://www.shopware.de)
23
 */
24
class Shopware_Controllers_Backend_ConnectConfig extends Shopware_Controllers_Backend_ExtJs
25
{
26
    /** @var \ShopwarePlugins\Connect\Components\Config */
27
    private $configComponent;
28
29
    /**
30
     * @var \ShopwarePlugins\Connect\Components\ConnectFactory
31
     */
32
    private $factory;
33
34
    /**
35
     * @var \ShopwarePlugins\Connect\Components\Utils\UnitMapper
36
     */
37
    private $unitMapper;
38
39
    /**
40
     * @var \ShopwarePlugins\Connect\Components\Logger
41
     */
42
    private $logger;
43
44
    /**
45
     * @var \Shopware\Components\Model\ModelRepository
46
     */
47
    private $customerGroupRepository;
48
49
    /**
50
     * @var \ShopwarePlugins\Connect\Components\PriceGateway
51
     */
52
    private $priceGateway;
53
54
    /**
55
     * @var \ShopwarePlugins\Connect\Components\SnHttpClient
56
     */
57
    private $snHttpClient;
58
59
    /**
60
     * The getGeneralAction function is an ExtJs event listener method of the
61
     * connect module. The function is used to load store
62
     * required in the general config form.
63
     * @return string
64
     */
65
    public function getGeneralAction()
66
    {
67
        $generalConfig = $this->getConfigComponent()->getGeneralConfig();
68
69
        $this->View()->assign([
70
            'success' => true,
71
            'data' => $generalConfig
72
        ]);
73
    }
74
75
    /**
76
     * The saveGeneralAction function is an ExtJs event listener method of the
77
     * connect module. The function is used to save store data.
78
     * @return string
79
     */
80 View Code Duplication
    public function saveGeneralAction()
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...
81
    {
82
        try {
83
            $data = $this->Request()->getParam('data');
84
            unset($data['id']);
85
            $this->getConfigComponent()->setGeneralConfigs($data);
86
87
            $this->View()->assign([
88
                'success' => true
89
            ]);
90
        } catch (\Exception $e) {
91
            $this->View()->assign([
92
                'success' => false,
93
                'message' => $e->getMessage()
94
            ]);
95
        }
96
    }
97
98
    public function changeLoggingAction()
99
    {
100
        try {
101
            $enableLogging = $this->Request()->getParam('enableLogging');
102
            $this->getConfigComponent()->setConfig('logRequest', $enableLogging, null, 'general');
103
104
            $this->View()->assign([
105
                'success' => true
106
            ]);
107
        } catch (\Exception $e) {
108
            $this->View()->assign([
109
                'success' => false,
110
            ]);
111
        }
112
    }
113
114
    public function getLoggingEnabledAction()
115
    {
116
        $this->View()->assign([
117
            'success' => true,
118
            'enableLogging' => $this->getConfigComponent()->getConfig('logRequest', 0),
119
        ]);
120
    }
121
122
    /**
123
     * The getImportAction function is an ExtJs event listener method of the
124
     * connect module. The function is used to load store
125
     * required in the import config form.
126
     * @return string
127
     */
128
    public function getImportAction()
129
    {
130
        $importConfigArray = $this->getConfigComponent()->getImportConfig();
131
132
        $this->View()->assign(
133
            [
134
                'success' => true,
135
                'data' => $importConfigArray
136
            ]
137
        );
138
    }
139
140
    /**
141
     * The saveImportAction function is an ExtJs event listener method of the
142
     * connect module. The function is used to save store data.
143
     * @return string
144
     */
145
    public function saveImportAction()
146
    {
147
        $data = $this->Request()->getParam('data');
148
        $data = !isset($data[0]) ? [$data] : $data;
149
150
        $this->getConfigComponent()->setImportConfigs($data);
151
152
        $this->View()->assign(
153
            [
154
                'success' => true
155
            ]
156
        );
157
    }
158
159
    /**
160
     * The getExportAction function is an ExtJs event listener method of the
161
     * connect module. The function is used to load store
162
     * required in the export config form.
163
     * @return string
164
     */
165
    public function getExportAction()
166
    {
167
        $exportConfigArray = $this->getConfigComponent()->getExportConfig();
168
        if (!array_key_exists('exportPriceMode', $exportConfigArray) || $this->isPriceTypeReset()) {
169
            $exportConfigArray['exportPriceMode'] = [];
170
        }
171
172
173
        //Resets the exportPriceMode
174
        if ($this->getSDK()->getPriceType() === \Shopware\Connect\SDK::PRICE_TYPE_NONE) {
175
            $exportConfigArray['exportPriceMode'] = [];
176
        }
177
178
        if (!array_key_exists(BaseProductQuery::LONG_DESCRIPTION_FIELD, $exportConfigArray)) {
179
            $exportConfigArray[BaseProductQuery::LONG_DESCRIPTION_FIELD] = true;
180
        }
181
182
        $this->View()->assign(
183
            [
184
                'success' => true,
185
                'data' => $exportConfigArray
186
            ]
187
        );
188
    }
189
190
    /**
191
     * @return bool
192
     */
193
    public function isPriceTypeReset()
194
    {
195
        return $this->getSDK()->getPriceType() === \Shopware\Connect\SDK::PRICE_TYPE_NONE;
196
    }
197
198
    /**
199
     * ExtJS uses this action to check is price mapping allowed.
200
     * If there is at least one exported product to connect,
201
     * price mapping cannot be changed.
202
     */
203
    public function isPricingMappingAllowedAction()
204
    {
205
        $isPriceModeEnabled = false;
206
        $isPurchasePriceModeEnabled = false;
207
        $isPricingMappingAllowed = $this->isPriceTypeReset();
208
209
        if ($isPricingMappingAllowed) {
210
            $this->View()->assign(
211
                [
212
                    'success' => true,
213
                    'isPricingMappingAllowed' => $isPricingMappingAllowed,
214
                    'isPriceModeEnabled' => true,
215
                    'isPurchasePriceModeEnabled' => true,
216
                ]
217
            );
218
219
            return;
220
        }
221
222
        if ($this->getSDK()->getPriceType() === \Shopware\Connect\SDK::PRICE_TYPE_BOTH
223
        || $this->getSDK()->getPriceType() === \Shopware\Connect\SDK::PRICE_TYPE_RETAIL) {
224
            $isPriceModeEnabled = true;
225
        }
226
227
        if ($this->getSDK()->getPriceType() === \Shopware\Connect\SDK::PRICE_TYPE_BOTH
228
        || $this->getSDK()->getPriceType() === \Shopware\Connect\SDK::PRICE_TYPE_PURCHASE) {
229
            $isPurchasePriceModeEnabled = true;
230
        }
231
232
        $this->View()->assign(
233
            [
234
                'success' => true,
235
                'isPricingMappingAllowed' => $isPricingMappingAllowed,
236
                'isPriceModeEnabled' => $isPriceModeEnabled,
237
                'isPurchasePriceModeEnabled' => $isPurchasePriceModeEnabled,
238
            ]
239
        );
240
    }
241
242
    /**
243
     * The saveExportAction function is an ExtJs event listener method of the
244
     * connect module. The function is used to save store data.
245
     * @return string
246
     */
247
    public function saveExportAction()
248
    {
249
        $data = $this->Request()->getParam('data');
250
        $exportPrice = in_array('price', $data['exportPriceMode']);
251
        $exportPurchasePrice = in_array('purchasePrice', $data['exportPriceMode']);
252
253
        $isModified = $this->getConfigComponent()->compareExportConfiguration($data);
254
        $isPriceTypeReset = $this->isPriceTypeReset();
255
256
        if ($isModified === false && $this->getSDK()->getPriceType() !== \Shopware\Connect\SDK::PRICE_TYPE_NONE) {
257
            $data = !isset($data[0]) ? [$data] : $data;
258
            $this->getConfigComponent()->setExportConfigs($data);
259
            $this->View()->assign(
260
                [
261
                    'success' => true,
262
                ]
263
            );
264
265
            return;
266
        }
267
268
        if ($exportPrice && $exportPurchasePrice) {
269
            $priceType = \Shopware\Connect\SDK::PRICE_TYPE_BOTH;
270
        } elseif ($exportPrice) {
271
            $priceType = \Shopware\Connect\SDK::PRICE_TYPE_RETAIL;
272
            unset($data['priceFieldForPurchasePriceExport']);
273
            unset($data['priceGroupForPurchasePriceExport']);
274
        } elseif ($exportPurchasePrice) {
275
            $priceType = \Shopware\Connect\SDK::PRICE_TYPE_PURCHASE;
276
            unset($data['priceFieldForPriceExport']);
277
            unset($data['priceGroupForPriceExport']);
278
        } else {
279
            $this->View()->assign([
280
                'success' => false,
281
                'message' => Shopware()->Snippets()->getNamespace('backend/connect/view/main')->get(
282
                    'config/export/priceFieldIsNotSupported',
283
                    'Price field is not maintained. Some of the products have price = 0',
284
                    true
285
                )
286
            ]);
287
288
            return;
289
        }
290
291
        if ($priceType == \Shopware\Connect\SDK::PRICE_TYPE_BOTH
292
            && $data['priceFieldForPurchasePriceExport'] == $data['priceFieldForPriceExport']
293
            && $data['priceGroupForPurchasePriceExport'] == $data['priceGroupForPriceExport']
294
        ) {
295
            $this->View()->assign([
296
                'success' => false,
297
                'message' => Shopware()->Snippets()->getNamespace('backend/connect/view/main')->get(
298
                    'config/export/error/same_price_fields',
299
                    'Endkunden-VK und Listenverkaufspreis müssen an verschiedene Felder angeschlossen sein',
300
                    true
301
                )
302
            ]);
303
304
            return;
305
        }
306
307
        $detailPurchasePrice = method_exists('Shopware\Models\Article\Detail', 'setPurchasePrice');
308
        if ($exportPurchasePrice && $detailPurchasePrice) {
309
            $data['priceFieldForPurchasePriceExport'] = 'detailPurchasePrice';
310
        }
311
312 View Code Duplication
        if ($priceType == \Shopware\Connect\SDK::PRICE_TYPE_BOTH
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...
313
            || $priceType == \Shopware\Connect\SDK::PRICE_TYPE_RETAIL
314
        ) {
315
            /** @var \Shopware\Models\Customer\Group $groupPrice */
316
            $groupPrice = $this->getCustomerGroupRepository()->findOneBy(['key' => $data['priceGroupForPriceExport']]);
317
            if (!$groupPrice) {
318
                $this->View()->assign([
319
                    'success' => false,
320
                    'message' => Shopware()->Snippets()->getNamespace('backend/connect/view/main')->get(
321
                        'config/export/invalid_customer_group',
322
                        'Ungültige Kundengruppe',
323
                        true
324
                    )
325
                ]);
326
327
                return;
328
            }
329
330
            if ($this->getPriceGateway()->countProductsWithConfiguredPrice($groupPrice, $data['priceFieldForPriceExport']) === 0) {
331
                $this->View()->assign([
332
                    'success' => false,
333
                    'message' => Shopware()->Snippets()->getNamespace('backend/connect/view/main')->get(
334
                        'config/export/priceFieldIsNotSupported',
335
                        'Price field is not maintained. Some of the products have price = 0',
336
                        true
337
                    )
338
                ]);
339
340
                return;
341
            }
342
        }
343
344 View Code Duplication
        if ($priceType == \Shopware\Connect\SDK::PRICE_TYPE_BOTH
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...
345
            || $priceType == \Shopware\Connect\SDK::PRICE_TYPE_PURCHASE
346
        ) {
347
            /** @var \Shopware\Models\Customer\Group $groupPurchasePrice */
348
            $groupPurchasePrice = $this->getCustomerGroupRepository()->findOneBy([
349
                'key' => $data['priceGroupForPurchasePriceExport']
350
            ]);
351
            if (!$groupPurchasePrice && !$detailPurchasePrice) {
352
                $this->View()->assign([
353
                    'success' => false,
354
                    'message' => Shopware()->Snippets()->getNamespace('backend/connect/view/main')->get(
355
                        'config/export/invalid_customer_group',
356
                        'Ungültige Kundengruppe',
357
                        true
358
                    )
359
                ]);
360
361
                return;
362
            }
363
364
            if ($this->getPriceGateway()->countProductsWithConfiguredPrice($groupPurchasePrice, $data['priceFieldForPurchasePriceExport']) === 0) {
365
                $this->View()->assign([
366
                    'success' => false,
367
                    'message' => Shopware()->Snippets()->getNamespace('backend/connect/view/main')->get(
368
                        'config/export/priceFieldIsNotSupported',
369
                        'Price field is not maintained. Some of the products have price = 0',
370
                        true
371
                    )
372
                ]);
373
374
                return;
375
            }
376
        }
377
378
        $connectExport = $this->getConnectExport();
379
380
        if ($isPriceTypeReset) {
381
            //removes all hashes from from sw_connect_product
382
            //and resets all item status
383
            $connectExport->clearConnectItems();
384
        }
385
386
        try {
387
            $data = !isset($data[0]) ? [$data] : $data;
388
            $response = $this->getSnHttpClient()->sendRequestToConnect(
389
                'account/settings',
390
                ['priceType' => $priceType]
391
            );
392
393
            $responseBody = json_decode($response->getBody());
394
            if (!$responseBody->success) {
395
                throw new \RuntimeException($responseBody->message);
396
            }
397
398
            $this->getSDK()->verifySdk();
399
            $this->getConfigComponent()->setExportConfigs($data);
400
401
            //todo@sb: check this. Not possible to export all products at the same request.
402
            $ids = $connectExport->getExportArticlesIds();
403
            $sourceIds = $this->getHelper()->getArticleSourceIds($ids);
404
            $errors = $connectExport->export($sourceIds);
405
        } catch (\RuntimeException $e) {
406
            $this->getLogger()->write(true, 'Save export settings', $e->getMessage() . $e->getTraceAsString());
407
            $this->View()->assign([
408
                    'success' => false,
409
                    'message' => $e->getMessage()
410
                ]);
411
412
            return;
413
        }
414
415
        if (!empty($errors)) {
416
            $msg = null;
417
            foreach ($errors as $type) {
418
                $msg .= implode("<br>\n", $type);
419
            }
420
421
            $this->View()->assign([
422
                    'success' => false,
423
                    'message' => $msg
424
                ]);
425
426
            return;
427
        }
428
429
        $this->View()->assign(
430
            [
431
                'success' => true
432
            ]
433
        );
434
    }
435
436
    /**
437
     * @return ConnectExport
438
     */
439 View Code Duplication
    public function getConnectExport()
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...
440
    {
441
        return new ConnectExport(
442
            $this->getHelper(),
443
            $this->getSDK(),
444
            $this->getModelManager(),
445
            new ProductsAttributesValidator(),
446
            $this->getConfigComponent(),
447
            new ErrorHandler(),
448
            $this->container->get('events')
449
        );
450
    }
451
452
    /**
453
     * It will make a call to SocialNetwork to reset the price type,
454
     * if this call return success true, then it will reset the export settings locally
455
     *
456
     * @return void
457
     */
458
    public function resetPriceTypeAction()
459
    {
460
        $response = $this->getSnHttpClient()->sendRequestToConnect('account/reset/price-type');
461
        $responseBody = json_decode($response->getBody());
462
463 View Code Duplication
        if (!$responseBody->success) {
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...
464
            $this->View()->assign([
465
                'success' => false,
466
                'message' => $responseBody->message
467
            ]);
468
469
            return;
470
        }
471
472
        try {
473
            $this->resetExportedProducts();
474
        } catch (\Exception $e) {
475
            $this->View()->assign([
476
                'success' => false,
477
                'message' => $responseBody->message
478
            ]);
479
480
            return;
481
        }
482
483
        $this->View()->assign([
484
            'success' => true,
485
        ]);
486
    }
487
488
    /**
489
     * It will make a call to SocialNetwork to reset the exchange settings,
490
     * if this call return success true, then it will reset the export settings locally
491
     *
492
     * @return void
493
     */
494
    public function resetExchangeSettingsAction()
495
    {
496
        $response = $this->getSnHttpClient()->sendRequestToConnect('account/reset/exchange-settings');
497
498
        $responseBody = json_decode($response->getBody());
499
500 View Code Duplication
        if (!$responseBody->success) {
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...
501
            $this->View()->assign([
502
                'success' => false,
503
                'message' => $responseBody->message
504
            ]);
505
506
            return;
507
        }
508
509
        try {
510
            $this->resetExportedProducts();
511
512
            //remove the existing api key
513
            $this->getConfigComponent()->setGeneralConfigs(['apiKey' => '']);
514
515
            //recreate the register menu
516
            $this->get('swagconnect.menu_service')->createRegisterMenu();
517
        } catch (\Exception $e) {
518
            $this->View()->assign([
519
                'success' => false,
520
                'message' => $responseBody->message
521
            ]);
522
523
            return;
524
        }
525
526
        $this->View()->assign([
527
            'success' => true,
528
        ]);
529
    }
530
531
    /**
532
     * WARNING This code remove the current product changes
533
     * This is a single call operation and its danger one
534
     */
535
    private function resetExportedProducts()
536
    {
537
        $builder = $this->getModelManager()->getConnection()->createQueryBuilder();
538
        $builder->delete('sw_connect_change')
539
            ->where('c_operation IN (:changes)')
540
            ->setParameter(
541
                'changes',
542
                [
543
                    ChangeGateway::PRODUCT_INSERT,
544
                    ChangeGateway::PRODUCT_UPDATE,
545
                    ChangeGateway::PRODUCT_DELETE,
546
                    ChangeGateway::PRODUCT_STOCK,
547
                ],
548
                \Doctrine\DBAL\Connection::PARAM_STR_ARRAY
549
            );
550
        $builder->execute();
551
552
        $itemRepo = $this->getModelManager()->getRepository('Shopware\CustomModels\Connect\Attribute');
553
        $itemRepo->resetExportedItemsStatus();
554
555
        $streamRepo = $this->getModelManager()->getRepository('Shopware\CustomModels\Connect\ProductStreamAttribute');
556
        $streamRepo->resetExportedStatus();
557
    }
558
559
    /**
560
     * @return \ShopwarePlugins\Connect\Components\Helper
561
     */
562
    public function getHelper()
563
    {
564
        if ($this->factory === null) {
565
            $this->factory = new \ShopwarePlugins\Connect\Components\ConnectFactory();
566
        }
567
568
        return $this->factory->getHelper();
569
    }
570
571
    /**
572
     * @return \Shopware\Connect\SDK
573
     */
574
    public function getSDK()
575
    {
576
        return Shopware()->Container()->get('ConnectSDK');
577
    }
578
579
    /**
580
     * @return Shopware\Components\Model\ModelManager
581
     */
582
    public function getModelManager()
583
    {
584
        return Shopware()->Models();
585
    }
586
587
    /**
588
     * The getStaticPagesAction function is an ExtJs event listener method of the
589
     * connect module. The function is used to load store
590
     * required in the general config form for static cms pages combo.
591
     * @return string
592
     */
593
    public function getStaticPagesAction()
594
    {
595
        $builder = $this->getModelManager()->createQueryBuilder();
596
        $builder->select('st.id, st.description AS name');
597
        $builder->from('Shopware\Models\Site\Site', 'st');
598
599
        $query = $builder->getQuery();
600
        $query->setFirstResult($this->Request()->getParam('start'));
601
        $query->setMaxResults($this->Request()->getParam('limit'));
602
603
        $total = Shopware()->Models()->getQueryCount($query);
604
        $data = $query->getArrayResult();
605
606
        $this->View()->assign([
607
                'success' => true,
608
                'data' => $data,
609
                'total' => $total
610
            ]);
611
    }
612
613
    /**
614
     * Helper function to get access on the Config component
615
     *
616
     * @return \ShopwarePlugins\Connect\Components\Config
617
     */
618
    private function getConfigComponent()
619
    {
620
        if ($this->configComponent === null) {
621
            $this->configComponent = ConfigFactory::getConfigInstance();
622
        }
623
624
        return $this->configComponent;
625
    }
626
627
    /**
628
     * The getUnitsAction function is an ExtJs event listener method of the
629
     * connect module. The function is used to load store
630
     * required in the units mapping.
631
     * @return string
632
     */
633
    public function getUnitsAction()
634
    {
635
        $repository = Shopware()->Models()->getRepository('Shopware\Models\Article\Unit');
636
        $units = $repository->findAll();
637
638
        $unitName = Shopware()->Snippets()->getNamespace('backend/connect/view/main')->get(
639
            'import/unit/take_over_units',
640
            'Take over unit',
641
            true
642
        );
643
644
        $unitsMappingArray[] = [
0 ignored issues
show
Coding Style Comprehensibility introduced by
$unitsMappingArray was never initialized. Although not strictly required by PHP, it is generally a good practice to add $unitsMappingArray = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
645
            'shopwareUnitName' => $unitName,
646
            'shopwareUnitKey' => UnitMapper::ADOPT_UNIT_KEY,
647
        ];
648
649
        foreach ($units as $unit) {
650
            $unitsMappingArray[] = [
651
                'shopwareUnitName' => $unit->getName(),
652
                'shopwareUnitKey' => $unit->getUnit()
653
            ];
654
        }
655
656
        $this->View()->assign(
657
            [
658
                'success' => true,
659
                'data' => $unitsMappingArray
660
            ]
661
        );
662
    }
663
664
    /**
665
     * The saveUnitsMappingAction function is an ExtJs event listener method of the
666
     * connect module. The function is used to save units store data.
667
     * @return string
668
     */
669
    public function saveUnitsMappingAction()
670
    {
671
        $data = $this->Request()->getParam('data');
672
        $data = !isset($data[0]) ? [$data] : $data;
673
674
        //prepares units for adoption
675
        $adoptUnitKeys = [];
676
        foreach ($data as $index => $unit) {
677
            if ($unit['shopwareUnitKey'] == UnitMapper::ADOPT_UNIT_KEY) {
678
                $adoptUnitKeys[] = $unit['connectUnit'];
679
                $data[$index]['shopwareUnitKey'] = $unit['connectUnit'];
680
            }
681
        }
682
683
        if (!empty($adoptUnitKeys)) {
684
            $this->getUnitMapper()->createUnits($adoptUnitKeys);
685
        }
686
687
        $this->getConfigComponent()->setUnitsMapping($data);
688
689
        // update related products
690
        $repository = Shopware()->Models()->getRepository('Shopware\Models\Article\Unit');
691
        foreach ($data as $unit) {
692
            /** @var \Shopware\Models\Article\Unit $unitModel */
693
            $unitModel = $repository->findOneBy(['unit' => $unit['shopwareUnitKey']]);
694
            if (!$unitModel) {
695
                continue;
696
            }
697
            $this->getHelper()->updateUnitInRelatedProducts($unitModel, $unit['connectUnit']);
698
        }
699
700
        $this->View()->assign(
701
            [
702
                'success' => true
703
            ]
704
        );
705
    }
706
707
    /**
708
     * The getConnectUnitsAction function is an ExtJs event listener method of the
709
     * connect module. The function is used to load store
710
     * required in the units mapping.
711
     * @return string
712
     */
713
    public function getConnectUnitsAction()
714
    {
715
        $connectUnits = new Units();
716
        $connectUnitsArray = $connectUnits->getLocalizedUnits('de');
717
        $unitsArray = [];
718
        $hideAssigned = (int) $this->Request()->getParam('hideAssignedUnits', 1);
719
720
        foreach ($this->getConfigComponent()->getUnitsMappings() as $connectUnit => $localUnit) {
721
            if ($hideAssigned == true && strlen($localUnit) > 0) {
0 ignored issues
show
Bug Best Practice introduced by
It seems like you are loosely comparing $hideAssigned of type integer to the boolean true. If you are specifically checking for non-zero, consider using something more explicit like > 0 or !== 0 instead.
Loading history...
722
                continue;
723
            }
724
            $unitsArray[] = [
725
                'connectUnit' => $connectUnit,
726
                'name' => $connectUnitsArray[$connectUnit],
727
                'shopwareUnitKey' => $localUnit
728
            ];
729
        }
730
731
        $this->View()->assign(
732
            [
733
                'success' => true,
734
                'data' => $unitsArray
735
            ]
736
        );
737
    }
738
739
    /**
740
     * Ask SocialNetwork what time is need to finish the product update
741
     */
742
    public function calculateFinishTimeAction()
743
    {
744
        $changes = $this->getConnectExport()->getChangesCount();
745
        $seconds = 0;
746
        if ($changes > 0) {
747
            $seconds = $this->getSDK()->calculateFinishTime($changes);
748
        }
749
750
        try {
751
            $this->View()->assign(
752
                [
753
                    'success' => true,
754
                    'time' => $seconds,
755
                ]
756
            );
757
        } catch (\Exception $e) {
758
            $this->View()->assign(
759
                [
760
                    'success' => false,
761
                    'message' => $e->getMessage(),
762
                ]
763
            );
764
        }
765
    }
766
767
    public function getMarketplaceAttributesAction()
768
    {
769
        try {
770
            $verified = $this->getConfigComponent()->getConfig('apiKeyVerified', false);
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $verified is correct as $this->getConfigComponen...apiKeyVerified', false) (which targets ShopwarePlugins\Connect\...nts\Config::getConfig()) seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
771
772
            if ($verified) {
773
                $marketplaceAttributes = $this->getSDK()->getMarketplaceProductAttributes();
774
775
                $attributes = [];
776
                foreach ($marketplaceAttributes as $attributeKey => $attributeLabel) {
777
                    $attributes[] = [
778
                        'attributeKey' => $attributeKey,
779
                        'attributeLabel' => $attributeLabel,
780
                        'shopwareAttributeKey' => ''
781
                    ];
782
                }
783
            } else {
784
                $attributes = [];
785
            }
786
        } catch (\Exception $e) {
787
            // ignore this exception because sometimes
788
            // connect plugin is not configured and tries to
789
            // read marketplace attributes
790
            $attributes = [];
791
        }
792
793
        $this->View()->assign(
794
            [
795
                'success' => true,
796
                'data' => $attributes
797
            ]
798
        );
799
    }
800
801
    public function saveProductAttributesMappingAction()
802
    {
803
        try {
804
            $data = $this->Request()->getParam('data');
805
            $data = !isset($data[0]) ? [$data] : $data;
806
            $marketplaceGateway = $this->getFactory()->getMarketplaceGateway();
807
            $marketplaceGateway->setMarketplaceMapping($data);
808
809
            $this->View()->assign(['success' => true]);
810
        } catch (\Exception $e) {
811
            $this->View()->assign(
812
                [
813
                    'success' => false,
814
                    'message' => $e->getMessage()
815
                ]
816
            );
817
        }
818
    }
819
820
    public function getProductAttributesMappingAction()
821
    {
822
        $marketplaceGateway = $this->getFactory()->getMarketplaceGateway();
823
824
        $mappings = array_map(
825
            function ($attribute) use ($marketplaceGateway) {
826
                return [
827
                    'shopwareAttributeKey' => $attribute->getName(),
828
                    'shopwareAttributeLabel' => $attribute->getLabel(),
829
                    'attributeKey' => $marketplaceGateway->findMarketplaceMappingFor($attribute->getName()),
830
                ];
831
            },
832
            array_values(
833
                array_filter(
834
                    Shopware()->Models()->getRepository('Shopware\Models\Article\Element')->findAll(),
835
                    function ($attribute) {
836
                        return $attribute->getName() != 'connectProductDescription';
837
                    }
838
                )
839
            )
840
        );
841
842
        $this->View()->assign(
843
            [
844
                'success' => true,
845
                'data' => $mappings
846
            ]
847
        );
848
    }
849
850
    /**
851
     * Loads all customer groups
852
     *
853
     * @throws Zend_Db_Statement_Exception
854
     */
855
    public function getExportCustomerGroupsAction()
856
    {
857
        $builder = $this->getCustomerGroupRepository()->createQueryBuilder('groups');
858
        $builder->select([
859
            'groups.id as id',
860
            'groups.key as key',
861
            'groups.name as name',
862
            'groups.tax as tax',
863
            'groups.taxInput as taxInput',
864
            'groups.mode as mode'
865
        ]);
866
867
        $query = $builder->getQuery();
868
869
        //get total result of the query
870
        $total = Shopware()->Models()->getQueryCount($query);
871
872
        $data = $query->getArrayResult();
873
874
        //return the data and total count
875
        $this->View()->assign(
876
            [
877
                'success' => true,
878
                'data' => $data,
879
                'total' => $total,
880
            ]
881
        );
882
    }
883
884
    /**
885
     * Loads all price groups where at least
886
     * one product with price greater than 0 exists
887
     *
888
     * @throws Zend_Db_Statement_Exception
889
     */
890
    public function getExportPriceGroupsAction()
891
    {
892
        $groups = [];
893
894
        $customerGroupKey = $this->Request()->getParam('customerGroup', 'EK');
895
        $priceExportMode = $this->Request()->getParam('priceExportMode');
896
        /** @var \Shopware\Models\Customer\Group $customerGroup */
897
        $customerGroup = $this->getCustomerGroupRepository()->findOneBy(['key' => $customerGroupKey]);
898
        if (!$customerGroup) {
899
            $this->View()->assign(
900
                [
901
                    'success' => true,
902
                    'data' => $groups,
903
                    'total' => count($groups),
904
                ]
905
            );
906
907
            return;
908
        }
909
910
        $exportConfigArray = $this->getConfigComponent()->getExportConfig();
911
912
        if (array_key_exists('exportPriceMode', $exportConfigArray)
913
            && count($exportConfigArray['exportPriceMode']) > 0
914
            && $this->getSDK()->getPriceType() != \Shopware\Connect\SDK::PRICE_TYPE_NONE
915
        ) {
916
            $groups[] = $this->getConfigComponent()->collectExportPrice($priceExportMode, $customerGroupKey);
917
        } else {
918
            $productCount = $this->getPriceGateway()->countProducts($customerGroup);
919
            $priceConfiguredProducts = $this->getPriceGateway()->countProductsWithConfiguredPrice($customerGroup, 'price');
920
            $basePriceConfiguredProducts = $this->getPriceGateway()->countProductsWithConfiguredPrice($customerGroup, 'baseprice');
921
            $pseudoPriceConfiguredProducts = $this->getPriceGateway()->countProductsWithConfiguredPrice($customerGroup, 'pseudoprice');
922
923
            $groups[] = [
924
                'price' => false,
925
                'priceAvailable' => $priceConfiguredProducts > 0,
926
                'priceConfiguredProducts' => $priceConfiguredProducts,
927
                'basePrice' => false,
928
                'basePriceAvailable' => $basePriceConfiguredProducts > 0,
929
                'basePriceConfiguredProducts' => $basePriceConfiguredProducts,
930
                'pseudoPrice' => false,
931
                'pseudoPriceAvailable' => $pseudoPriceConfiguredProducts > 0,
932
                'pseudoPriceConfiguredProducts' => $pseudoPriceConfiguredProducts,
933
                'productCount' => $productCount
934
            ];
935
        }
936
937
        $this->View()->assign(
938
            [
939
                'success' => true,
940
                'data' => $groups,
941
                'total' => count($groups),
942
            ]
943
        );
944
    }
945
946
    public function adoptUnitsAction()
947
    {
948
        $connection = $this->getModelManager()->getConnection();
949
        $connection->beginTransaction();
950
951
        try {
952
            $units = array_filter($this->getConfigComponent()->getUnitsMappings(), function ($unit) {
953
                return strlen($unit) == 0;
954
            });
955
956
            $models = $this->getUnitMapper()->createUnits(array_keys($units));
957
            foreach ($models as $unit) {
958
                $this->getHelper()->updateUnitInRelatedProducts($unit, $unit->getUnit());
959
            }
960
            $connection->commit();
961
        } catch (\Exception $e) {
962
            $connection->rollBack();
963
            $this->getLogger()->write(true, $e->getMessage(), $e);
964
            $this->View()->assign(
965
                [
966
                    'success' => false,
967
                ]
968
            );
969
970
            return;
971
        }
972
973
        $this->View()->assign(
974
            [
975
                'success' => true,
976
            ]
977
        );
978
    }
979
980
    public function checkCronPluginAction()
981
    {
982
        $pluginRepo = $this->getModelManager()->getRepository(Plugin::class);
983
        $cronPlugin = $pluginRepo->findOneBy(['name' => 'Cron']);
984
985
        $this->View()->assign(
986
            [
987
                'cronActivated' => (bool) $cronPlugin->getActive()
988
            ]
989
        );
990
    }
991
992
    /**
993
     * @return \ShopwarePlugins\Connect\Components\ConnectFactory
994
     */
995
    public function getFactory()
996
    {
997
        if ($this->factory === null) {
998
            $this->factory = new \ShopwarePlugins\Connect\Components\ConnectFactory();
999
        }
1000
1001
        return $this->factory;
1002
    }
1003
1004
    /**
1005
     * @return UnitMapper
1006
     */
1007
    private function getUnitMapper()
1008
    {
1009
        if (!$this->unitMapper) {
1010
            $this->unitMapper = new UnitMapper(
1011
                $this->getConfigComponent(),
1012
                $this->getModelManager()
1013
            );
1014
        }
1015
1016
        return $this->unitMapper;
1017
    }
1018
1019
    /**
1020
     * @return Logger
1021
     */
1022
    private function getLogger()
1023
    {
1024
        if (!$this->logger) {
1025
            $this->logger = new Logger(Shopware()->Db());
1026
        }
1027
1028
        return $this->logger;
1029
    }
1030
1031
    /**
1032
     * @return \Shopware\Components\Model\ModelRepository
1033
     */
1034
    private function getCustomerGroupRepository()
1035
    {
1036
        if (!$this->customerGroupRepository) {
1037
            $this->customerGroupRepository = Shopware()->Models()->getRepository('Shopware\Models\Customer\Group');
1038
        }
1039
1040
        return $this->customerGroupRepository;
1041
    }
1042
1043
    private function getPriceGateway()
1044
    {
1045
        if (!$this->priceGateway) {
1046
            $this->priceGateway = new \ShopwarePlugins\Connect\Components\PriceGateway(
1047
                Shopware()->Db()
1048
            );
1049
        }
1050
1051
        return $this->priceGateway;
1052
    }
1053
1054 View Code Duplication
    private function getSnHttpClient()
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...
1055
    {
1056
        if (!$this->snHttpClient) {
1057
            $this->snHttpClient = new SnHttpClient(
1058
                $this->get('http_client'),
1059
                new \Shopware\Connect\Gateway\PDO(Shopware()->Db()->getConnection()),
1060
                $this->getConfigComponent()
1061
            );
1062
        }
1063
1064
        return $this->snHttpClient;
1065
    }
1066
}
1067