Completed
Push — master ( 335c44...a95920 )
by Jonas
05:50 queued 02:51
created

ImageImport::importImagesForArticle()   B

Complexity

Conditions 4
Paths 6

Size

Total Lines 32
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 32
rs 8.5806
c 0
b 0
f 0
cc 4
eloc 17
nc 6
nop 2
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\Model\ModelManager;
11
use Shopware\Models\Article\Article;
12
use Shopware\Models\Article\Detail;
13
use Shopware\Models\Article\Image;
14
use Shopware\Models\Media\Media;
15
use Shopware\Models\Attribute\Media as MediaAttribute;
16
use Shopware\Models\Attribute\ArticleImage as ImageAttribute;
17
use Symfony\Component\HttpFoundation\File\File;
18
use Shopware\Models\Article\Supplier;
19
use Shopware\Components\Thumbnail\Manager as ThumbnailManager;
20
21
class ImageImport
22
{
23
    /** @var \Shopware\Components\Model\ModelManager */
24
    protected $manager;
25
26
    /** @var Helper */
27
    protected $helper;
28
29
    /**
30
     * @var ThumbnailManager
31
     */
32
    protected $thumbnailManager;
33
34
    /** @var \ShopwarePlugins\Connect\Components\Logger */
35
    protected $logger;
36
37
    public function __construct(
38
        ModelManager $manager,
39
        Helper $helper,
40
        ThumbnailManager $thumbnailManager,
41
        Logger $logger
42
    ) {
43
        $this->manager = $manager;
44
        $this->helper = $helper;
45
        $this->thumbnailManager = $thumbnailManager;
46
        $this->logger = $logger;
47
    }
48
49
    /**
50
     * Helper to determine, if there is a main image for a given articleId
51
     *
52
     * @param $articleId
53
     * @return bool
54
     */
55
    public function hasArticleMainImage($articleId)
56
    {
57
        $builder = $this->manager->createQueryBuilder();
58
        $builder->select(['images'])
59
            ->from('Shopware\Models\Article\Image', 'images')
60
            ->where('images.articleId = :articleId')
61
            ->andWhere('images.parentId IS NULL')
62
            ->andWhere('images.main = :main')
63
            ->setParameter('main', 1)
64
            ->setParameter('articleId', $articleId)
65
            ->setFirstResult(0)
66
            ->setMaxResults(1);
67
68
        $result = $builder->getQuery()->getResult();
69
70
        return !empty($result);
71
    }
72
73
    /**
74
     * Get ids of products that needs an image import
75
     * @param null $limit
76
     * @return array        Ids of products needing an image import
77
     */
78
    public function getProductsNeedingImageImport($limit=null)
79
    {
80
        $updateFlags = $this->helper->getUpdateFlags();
81
        $updateFlagsByName = array_flip($updateFlags);
82
83
        $initialImportFlag = $updateFlagsByName['imageInitialImport'];
84
85
        $builder = $this->manager->createQueryBuilder();
86
        $builder->from('Shopware\CustomModels\Connect\Attribute', 'at');
87
        $builder->innerJoin('at.articleDetail', 'detail');
88
        $builder->select('at.articleId');
89
        $builder->andWhere('at.shopId IS NOT NULL')
90
            ->andWHere('at.lastUpdateFlag IS NOT NULL')
91
            ->andWHere('BIT_AND(at.lastUpdateFlag, :initialImportFlag) > 0')
92
            ->setParameter('initialImportFlag', $initialImportFlag);
93
94
        if ($limit) {
95
            $builder->setMaxResults($limit);
96
        }
97
98
        $ids = $builder->getQuery()->getArrayResult();
99
100
        return array_map('array_pop', $ids);
101
    }
102
103
    /**
104
     * Batch import images for new products without images
105
     *
106
     * @param int|null $limit
107
     */
108
    public function import($limit = null)
109
    {
110
        $articleRepository = $this->manager->getRepository('Shopware\Models\Article\Article');
111
112
        $flags = $this->helper->getUpdateFlags();
113
        $flagsByName = array_flip($flags);
114
115
        $ids = $this->getProductsNeedingImageImport($limit);
0 ignored issues
show
Bug introduced by
It seems like $limit defined by parameter $limit on line 108 can also be of type integer; however, ShopwarePlugins\Connect\...ctsNeedingImageImport() does only seem to accept null, maybe add an additional type check?

This check looks at variables that have been passed in as parameters and are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
116
117
        foreach ($ids as $id) {
118
            /** @var \Shopware\Models\Article\Article $article */
119
            $article = $articleRepository->find($id);
120
            $connectAttributes = $this->helper->getConnectAttributesByArticle($article);
121
122
            /** @var \Shopware\CustomModels\Connect\Attribute $connectAttribute */
123
            foreach ($connectAttributes as $connectAttribute) {
124
                $lastUpdate = json_decode($connectAttribute->getLastUpdate(), true);
125
                $this->importImagesForArticle(array_diff($lastUpdate['image'], $lastUpdate['variantImages']), $article);
126
                $this->importImagesForDetail($lastUpdate['variantImages'], $connectAttribute->getArticleDetail());
127
                $connectAttribute->flipLastUpdateFlag($flagsByName['imageInitialImport']);
128
            }
129
130
            $this->manager->flush();
131
        }
132
    }
133
134
    /**
135
     * Handles the image import of a product. This will:
136
     * - delete all images imported from connect before and not in the current import list
137
     * - create new images which have not already been imported
138
     * - set the main image, if there is no main image, yet
139
     *
140
     * Images are identified via the URL of the connect image. So we don't need to md5 the
141
     * actual image content every time.
142
     *
143
     * @param array $images
144
     * @param $article \Shopware\Models\Article\Article
145
     */
146
    public function importImagesForArticle($images, Article $article)
147
    {
148
        $localImagesFromConnect = $this->getImportedImages($article);
149
        $remoteImagesFromConnect = array_flip($images);
150
151
        // Build up arrays of images to delete and images to create
152
        $imagesToDelete = array_diff_key($localImagesFromConnect, $remoteImagesFromConnect);
153
        $imagesToCreate = array_diff_key($remoteImagesFromConnect, $localImagesFromConnect);
154
155
        // Delete old connect images and media objects
156
        foreach ($imagesToDelete as $hash => $data) {
157
            /** @var \Shopware\Models\Article\Image $image */
158
            $image = $data['image'];
159
            // if the image has mapping, it's variant image and shouldn't be deleted
160
            if (count($image->getMappings()) > 0) {
161
                continue;
162
            }
163
            $this->manager->remove($image);
164
            $this->manager->remove($data['media']);
165
        }
166
        $this->manager->flush();
167
168
        try {
169
            $this->importImages($imagesToCreate, $article);
170
        } catch (\Exception $e) {
171
            // log exception message if for some reason
172
            // image import fails
173
            $this->logger->write(true, 'Import images', $e->getMessage());
174
        }
175
176
        $this->manager->flush();
177
    }
178
179
    /**
180
     * Handles the image import of a product. This will:
181
     * - delete all images imported from connect before and not in the current import list
182
     * - create new images which have not already been imported
183
     * - set the main image, if there is no main image, yet
184
     *
185
     * Images are identified via the URL of the connect image. So we don't need to md5 the
186
     * actual image content every time.
187
     *
188
     * @param array $variantImages
189
     * @param $detail \Shopware\Models\Article\Detail
190
     */
191
    public function importImagesForDetail(array $variantImages, Detail $detail)
192
    {
193
        $article = $detail->getArticle();
194
        $articleImages = $article->getImages();
195
196
        $localImagesFromConnect = $this->getImportedImages($detail);
197
        $localArticleImagesFromConnect = $this->getImportedImages($article);
198
199
        $remoteImagesFromConnect = array_flip($variantImages);
200
201
        // Build up arrays of images to delete and images to create
202
        $imagesToDelete = array_diff_key($localImagesFromConnect, $remoteImagesFromConnect);
203
        $imagesToCreate = array_diff_key($remoteImagesFromConnect, $localImagesFromConnect);
204
205
        $mappingRepository = $this->manager->getRepository('Shopware\Models\Article\Image\Mapping');
206
        // Delete old connect images and media objects
207
        foreach ($imagesToDelete as $hash => $data) {
208
            /** @var \Shopware\Models\Article\Image $image */
209
            $image = $data['image'];
210
            /** @var \Shopware\Models\Article\Image $child */
211
            foreach ($image->getChildren() as $child) {
212
                if ($detail->getId() == $child->getArticleDetail()->getId()) {
213
                    $childAttribute = $child->getAttribute();
214
                    if (!$childAttribute) {
215
                        break;
216
                    }
217
218
                    $mapping = $mappingRepository->find($childAttribute->getConnectDetailMappingId());
219
                    if (!$mapping) {
220
                        break;
221
                    }
222
223
                    $this->manager->remove($mapping);
224
                    $this->manager->remove($child);
225
                    break;
226
                }
227
            }
228
229
            if (count($image->getChildren()) == 1) {
230
                $this->manager->remove($image);
231
                $this->manager->remove($data['media']);
232
            }
233
        }
234
        $this->manager->flush();
235
236
        try {
237
            $positions = [];
238
            foreach ($article->getImages() as $image) {
239
                $positions[] = $image->getPosition();
240
            }
241
            $maxPosition = count($positions) > 0 ? max($positions) : 0;
242
243
            /** @var \Shopware\Models\Media\Album $album */
244
            $album = $this->manager->find('Shopware\Models\Media\Album', -1);
245
            foreach ($imagesToCreate as $imageUrl => $key) {
246
                // check if image already exists in article images
247
                // 1) if it exists skip import and it's global image
248
                if (array_key_exists($imageUrl, $localArticleImagesFromConnect)
249
                    && empty($localArticleImagesFromConnect[$imageUrl]['image']->getMappings())) {
250
                    // if image doesn't have mappings
251
                    // it's global for all details
252
                    // do nothing, just continue
253
                    continue;
254
                }
255
256
                // 2) if it has mapping, add new one for current detail
257
                if (array_key_exists($imageUrl, $localArticleImagesFromConnect)) {
258
                    /** @var \Shopware\Models\Article\Image $articleImage */
259
                    $articleImage = $localArticleImagesFromConnect[$imageUrl]['image'];
260
                    $articleMedia = $localArticleImagesFromConnect[$imageUrl]['media'];
261
262
                    // add new mapping
263
                    $mapping = new Image\Mapping();
264
                    $mapping->setImage($articleImage);
265
                    foreach ($detail->getConfiguratorOptions() as $option) {
266
                        $rule = new Image\Rule();
267
                        $rule->setMapping($mapping);
268
                        $rule->setOption($option);
269
                        $mapping->getRules()->add($rule);
270
                    }
271
                    $this->manager->persist($mapping);
272
                    // mapping should have id, because it should be stored as child image attribute
273
                    $this->manager->flush($mapping);
274
                    $articleImage->getMappings()->add($mapping);
275
276
                    // add child image
277
                    $childImage = new Image();
278
                    $childImage->setMain(2);
279
                    $childImage->setPosition($maxPosition + $key + 1);
280
                    $childImage->setParent($articleImage);
281
                    $childImage->setArticleDetail($detail);
282
                    $childImage->setExtension($articleMedia->getExtension());
283
                    $childImageAttribute = $childImage->getAttribute() ?: new ImageAttribute();
284
                    $childImageAttribute->setArticleImage($childImage);
285
                    $childImageAttribute->setConnectDetailMappingId($mapping->getId());
286
287
                    $detail->getImages()->add($childImage);
288
                    $articleImage->getChildren()->add($childImage);
289
290
                    $this->manager->persist($childImage);
291
                    $this->manager->persist($childImageAttribute);
292
                    $this->manager->persist($articleImage);
293
294
                    continue;
295
                }
296
297
                // 3) if it doesn't exist, import it
298
                $importedImages = $this->importImages([$imageUrl => $key], $article, $maxPosition);
299
                $image = reset($importedImages);
300
                $media = $image->getMedia();
301
302
                // add new mapping
303
                $mapping = new Image\Mapping();
304
                $mapping->setImage($image);
305
                foreach ($detail->getConfiguratorOptions() as $option) {
306
                    $rule = new Image\Rule();
307
                    $rule->setMapping($mapping);
308
                    $rule->setOption($option);
309
                    $rules = $mapping->getRules();
310
                    $rules->add($rule);
311
                    $mapping->setRules($rules);
312
                    $this->manager->persist($rule);
313
                }
314
                $this->manager->persist($mapping);
315
                // mapping should have id, because it should be stored as child image attribute
316
                $this->manager->flush($mapping);
317
318
                $mappings = $image->getMappings();
319
                $mappings->add($mapping);
320
                $image->setMappings($mappings);
321
322
                // add child image
323
                $childImage = new Image();
324
                $childImage->setMain(2);
325
                $childImage->setPosition($maxPosition + $key + 1);
326
                $childImage->setParent($image);
327
                $childImage->setArticleDetail($detail);
328
                $childImage->setExtension($media->getExtension());
329
                $childImageAttribute = $childImage->getAttribute() ?: new ImageAttribute();
330
                $childImageAttribute->setArticleImage($childImage);
331
                $childImageAttribute->setConnectDetailMappingId($mapping->getId());
332
                $detail->getImages()->add($childImage);
333
334
                $image->getChildren()->add($childImage);
335
336
                $this->manager->persist($childImage);
337
                $this->manager->persist($childImageAttribute);
338
                $this->manager->persist($image);
339
340
                $this->thumbnailManager->createMediaThumbnail(
341
                    $media,
342
                    $this->getThumbnailSize($album),
343
                    true
344
                );
345
            }
346
        } catch (\Exception $e) {
347
            // log exception message if for some reason
348
            // image import fails
349
            $this->logger->write(true, 'Import images', $e->getMessage());
350
        }
351
352
        $article->setImages($articleImages);
353
        $this->manager->persist($article);
354
        $this->manager->flush();
355
    }
356
357
    /**
358
     * Helper: Read images for a given detail
359
     *
360
     * @param int $articleDetailId
361
     * @return array
362
     */
363
    public function getImagesForDetail($articleDetailId)
364
    {
365
        $builder = $this->manager->createQueryBuilder();
366
        $builder->select('media.path')
367
            ->from('Shopware\Models\Article\Image', 'images')
368
            ->join('images.media', 'media')
369
            ->where('images.articleDetailId = :articleDetailId')
370
            ->andWhere('images.parentId IS NULL')
371
            ->setParameter('articleDetailId', $articleDetailId)
372
            ->orderBy('images.main', 'ASC')
373
            ->addOrderBy('images.position', 'ASC');
374
375
        return array_map(function ($image) {
376
            return $image['path'];
377
        },
378
            $builder->getQuery()->getArrayResult()
379
        );
380
    }
381
382
    /**
383
     * Download, import and assign images to article
384
     *
385
     * @param array $imagesToCreate
386
     * @param Article|Detail $model
387
     * @param null|int $maxPosition
388
     * @throws \Doctrine\ORM\ORMException
389
     * @throws \Doctrine\ORM\OptimisticLockException
390
     * @throws \Doctrine\ORM\TransactionRequiredException
391
     * @throws \Exception
392
     * @return \Shopware\Models\Article\Image
393
     */
394
    private function importImages(array $imagesToCreate, $model, $maxPosition = null)
395
    {
396
        if (!$maxPosition) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $maxPosition of type null|integer is loosely compared to false; this is ambiguous if the integer can be zero. You might want to explicitly use === null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
397
            $positions = [];
398
            foreach ($model->getImages() as $image) {
399
                $positions[] = $image->getPosition();
400
            }
401
            $maxPosition = count($positions) > 0 ? max($positions) : 0;
402
        }
403
404
        if ($model instanceof Detail) {
0 ignored issues
show
Bug introduced by
The class Shopware\Models\Article\Detail does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
405
            $article = $model->getArticle();
406
        } elseif ($model instanceof Article) {
0 ignored issues
show
Bug introduced by
The class Shopware\Models\Article\Article does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
407
            $article = $model;
408
        } else {
409
            throw new \RuntimeException('Model must be instance of Article or Detail!');
410
        }
411
412
        // If there is no main image set first image as main image
413
        $hasMainImage = $this->hasArticleMainImage($article->getId());
414
        $importedImages = [];
415
        /** @var \Shopware\Models\Media\Album $album */
416
        $album = $this->manager->find('Shopware\Models\Media\Album', -1);
417
        $tempDir = Shopware()->DocPath('media_temp');
418
        foreach ($imagesToCreate as $imageUrl => $key) {
419
            $tempFile = tempnam($tempDir, 'image');
420
            copy($imageUrl, $tempFile);
421
            $file = new File($tempFile);
422
423
            // Create the media object
424
            $media = new Media();
425
            $media->setAlbum($album);
426
            $media->setDescription('');
427
            $media->setCreated(new \DateTime());
428
            $media->setUserId(0);
429
            $media->setFile($file);
430
431
            $mediaAttribute = $media->getAttribute() ?: new MediaAttribute();
432
            $mediaAttribute->setConnectHash($imageUrl);
433
            $mediaAttribute->setMedia($media);
434
            $media->setAttribute($mediaAttribute);
435
            $this->manager->persist($media);
436
            $this->manager->persist($mediaAttribute);
437
438
            // Create the associated image object
439
            $image = new Image();
440
            $image->setMain((!$hasMainImage && $key == 0) ? 1 : 2);
441
            $image->setMedia($media);
442
            $image->setPosition($maxPosition + $key + 1);
443
            $image->setArticle($article);
444
            $image->setPath($media->getName());
445
            $image->setExtension($media->getExtension());
446
447
            $article->getImages()->add($image);
448
449
            $this->manager->persist($image);
450
451
            $this->thumbnailManager->createMediaThumbnail(
452
                $media,
453
                $this->getThumbnailSize($album),
454
                true
455
            );
456
457
            $importedImages[] = $image;
458
        }
459
460
        return $importedImages;
461
    }
