Completed
Pull Request — master (#336)
by Stefan
05:11
created

LocalProductQueryTest::setUp()   B

Complexity

Conditions 2
Paths 2

Size

Total Lines 88
Code Lines 62

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 88
rs 8.6012
c 0
b 0
f 0
cc 2
eloc 62
nc 2
nop 0

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace Tests\ShopwarePlugins\Connect\Component\ProductQuery;
4
5
use Shopware\Components\Model\ModelManager;
6
use Shopware\Connect\Struct\PriceRange;
7
use Shopware\Connect\Struct\Product;
8
use Shopware\Connect\Struct\Translation;
9
use ShopwarePlugins\Connect\Components\Config;
10
use ShopwarePlugins\Connect\Components\Marketplace\MarketplaceGateway;
11
use ShopwarePlugins\Connect\Components\ProductQuery;
12
use ShopwarePlugins\Connect\Components\ProductQuery\LocalProductQuery;
13
use Shopware\Bundle\StoreFrontBundle\Struct\Media;
14
use Shopware\Models\Property;
15
use Tests\ShopwarePlugins\Connect\ConnectTestHelper;
16
17
class LocalProductQueryTest extends ConnectTestHelper
18
{
19
    /**
20
     * @var LocalProductQuery
21
     */
22
    protected $localProductQuery;
23
24
    protected $productTranslator;
25
26
    protected $mediaService;
27
28
    private $translations;
29
30
    protected $localMediaService;
31
32
    protected $contextService;
33
34
    /** @var \Shopware\Models\Article\Article $article */
35
    private $article;
36
37
    /**
38
     * @var \Enlight_Components_Db_Adapter_Pdo_Mysql
39
     */
40
    private $db;
41
42
    /**
43
     * @var ModelManager
44
     */
45
    private $manager;
46
47
    /**
48
     * @var Config
49
     */
50
    private $config;
51
52
    protected $productContext;
53
54
    public function setUp()
55
    {
56
        parent::setUp();
57
58
        $this->db = Shopware()->Db();
59
        $this->manager = Shopware()->Models();
60
        $this->config = new Config($this->manager);
61
        $this->createArticle();
62
63
        $this->translations = [
64
            'en' => new Translation(
65
                [
66
                    'title' => 'Glas -Teetasse 0,25l EN',
67
                    'shortDescription' => 'shopware Connect local product short description EN',
68
                    'longDescription' => 'shopware Connect local product long description EN',
69
                    'url' => $this->getProductBaseUrl() . '22/shId/2'
70
                ]
71
            ),
72
            'nl' => new Translation(
73
                [
74
                    'title' => 'Glas -Teetasse 0,25l NL',
75
                    'shortDescription' => 'shopware Connect local product short description NL',
76
                    'longDescription' => 'shopware Connect local product long description NL',
77
                    'url' => $this->getProductBaseUrl() . '22/shId/176'
78
                ]
79
            ),
80
        ];
81
82
        $this->productTranslator = $this->getMockBuilder('\\ShopwarePlugins\\Connect\\Components\\Translations\\ProductTranslator')
83
            ->disableOriginalConstructor()
84
            ->getMock();
85
86
        $this->mediaService = $this->getMockBuilder('\\Shopware\\Bundle\\MediaBundle\\MediaService')
87
            ->disableOriginalConstructor()
88
            ->getMock();
89
90
        $this->mediaService->expects($this->any())
91
            ->method('getUrl')
92
            ->with($this->logicalOr(
93
                $this->equalTo('/media/image/tea_pavilion.jpg'),
94
                $this->equalTo('/media/image/tea.png')
95
            ))
96
            ->will($this->returnCallback([$this, 'getUrlCallback']));
97
        $this->productTranslator->expects($this->any())
98
            ->method('translate')
99
            ->willReturn($this->translations);
100
101
        $this->productTranslator->expects($this->any())
102
            ->method('translateConfiguratorGroup')
103
            ->willReturn($this->translations);
104
105
        $this->productTranslator->expects($this->any())
106
            ->method('translateConfiguratorOption')
107
            ->willReturn($this->translations);		
108
109
        $this->localMediaService = $this->getMockBuilder('\\ShopwarePlugins\\Connect\\Components\\MediaService\\LocalMediaService')
110
            ->disableOriginalConstructor()
111
            ->getMock();
112
113
        $this->contextService = $this->getMockBuilder('\\Shopware\\Bundle\\StoreFrontBundle\\Service\\Core\\ContextService')
114
            ->disableOriginalConstructor()
115
            ->getMock();
116
117
        $this->productContext = $this->getMockBuilder('\\Shopware\\Bundle\\StoreFrontBundle\\Struct\\ProductContext')
118
            ->disableOriginalConstructor()
119
            ->getMock();
120
        $this->contextService->expects($this->any())
121
            ->method('createShopContext')
122
            ->willReturn($this->productContext);
123
124
        $configs = [
125
            'priceGroupForPriceExport' => ['EK', null, 'export'],
126
            'priceGroupForPurchasePriceExport' => ['EK', null, 'export'],
127
            'priceFieldForPriceExport' => ['price', null, 'export'],
128
            'priceFieldForPurchasePriceExport' => ['detailPurchasePrice', null, 'export'],
129
        ];
130
131
        foreach ($configs as $name => $values) {
132
            list($value, $shopId, $group) = $values;
133
134
            $this->config->setConfig(
135
                $name,
136
                $value,
137
                $shopId,
138
                $group
139
            );
140
        }
141
    }
142
143
    /**
144
     * @param string $imagePath
145
     * @return string
146
     */
147
    public function getUrlCallback($imagePath) {
148
        if ($imagePath == '/media/image/tea_pavilion.jpg') {
149
            return 'http://myshop/media/image/2e/4f/tea_pavilion.jpg';
150
        } elseif ($imagePath == '/media/image/tea.png') {
151
            return 'http://myshop/media/image/2e/4f/tea.png';
152
        }
153
154
        throw new \InvalidArgumentException();
155
    }
156
157
    public function getLocalProductQuery()
158
    {
159
        if (!$this->localProductQuery) {
160
            /** @var \ShopwarePlugins\Connect\Components\Config $configComponent */
161
            $configComponent = new Config(Shopware()->Models());
162
163
            $this->localProductQuery = new LocalProductQuery(
164
                Shopware()->Models(),
165
                $this->getProductBaseUrl(),
166
                $configComponent,
167
                new MarketplaceGateway(Shopware()->Models()),
168
                $this->productTranslator,
169
                $this->contextService,
170
                $this->localMediaService,
171
                Shopware()->Container()->get('events'),
172
                $this->mediaService
173
            );
174
        }
175
        return $this->localProductQuery;
176
    }
177
178
    public function getProductBaseUrl()
179
    {
180
        if (!Shopware()->Front()->Router()) {
181
            return null;
182
        }
183
184
        return Shopware()->Front()->Router()->assemble([
185
            'module' => 'frontend',
186
            'controller' => 'connect_product_gateway',
187
            'action' => 'product',
188
            'id' => '',
189
            'fullPath' => true
190
        ]);
191
    }
192
193
    public function testGetUrlForProduct()
194
    {
195
        $expectedUrl = $this->getProductBaseUrl() . '1091';
196
        $this->assertEquals($expectedUrl, $this->getLocalProductQuery()->getUrlForProduct(1091));
197
    }
198
199
    public function testGetUrlForProductWithShopId()
200
    {
201
        $expectedUrl = $this->getProductBaseUrl() . '1091/shId/3';
202
        $this->assertEquals($expectedUrl, $this->getLocalProductQuery()->getUrlForProduct(1091, 3));
203
    }
204
205
    public function testGetConnectProduct()
206
    {
207
        $row = [
208
            'sku' => 'SW10005',
209
            'sourceId' => '22',
210
            'ean' => NULL,
211
            'title' => 'Glas -Teetasse 0,25l',
212
            'shortDescription' => 'Almus Emitto Bos sicut hae Amplitudo rixa ortus retribuo Vicarius an nam capitagium medius.',
213
            'vendor' =>  [
214
                'name' => 'Teapavilion',
215
                'description' => 'Teapavilion description',
216
                'logo_url' => 'tea_pavilion.jpg',
217
                'url' => 'http://teapavilion.com',
218
                'page_title' => 'Teapavilion title',
219
            ],
220
            'vat' => '0.190000',
221
            'availability' => 3445,
222
            'price' => 10.924369747899,
223
            'purchasePrice' => 0,
224
            'longDescription' => '<p>Reficio congratulor simplex Ile familia mire hae Prosequor in pro St quae Muto,, St Texo aer Cornu ferox lex inconsiderate propitius, animus ops nos haero vietus Subdo qui Gemo ipse somniculosus. Non Apertio ops, per Repere torpeo penintentiarius Synagoga res mala caelestis praestigiator. Ineo via consectatio Gemitus sui domus ludio is vulgariter, hic ut legens nox Falx nos cui vaco insudo tero, tollo valde emo. deprecativus fio redigo probabiliter pacificus sem Nequequam, suppliciter dis Te summisse Consuesco cur Desolo sis insolesco expeditus pes Curo aut Crocotula Trimodus. Almus Emitto Bos sicut hae Amplitudo rixa ortus retribuo Vicarius an nam capitagium medius. Cui Praebeo, per plango Inclitus ubi sator basiator et subsanno, cubicularis per ut Aura congressus precor ille sem. aro quid ius Praedatio vitupero Tractare nos premo procurator. Ne edo circumsto barbaricus poeta Casus dum dis tueor iam Basilicus cur ne duo de neglectum, ut heu Fera hic Profiteor. Ius Perpetuus stilla co.</p>',
225
            'fixedPrice' => null,
226
            'deliveryWorkDays' => null,
227
            'shipping' => null,
228
            'translations' => [],
229
            'attributes' => [
230
                'unit' => null,
231
                'quantity' => null,
232
                'ref_quantity' => null,
233
            ],
234
        ];
235
236
        $productMedia = [];
237
        for ($i = 1; $i < 12; $i++) {
238
            $media = new Media();
239
            $media->setFile(sprintf('http://myshop/media/image/2e/4f/tea_pavilion_product_image%s.jpg', $i));
240
            $productMedia[] = $media;
241
        }
242
243
        $variantMedia = [];
244
        for ($i = 1; $i < 12; $i++) {
245
            $media = new Media();
246
            $media->setFile(sprintf('http://myshop/media/image/2e/4f/tea_pavilion_variant_image%s.jpg', $i));
247
            $variantMedia[] = $media;
248
        }
249
250
        $this->localMediaService->expects($this->once())
251
            ->method('getProductMediaList')
252
            ->with($this->anything(), $this->productContext)
253
            ->willReturn([$row['sku'] => $productMedia]);
254
255
        $this->localMediaService->expects($this->once())
256
            ->method('getVariantMediaList')
257
            ->with($this->anything(), $this->productContext)
258
            ->willReturn([$row['sku'] => $variantMedia]);
259
260
        $expectedProduct = new Product($row);
261
        $expectedProduct->vendor['logo_url'] = 'http://myshop/media/image/2e/4f/tea_pavilion.jpg';
262
        $expectedProduct->url = $this->getProductBaseUrl() . '22';
263
        $expectedProduct->attributes = [
264
            'quantity' => NULL,
265
            'ref_quantity' => NULL,
266
        ];
267
        $expectedProduct->translations = $this->translations;
268
        $expectedProduct->priceRanges = [
269
            new PriceRange([
270
                'customerGroupKey' => 'EK',
271
                'from' => 1,
272
                'to' => 5,
273
                'price' => 123.99,
274
            ]),
275
            new PriceRange([
276
                'customerGroupKey' => 'EK',
277
                'from' => 6,
278
                'to' => PriceRange::ANY,
279
                'price' => 113.99,
280
            ]),
281
        ];
282
283
        $expectedProduct->properties = [
284
            new \Shopware\Connect\Struct\Property([
285
                'groupName' => 'Adidas',
286
                'groupPosition' => 3,
287
                'comparable' => false,
288
                'sortMode' => 3,
289
                'option' => 'color',
290
                'filterable' => false,
291
                'value' => 'green',
292
                'valuePosition' => 0,
293
            ]),
294
            new \Shopware\Connect\Struct\Property([
295
                'groupName' => 'Adidas',
296
                'groupPosition' => 3,
297
                'comparable' => false,
298
                'sortMode' => 3,
299
                'option' => 'size',
300
                'filterable' => false,
301
                'value' => '2xl',
302
                'valuePosition' => 0,
303
            ]),
304
            new \Shopware\Connect\Struct\Property([
305
                'groupName' => 'Adidas',
306
                'groupPosition' => 3,
307
                'comparable' => false,
308
                'sortMode' => 3,
309
                'option' => 'size',
310
                'filterable' => false,
311
                'value' => '3xl',
312
                'valuePosition' => 0,
313
            ]),
314
        ];
315
316
		$expectedProduct->images = [
317
            'http://myshop/media/image/2e/4f/tea_pavilion_product_image1.jpg',
318
            'http://myshop/media/image/2e/4f/tea_pavilion_product_image2.jpg',
319
            'http://myshop/media/image/2e/4f/tea_pavilion_product_image3.jpg',
320
            'http://myshop/media/image/2e/4f/tea_pavilion_product_image4.jpg',
321
            'http://myshop/media/image/2e/4f/tea_pavilion_product_image5.jpg',
322
            'http://myshop/media/image/2e/4f/tea_pavilion_product_image6.jpg',
323
            'http://myshop/media/image/2e/4f/tea_pavilion_product_image7.jpg',
324
            'http://myshop/media/image/2e/4f/tea_pavilion_product_image8.jpg',
325
            'http://myshop/media/image/2e/4f/tea_pavilion_product_image9.jpg',
326
            'http://myshop/media/image/2e/4f/tea_pavilion_product_image10.jpg',
327
            'http://myshop/media/image/2e/4f/tea_pavilion_variant_image1.jpg',
328
            'http://myshop/media/image/2e/4f/tea_pavilion_variant_image2.jpg',
329
            'http://myshop/media/image/2e/4f/tea_pavilion_variant_image3.jpg',
330
            'http://myshop/media/image/2e/4f/tea_pavilion_variant_image4.jpg',
331
            'http://myshop/media/image/2e/4f/tea_pavilion_variant_image5.jpg',
332
            'http://myshop/media/image/2e/4f/tea_pavilion_variant_image6.jpg',
333
            'http://myshop/media/image/2e/4f/tea_pavilion_variant_image7.jpg',
334
            'http://myshop/media/image/2e/4f/tea_pavilion_variant_image8.jpg',
335
            'http://myshop/media/image/2e/4f/tea_pavilion_variant_image9.jpg',
336
            'http://myshop/media/image/2e/4f/tea_pavilion_variant_image10.jpg',
337
        ];
338
        $expectedProduct->variantImages = [
339
            'http://myshop/media/image/2e/4f/tea_pavilion_variant_image1.jpg',
340
            'http://myshop/media/image/2e/4f/tea_pavilion_variant_image2.jpg',
341
            'http://myshop/media/image/2e/4f/tea_pavilion_variant_image3.jpg',
342
            'http://myshop/media/image/2e/4f/tea_pavilion_variant_image4.jpg',
343
            'http://myshop/media/image/2e/4f/tea_pavilion_variant_image5.jpg',
344
            'http://myshop/media/image/2e/4f/tea_pavilion_variant_image6.jpg',
345
            'http://myshop/media/image/2e/4f/tea_pavilion_variant_image7.jpg',
346
            'http://myshop/media/image/2e/4f/tea_pavilion_variant_image8.jpg',
347
            'http://myshop/media/image/2e/4f/tea_pavilion_variant_image9.jpg',
348
            'http://myshop/media/image/2e/4f/tea_pavilion_variant_image10.jpg',
349
        ];
350
351
        $row['vendorName'] = $row['vendor']['name'];
352
        $row['vendorLink'] = $row['vendor']['url'];
353
        $row['vendorImage'] = $row['vendor']['logo_url'];
354
        $row['vendorDescription'] = $row['vendor']['description'];
355
        $row['vendorMetaTitle'] = $row['vendor']['page_title'];
356
        unset($row['vendor']);
357
        $row['category'] = '';
358
        $row['weight'] = null;
359
        $row['unit'] = null;
360
        $row['localId'] = $this->article->getId();
361
        $row['detailId'] = $this->article->getMainDetail()->getId();
362
363
        $this->assertEquals($expectedProduct, $this->getLocalProductQuery()->getConnectProduct($row));
364
    }
365
366
    private function createArticle()
367
    {
368
        $group = $this->manager->getRepository(Property\Group::class)->findOneBy(
369
            ['name' => 'Adidas']
370
        );
371
372
        if (!$group) {
373
            $group = new Property\Group();
374
            $group->setName('Adidas');
375
            $group->setPosition(3);
376
            $group->setSortMode(3);
377
            $group->setComparable(0);
378
            $this->manager->persist($group);
379
            $this->manager->flush();
380
        }
381
382
        $minimalTestArticle = [
383
            'name' => 'Glas -Teetasse 0,25l',
384
            'active' => true,
385
            'tax' => 19,
386
            'supplier' => 'Teapavilion',
387
            'mainDetail' => [
388
                'number' => '9898' . rand(1, 99999),
389
            ],
390
            'filterGroupId' => $group->getId(),
391
            'propertyValues' => [
392
                [
393
                    'option' => [
394
                        'name' => 'color',
395
                    ],
396
                    'value' => 'green'
397
                ],
398
                [
399
                    'option' => [
400
                        'name' => 'size',
401
                    ],
402
                    'value' => '2xl'
403
                ],
404
                [
405
                    'option' => [
406
                        'name' => 'size',
407
                    ],
408
                    'value' => '3xl'
409
                ]
410
            ]
411
        ];
412
413
        $articleResource = \Shopware\Components\Api\Manager::getResource('article');
414
        /** @var \Shopware\Models\Article\Article $article */
415
        $this->article = $articleResource->create($minimalTestArticle);
416
417
        $this->db->insert(
418
            's_articles_prices',
419
            [
420
                'pricegroup' => 'EK',
421
                'from' => 1,
422
                'to' => 5,
423
                'price' => 123.99,
424
                'articleID' => $this->article->getId(),
425
                'articledetailsID' => $this->article->getMainDetail()->getId(),
426
                'pseudoprice' => 0
427
            ]
428
        );
429
430
        $this->db->insert(
431
            's_articles_prices',
432
            [
433
                'pricegroup' => 'EK',
434
                'from' => 6,
435
                'to' => 'beliebig',
436
                'price' => 113.99,
437
                'articleID' => $this->article->getId(),
438
                'articledetailsID' => $this->article->getMainDetail()->getId(),
439
                'pseudoprice' => 0
440
            ]
441
        );
442
443
        $this->db->insert(
444
            's_plugin_connect_items',
445
            [
446
                'article_id' => $this->article->getId(),
447
                'article_detail_id' => $this->article->getMainDetail()->getId(),
448
                'source_id' => $this->getHelper()->generateSourceId($this->article->getMainDetail()),
449
            ]
450
        );
451
    }
452
453
    public function testGetLocalProductQueryShouldFetchProductsWithoutArticleDetailAttribute()
454
    {
455
        $this->localMediaService->expects($this->any())
456
            ->method('getProductMediaList')
457
            ->with($this->anything(), $this->productContext)
458
            ->willReturn(['SW10005' => []]);
459
460
        $this->localMediaService->expects($this->any())
461
            ->method('getVariantMediaList')
462
            ->with($this->anything(), $this->productContext)
463
            ->willReturn(['SW10005' => []]);
464
465
        $this->db->delete('s_articles_attributes', 'articleID = ' . $this->article->getId());
466
467
        $this->assertCount(1, $this->getLocalProductQuery()->get([$this->article->getId()]));
468
    }
469
470
471
    public function tearDown()
472
    {
473
        if (!$this->article) {
474
            return;
475
        }
476
477
        $articleId = $this->article->getId();
478
        $this->db->exec("DELETE FROM s_articles WHERE id = $articleId");
479
        $this->db->exec('DELETE FROM s_articles_details WHERE ordernumber LIKE "9898%"');
480
        $this->db->exec("DELETE FROM s_articles_prices WHERE articleID = $articleId");
481
    }
482
}
483