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

ConnectTestHelper::getProductToShop()   B

Complexity

Conditions 1
Paths 1

Size

Total Lines 24
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 24
rs 8.9713
c 0
b 0
f 0
cc 1
eloc 18
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 Tests\ShopwarePlugins\Connect;
9
10
use Shopware\Connect\Gateway\PDO;
11
use Shopware\Connect\Struct\Property;
12
use Shopware\Connect\Struct\Translation;
13
use ShopwarePlugins\Connect\Components\CategoryResolver\DefaultCategoryResolver;
14
use ShopwarePlugins\Connect\Components\ConnectExport;
15
use ShopwarePlugins\Connect\Components\ConnectFactory;
16
use ShopwarePlugins\Connect\Components\ErrorHandler;
17
use ShopwarePlugins\Connect\Components\Gateway\ProductTranslationsGateway\PdoProductTranslationsGateway;
18
use ShopwarePlugins\Connect\Components\ImageImport;
19
use ShopwarePlugins\Connect\Components\Logger;
20
use ShopwarePlugins\Connect\Components\Marketplace\MarketplaceGateway;
21
use ShopwarePlugins\Connect\Components\ProductToShop;
22
use ShopwarePlugins\Connect\Components\Validator\ProductAttributesValidator\ProductsAttributesValidator;
23
use Shopware\CustomModels\Connect\Attribute;
24
use ShopwarePlugins\Connect\Components\Config;
25
use Shopware\Models\Article\Article;
26
use Shopware\Models\Article\Detail;
27
use ShopwarePlugins\Connect\Components\VariantConfigurator;
28
29
class ConnectTestHelper extends \Enlight_Components_Test_Plugin_TestCase
30
{
31
    const IMAGE_PROVIDER_URL = 'http://www.shopware.de/ShopwareCommunityCenter/img/logo.png';
32
33
    public function setUp()
34
    {
35
        parent::setUp();
36
37
        set_error_handler(null);
38
        set_exception_handler(null);
39
    }
40
41
    /**
42
     * @return \ShopwarePlugins\Connect\Components\ConnectFactory
43
     */
44
    public function getConnectFactory()
45
    {
46
        if (!$this->connectFactory) {
47
            $this->connectFactory = new ConnectFactory();
48
        }
49
50
        return $this->connectFactory;
51
    }
52
53
    /**
54
     * @return \Shopware\Connect\SDK
55
     */
56
    public function getSDK()
57
    {
58
        if (!$this->sdk) {
59
            $this->sdk = $this->getConnectFactory()->createSdk();
60
        }
61
62
        return $this->sdk;
63
    }
64
65
    /**
66
     * @return int
67
     */
68
    public function getConnectProductArticleId($sourceId, $shopId=3)
69
    {
70
        $id = Shopware()->Db()->fetchOne(
71
            'SELECT article_id FROM s_plugin_connect_items WHERE source_id = ? and shop_id =  ? LIMIT 1',
72
            [$sourceId, $shopId]
73
        );
74
75
        return $id;
76
    }
77
78
    public function getExternalProductSourceId()
79
    {
80
        $sql = 'SELECT source_id FROM s_plugin_connect_items WHERE shop_id IS NOT NULL';
81
        $sourceId = Shopware()->Db()->fetchOne($sql);
82
83
        return $sourceId;
84
    }
85
86
    /**
87
     * @return \ShopwarePlugins\Connect\Components\Helper
88
     */
89
    public function getHelper()
90
    {
91
        return Shopware()->Plugins()->Backend()->SwagConnect()->getHelper();
92
    }
93
94
    public function callPrivate($class, $method, $args)
95
    {
96
        $method = new \ReflectionMethod(
97
            $class, $method
98
        );
99
100
        $method->setAccessible(true);
101
102
        return call_user_func([$method, 'invoke', $args]);
103
    }
104
105
    /**
106
     * @return ConnectExport
107
     */
108 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...
109
    {
110
        return new ConnectExport(
111
            $this->getHelper(),
112
            $this->getSDK(),
113
            Shopware()->Models(),
114
            new ProductsAttributesValidator(),
115
            new Config(Shopware()->Models()),
116
            new ErrorHandler(),
117
            Shopware()->Container()->get('events')
118
        );
119
    }
120
121
    /**
122
     * @return ImageImport
123
     */
124 View Code Duplication
    public function getImageImport()
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...
125
    {
126
        return new ImageImport(
127
            Shopware()->Models(),
128
            $this->getHelper(),
129
            Shopware()->Container()->get('thumbnail_manager'),
130
            new Logger(Shopware()->Db())
131
        );
132
    }
133
134
    public function changeCategoryConnectMappingForCategoryTo($categoryId, $mapping)
135
    {
136
        $modelManager = Shopware()->Models();
137
        $categoryRepository = $modelManager->getRepository('Shopware\Models\Category\Category');
138
        $category = $categoryRepository->find($categoryId);
139
140
        if (!$category) {
141
            $this->fail('Could not find category with ID ' . $categoryId);
142
        }
143
144
        $attribute = $category->getAttribute() ?: new \Shopware\Models\Attribute\Category();
145
        $attribute->setConnectImportMapping($mapping);
146
        $attribute->setConnectExportMapping($mapping);
147
        $category->setAttribute($attribute);
148
        $attribute->setCategory($category);
149
150
        $modelManager->persist($category);
151
        $modelManager->persist($attribute);
152
153
        $modelManager->flush();
154
    }
155
156
    public static function dispatchRpcCall($service, $command, array $args)
157
    {
158
        $sdk = Shopware()->Container()->get('ConnectSDK');
159
        $refl = new \ReflectionObject($sdk);
160
        $property = $refl->getProperty('dependencies');
161
        $property->setAccessible(true);
162
        $deps = $property->getValue($sdk);
163
        $serviceRegistry = $deps->getServiceRegistry();
164
        $callable = $serviceRegistry->getService($service, $command);
165
166
        return call_user_func_array([$callable['provider'], $callable['command']], $args);
167
    }
168
169
    protected function getProduct($withImage = false, $withVariantImages = false)
170
    {
171
        $purchasePrice = 6.99;
172
        $offerValidUntil = time() + 1 * 365 * 24 * 60 * 60; // One year
173
        $number = rand(1, 999999999);
174
        $product =  new \Shopware\Connect\Struct\Product([
175
            'shopId' => 3,
176
            'revisionId' => time(),
177
            'sourceId' => $number,
178
            'ean' => $number,
179
            'sku' => 'sku#' . $number,
180
            'url' => 'http://shopware.de',
181
            'title' => 'MassImport #' . $number,
182
            'shortDescription' => 'Ein Produkt aus shopware Connect',
183
            'longDescription' => 'Ein Produkt aus shopware Connect',
184
            'additionalDescription' => 'Ein Produkt aus shopware Connect',
185
            'vendor' => [
186
                'url' => 'http://connect.shopware.de/',
187
                'name' => 'shopware Connect',
188
                'logo_url' => self::IMAGE_PROVIDER_URL,
189
                'page_title' => 'shopware Connect title',
190
                'description' => 'shopware Connect description'
191
            ],
192
            'stream' => 'Awesome products',
193
            'price' => 9.99,
194
            'purchasePrice' => $purchasePrice,
195
            'purchasePriceHash' => hash_hmac(
196
                'sha256',
197
                sprintf('%.3F %d', $purchasePrice, $offerValidUntil), '54642546-0001-48ee-b4d0-4f54af66d822'
198
            ),
199
            'offerValidUntil' => $offerValidUntil,
200
            'availability' => 100,
201
            'categories' => [
202
                '/bücher' => 'Bücher',
203
            ],
204
            'translations' => [
205
                'en' => new Translation([
206
                    'title' => 'MassImport #' . $number . ' EN',
207
                    'longDescription' => 'Ein Produkt aus shopware Connect EN',
208
                    'shortDescription' => 'Ein Produkt aus shopware Connect short EN',
209
                    'additionalDescription' => 'Ein Produkt aus shopware Verbinden Sie mit zusätzlicher Beschreibung EN',
210
                    'url' => 'http://shopware.de',
211
                ])
212
            ]
213
        ]);
214
215
        if ($withImage) {
216
            $product->images = [self::IMAGE_PROVIDER_URL . '?' . $number];
217
        }
218
219
        if ($withVariantImages) {
220
            $product->variantImages = [self::IMAGE_PROVIDER_URL . '?' . $number . '-variantImage'];
221
        }
222
223
        return $product;
224
    }
225
226
    protected function getProperties()
227
    {
228
        return [
229
            new Property([
230
                'groupName' => 'Nike',
231
                'comparable' => false,
232
                'sortMode' => 1,
233
                'option' => 'color',
234
                'filterable' => false,
235
                'value' => 'red'
236
            ]),
237
            new Property([
238
                'groupName' => 'Nike',
239
                'comparable' => false,
240
                'sortMode' => 1,
241
                'option' => 'size',
242
                'filterable' => false,
243
                'value' => 'XXL',
244
                'valuePosition' => 1
245
            ]),
246
            new Property([
247
                'groupName' => 'Nike',
248
                'comparable' => false,
249
                'sortMode' => 1,
250
                'option' => 'size',
251
                'filterable' => false,
252
                'value' => '3XL'
253
            ])
254
        ];
255
    }
256
257
    protected function getProducts($number = 10, $withImage = false, $withVariantImages = false)
258
    {
259
        $products = [];
260
        for ($i=0; $i<$number; ++$i) {
261
            $products[] = $this->getProduct($withImage, $withVariantImages);
262
        }
263
264
        return $products;
265
    }
266
267
    protected function getVariants()
268
    {
269
        $number = $groupId = rand(1, 999999999);
270
        $color = [
271
            ['de' => 'Weiss-Blau' . $number, 'en' => 'White-Blue'],
272
            ['de' => 'Weiss-Rot' . $number, 'en' => 'White-Red'],
273
            ['de' => 'Blau-Rot' . $number, 'en' => 'Blue-Red'],
274
            ['de' => 'Schwarz-Rot' . $number, 'en' => 'Black-Red'],
275
        ];
276
277
        $variants = [];
278
        $mainVariant = $this->getProduct(true);
279
        $mainVariantColor = array_pop($color);
280
        $mainVariant->variant['Farbe'] = $mainVariantColor['de'];
281
        $mainVariant->groupId = $groupId;
0 ignored issues
show
Documentation Bug introduced by
The property $groupId was declared of type string, but $groupId is of type integer. Maybe add a type cast?

This check looks for assignments to scalar types that may be of the wrong type.

To ensure the code behaves as expected, it may be a good idea to add an explicit type cast.

$answer = 42;

$correct = false;

$correct = (bool) $answer;
Loading history...
282
        $variants[] = $mainVariant;
283
284
        //add translations
285
        $mainVariant->translations['en']->variantLabels = [
286
            'Farbe' => 'Color',
287
        ];
288
        $mainVariant->translations['en']->variantValues = [
289
            $mainVariantColor['de'] => $mainVariantColor['en'],
290
        ];
291
292
        for ($i = 0; $i < 4 - 1; ++$i) {
293
            $variant = $this->getProduct(true);
294
            $variantSourceId = $mainVariant->sourceId . '-' . $i;
295
            $variant->title = 'MassImport #' . $variantSourceId;
296
            $variant->sourceId = $variantSourceId;
297
            $variant->ean = $variantSourceId;
298
            $variantColor = array_pop($color);
299
            $variant->variant['Farbe'] = $variantColor['de'];
300
            $variant->groupId = $groupId;
301
            $variant->translations = [
302
                'en' => new Translation([
303
                    'title' => 'MassImport #' . $variantSourceId . ' EN',
304
                    'longDescription' => $mainVariant->longDescription . ' EN',
305
                    'shortDescription' => $mainVariant->shortDescription . ' EN',
306
                    'variantLabels' => [
307
                        'Farbe' => 'Color',
308
                    ],
309
                    'variantValues' => [
310
                        $variantColor['de'] => $variantColor['en'],
311
                    ],
312
                ]),
313
            ];
314
315
            $variants[] = $variant;
316
        }
317
318
        return $variants;
319
    }
320
321
    public function getLocalArticle()
322
    {
323
        $number = rand(1, 999999999);
324
325
        $article = new Article();
326
        $article->fromArray([
327
            'name' => 'LocalArticle #' . $number,
328
            'active' => true,
329
        ]);
330
        $tax = Shopware()->Models()->getRepository('Shopware\Models\Tax\Tax')->find(1);
331
        $article->setTax($tax);
332
333
        $supplier = Shopware()->Models()->getRepository('Shopware\Models\Article\Supplier')->find(1);
334
        $article->setSupplier($supplier);
335
336
        Shopware()->Models()->persist($article);
337
        Shopware()->Models()->flush();
338
339
        $mainDetail = new Detail();
340
        $mainDetail->fromArray([
341
            'number' => $number,
342
            'inStock' => 30,
343
            'article' => $article
344
        ]);
345
        $article->setMainDetail($mainDetail);
346
        $detailAtrribute = new \Shopware\Models\Attribute\Article();
347
        $detailAtrribute->fromArray([
348
            'article' => $article,
349
            'articleDetail' => $mainDetail,
350
        ]);
351
352
        /** @var \Shopware\Models\Customer\Group $customerGroup */
353
        $customerGroup = Shopware()->Models()->getRepository('Shopware\Models\Customer\Group')->findOneByKey('EK');
354
355
        $connectAttribute = new Attribute();
356
        $connectAttribute->fromArray([
357
            'isMainVariant' => true,
358
            'article' => $article,
359
            'articleDetail' => $article->getMainDetail(),
360
            'sourceId' => $article->getId(),
361
            'category' => '/bücher',
362
            'fixedPrice' => false,
363
            'purchasePriceHash' => '',
364
            'offerValidUntil' => 0,
365
            'stream' => '',
366
        ]);
367
368
        Shopware()->Models()->persist($mainDetail);
369
        Shopware()->Models()->persist($detailAtrribute);
370
        Shopware()->Models()->persist($connectAttribute);
371
        Shopware()->Models()->flush();
372
373
        // set price via plain SQL because shopware throws exception
374
        // undefined index: key when error handler is disabled
375
        Shopware()->Db()->executeQuery(
376
            'INSERT INTO `s_articles_prices`(`pricegroup`, `from`, `to`, `articleID`, `articledetailsID`, `price`, `baseprice`)
377
          VALUES (?, 1, "beliebig", ?, ?, ?, ?)
378
          ', [$customerGroup->getKey(), $article->getId(), $mainDetail->getId(), 8.99, 3.99]);
379
380
        return $article;
381
    }
382
383
    public function getProductToShop()
384
    {
385
        $manager = Shopware()->Models();
386
387
        return new ProductToShop(
388
            $this->getHelper(),
389
            Shopware()->Models(),
390
            $this->getImageImport(),
391
            new Config(Shopware()->Models()),
392
            new VariantConfigurator(
393
                $manager,
394
                new PdoProductTranslationsGateway(Shopware()->Db())
395
            ),
396
            new MarketplaceGateway($manager),
397
            new PdoProductTranslationsGateway(Shopware()->Db()),
398
            new DefaultCategoryResolver(
399
                $manager,
400
                $manager->getRepository('Shopware\CustomModels\Connect\RemoteCategory'),
401
                $manager->getRepository('Shopware\CustomModels\Connect\ProductToRemoteCategory')
402
            ),
403
            new PDO(Shopware()->Db()->getConnection()),
404
            Shopware()->Container()->get('events')
405
        );
406
    }
407
408
    protected function insertOrUpdateProducts($number, $withImage, $withVariantImages)
409
    {
410
        $commands = [];
411
        foreach ($this->getProducts($number, $withImage, $withVariantImages) as $product) {
412
            $commands[$product->sourceId] = new \Shopware\Connect\Struct\Change\ToShop\InsertOrUpdate([
413
                'product' => $product,
414
                'revision' => time(),
415
            ]);
416
        }
417
418
        $this->dispatchRpcCall('products', 'toShop', [
419
            $commands
420
        ]);
421
422
        return array_keys($commands);
423
    }
424
425
    protected function getRandomUser()
426
    {
427
        $user = Shopware()->Db()->fetchRow('SELECT * FROM s_user WHERE id = 1 LIMIT 1');
428
429
        $billing = Shopware()->Db()->fetchRow(
430
            'SELECT * FROM s_user_billingaddress WHERE userID = :id',
431
            [':id' => $user['id']]
432
        );
433
        $billing['stateID'] = isset($billing['stateId']) ? $billing['stateID'] : '1';
434
        $shipping = Shopware()->Db()->fetchRow(
435
            'SELECT * FROM s_user_shippingaddress WHERE userID = :id',
436
            [':id' => $user['id']]
437
        );
438
        $shipping['stateID'] = isset($shipping['stateId']) ? $shipping['stateID'] : '1';
439
        $country = Shopware()->Db()->fetchRow(
440
            'SELECT * FROM s_core_countries WHERE id = :id',
441
            [':id' => $billing['countryID']]
442
        );
443
        $state = Shopware()->Db()->fetchRow(
444
            'SELECT * FROM s_core_countries_states WHERE id = :id',
445
            [':id' => $billing['stateID']]
446
        );
447
        $countryShipping = Shopware()->Db()->fetchRow(
448
            'SELECT * FROM s_core_countries WHERE id = :id',
449
            [':id' => $shipping['countryID']]
450
        );
451
        $payment = Shopware()->Db()->fetchRow(
452
            'SELECT * FROM s_core_paymentmeans WHERE id = :id',
453
            [':id' => $user['paymentID']]
454
        );
455
        $customerGroup = Shopware()->Db()->fetchRow(
456
            'SELECT * FROM s_core_customergroups WHERE groupkey = :key',
457
            [':key' => $user['customergroup']]
458
        );
459
460
        $taxFree = (bool) ($countryShipping['taxfree']);
461
        if ($countryShipping['taxfree_ustid']) {
462
            if ($countryShipping['id'] == $country['id'] && $billing['ustid']) {
463
                $taxFree = true;
464
            }
465
        }
466
467
        if ($taxFree) {
468
            $customerGroup['tax'] = 0;
469
        }
470
471
        Shopware()->Session()->sUserGroupData = $customerGroup;
472
473
        return [
474
            'user' => $user,
475
            'billingaddress' => $billing,
476
            'shippingaddress' => $shipping,
477
            'customerGroup' => $customerGroup,
478
            'additional' => [
479
                'country' => $country,
480
                'state'   => $state,
481
                'user'    => $user,
482
                'countryShipping' => $countryShipping,
483
                'payment' => $payment,
484
                'charge_vat' => !$taxFree
485
            ]
486
        ];
487
    }
488
}
489