462
463
    /**
464
     * Returns a list with already imported images from Connect
465
     * by given Article or Detail
466
     *
467
     * @param Article|Detail $model
468
     * @return array
469
     */
470
    private function getImportedImages($model)
471
    {
472
        if (!$model instanceof Article && !$model instanceof Detail) {
0 ignored issues
show
Bug introduced by
The class Shopware\Models\Article\Article does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
Bug introduced by
The class Shopware\Models\Article\Detail does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
473
            throw new \RuntimeException('Model must be instance of Article or Detail!');
474
        }
475
476
        $localArticleImagesFromConnect = [];
477
478
        /** @var \Shopware\Models\Article\Image $image */
479
        foreach ($model->getImages() as $image) {
480
            if ($model instanceof Detail && $model->getId() == $image->getArticleDetail()->getId()) {
0 ignored issues
show
Bug introduced by
The class Shopware\Models\Article\Detail does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
481
                $image = $image->getParent();
482
            }
483
            $media = $image->getMedia();
484
485
            try {
486
                if (!$media || !$media->getAttribute()) {
487
                    continue;
488
                }
489
                $attribute = $media->getAttribute();
490
            } catch (\Doctrine\ORM\EntityNotFoundException $e) {
0 ignored issues
show
Bug introduced by
The class Doctrine\ORM\EntityNotFoundException does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
491
                //is thrown if media was deleted -> simply continue
492
                continue;
493
            }
494
495
            // If the image was not imported from connect, skip it
496
            $connectHash = $attribute->getConnectHash();
497
            if (!$connectHash) {
498
                continue;
499
            }
500
            $localArticleImagesFromConnect[$connectHash] = ['image' => $image, 'media' => $media];
501
        }
502
503
        return $localArticleImagesFromConnect;
504
    }
505
506
    /**
507
     * @param $imageUrl
508
     * @param Supplier $supplier
509
     */
510
    public function importImageForSupplier($imageUrl, Supplier $supplier)
511
    {
512
        try {
513
            $album = $this->manager->find('Shopware\Models\Media\Album', -12);
514
            $tempDir = Shopware()->DocPath('media_temp');
515
516
            $tempFile = tempnam($tempDir, 'image');
517
            copy($imageUrl, $tempFile);
518
            $file = new File($tempFile);
519
520
            $media = new Media();
521
            $media->setAlbum($album);
522
            $media->setDescription('');
523
            $media->setCreated(new \DateTime());
524
            $media->setUserId(0);
525
            $media->setFile($file);
526
527
            $this->manager->persist($media);
528
529
            $this->thumbnailManager->createMediaThumbnail(
530
                $media,
531
                $this->getThumbnailSize($album),
532
                true
533
            );
534
535
            $supplier->setImage($media->getPath());
536
            $this->manager->persist($supplier);
537
538
            $this->manager->flush();
539
        } catch (\Exception $e) {
540
            $this->logger->write(
541
                true,
542
                'import image for supplier',
543
                $e->getMessage() . 'imageUrl:' . $imageUrl
544
            );
545
        }
546
    }
547
548
    /**
549
     * Returns thumbnails size by album
550
     * @param $album \Shopware\Models\Media\Album
551
     * @return array
552
     */
553
    protected function getThumbnailSize($album)
554
    {
555
        if (!$album->getId()) {
556
            return;
557
        }
558
559
        $thumbnailSizes = $album->getSettings()->getThumbnailSize();
560
        $sizesArray = [];
561
        $requiredSizeExists = false;
562
        foreach ($thumbnailSizes as $size) {
563
            if (strlen($size) == 0) {
564
                continue;
565
            }
566
567
            $sizes = explode('x', $size);
568
            if ($sizes[0] == 140 && $sizes[1] == 140) {
569
                $requiredSizeExists = true;
570
            }
571
            $sizesArray[] = $size;
572
        }
573
574
        if ($requiredSizeExists === false) {
575
            $sizesArray[] = '140x140';
576
        }
577
578
        return $sizesArray;
579
    }
580
581
    /**
582
     * @param $imageUrl string
583
     * @param $articleId int
584
     */
585
    public function importMainImage($imageUrl, $articleId)
586
    {
587
        $oldMainImageId = $this->manager->getConnection()->fetchColumn('SELECT id FROM s_articles_img WHERE articleID = ? AND main = 1 AND parent_id IS NULL',
588
            [$articleId]);
589
590
        $newMainImageId = $this->manager->getConnection()->fetchColumn('
591
            SELECT s_articles_img.id 
592
            FROM s_articles_img 
593
            INNER JOIN s_media ON s_articles_img.media_id = s_media.id
594
            INNER JOIN s_media_attributes ON s_media.id = s_media_attributes.mediaID
595
            WHERE s_articles_img.articleID = ? AND s_articles_img.parent_id IS NULL AND s_media_attributes.connect_hash = ?',
596
            [$articleId, $imageUrl]);
597
598
        if ($newMainImageId && $newMainImageId !== $oldMainImageId) {
599
            $this->manager->getConnection()->executeQuery('
600
            UPDATE s_articles_img SET main = ? WHERE id = ?',
601
            [0, $oldMainImageId]);
602
            $this->manager->getConnection()->executeQuery('
603
            UPDATE s_articles_img SET main = ? WHERE id = ?',
604
             [1, $newMainImageId]);
605
        }
606
    }
607
608
    /**
609
     * @param $imageUrl string
610
     * @param $articleId int
611
     * @return bool
612
     */
613
    public function hasMainImageChanged($imageUrl, $articleId)
614
    {
615
        $result = $this->manager->getConnection()->fetchColumn('
616
            SELECT s_articles_img.id 
617
            FROM s_articles_img 
618
            INNER JOIN s_media ON s_articles_img.media_id = s_media.id
619
            INNER JOIN s_media_attributes ON s_media.id = s_media_attributes.mediaID
620
            WHERE s_articles_img.articleID = ? AND s_articles_img.main = 1 AND s_articles_img.parent_id IS NULL AND s_media_attributes.connect_hash = ?',
621
            [$articleId, $imageUrl]);
622
623
        return !(bool) $result;
624
    }
625
}
626