Images   A
last analyzed

Complexity

Total Complexity 12

Size/Duplication

Total Lines 169
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 4

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
dl 0
loc 169
ccs 0
cts 62
cp 0
rs 10
c 0
b 0
f 0
wmc 12
lcom 1
cbo 4

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 17 1
C saveProductImages() 0 91 10
A getMediaDirTmpDir() 0 4 1
1
<?php
2
3
namespace Stockbase\Integration\Helper;
4
5
use Psr\Log\LoggerInterface;
6
use Magento\Framework\App\Filesystem\DirectoryList;
7
use Magento\Framework\Filesystem\Io\File;
8
use Magento\Catalog\Model\Product as ProductModel;
9
use Stockbase\Integration\Model\ProductImage;
10
use Stockbase\Integration\Model\ResourceModel\ProductImage as ProductImageResource;
11
use Stockbase\Integration\Model\Config\StockbaseConfiguration;
12
use Stockbase\Integration\StockbaseApi\Client\StockbaseClient;
13
14
/**
15
 *
16
 * Stockbase images helper.
17
 *
18
 * Class Images
19
 * @package Stockbase\Integration\Helper
20
 */
21
class Images
22
{
23
    /**
24
     * @var LoggerInterface
25
     */
26
    private $logger;
27
    /**
28
     * @var DirectoryList
29
     */
30
    private $directoryList;
31
    /**
32
     * @var File
33
     */
34
    private $file;
35
    /**
36
     * @var ProductImage
37
     */
38
    private $productImage;
39
    /**
40
     * @var ProductImageResource
41
     */
42
    private $productImageResource;
43
    /**
44
     * @var ProductModel
45
     */
46
    private $product;
47
    /**
48
     * @var StockbaseConfiguration
49
     */
50
    private $config;
51
52
    /**
53
     * Images constructor.
54
     * @param LoggerInterface        $logger
55
     * @param StockbaseConfiguration $config
56
     * @param ProductImage           $productImage
57
     * @param ProductImageResource   $productImageResource
58
     * @param ProductModel           $product
59
     * @param DirectoryList          $directoryList
60
     * @param File                   $file
61
     */
62
    public function __construct(
63
        LoggerInterface $logger,
64
        StockbaseConfiguration $config,
65
        ProductImage $productImage,
66
        ProductImageResource $productImageResource,
67
        ProductModel $product,
68
        DirectoryList $directoryList,
69
        File $file
70
    ) {
71
        $this->logger = $logger;
72
        $this->config = $config;
73
        $this->productImage = $productImage;
74
        $this->productImageResource = $productImageResource;
75
        $this->product = $product;
76
        $this->directoryList = $directoryList;
77
        $this->file = $file;
78
    }
79
80
    /**
81
     * Saves images array from stockbase for given $ean
82
     *
83
     * @param array           $images
84
     * @param StockbaseClient $client
85
     * @return bool
86
     */
87
    public function saveProductImages($images, StockbaseClient $client)
88
    {
89
        $this->logger->debug('Save images process:');
90
        $newImagesCount = 0;
91
        // get product model:
92
        $productModel = $this->product;
93
        // get ean attribute:
94
        $eanField = $this->config->getEanFieldName();
95
        // loop images:
96
        foreach ($images as $image) {
97
            $this->logger->debug('Image URL: '.$image->{'Url'}.' - EAN: '.$image->EAN);
98
            // load product by ean:
99
            $product = $productModel->loadByAttribute($eanField, $image->EAN);
100
            // continue looping if we do not have product:
101
            if (!$product) {
102
                $this->logger->debug('Product not found for EAN: '.$image->EAN);
103
                continue;
104
            }
105
            $this->logger->debug('Loaded product: '.$product->getId());
106
            if (!$product->getData('stockbase_product')) {
107
                $this->logger->debug('The Product is not mark as Stockbase product: '.$product->getId());
108
                continue;
109
            }
110
            // stockbase image:
111
            $stockbaseImage = (string) $image->{'Url'};
112
            // image name:
113
            $fileInfo = $this->file->getPathInfo($image->{'Url'});
114
            $imageName = $fileInfo['basename'];
115
            // check if the image exists:
116
            $imageCollection = $this->productImageResource->imageExists($imageName, $product->getId(), $image->EAN);
117
            if (count($imageCollection) > 0) {
118
                $this->logger->debug('The image '.$imageName.' is already synchronized for product '.$product->getId());
119
                continue;
120
            }
121
            // create temporal folder if it is not exists:
122
            $tmpDir = $this->getMediaDirTmpDir();
123
            $this->file->checkAndCreateFolder($tmpDir);
124
            // get new file path:
125
            $newFileName = $tmpDir.$imageName;
126
            // if the image file is not in our system:
127
            if (!$this->file->fileExists($newFileName)) {
128
                // read file from URL and copy it to the new destination:
129
                //$this->file->read($stockbaseImage, $newFileName);
130
                $client->downloadImage($stockbaseImage, $newFileName);
131
                $this->logger->debug('New image saved: '.$newFileName);
132
            }
133
            // if the process worked then the file should be there now:
134
            if ($this->file->fileExists($newFileName)) {
135
                // if product gallery is empty the set the default values:
136
                $mediaGallery = $product->getMediaGallery();
137
                if (!$mediaGallery) {
138
                    $product->setMediaGallery([
139
                        'images' => [],
140
                        'values' => [],
141
                    ]);
142
                } else {
143
                    // if the product has a gallery and the image is already there then continue with the next one:
144
                    if (is_array($mediaGallery['images']) && in_array($imageName, $mediaGallery['images'])) {
145
                        continue;
146
                    }
147
                }
148
                // add saved file into the product gallery:
149
                $product->addImageToMediaGallery(
150
                    $newFileName,
151
                    array('image', 'small_image', 'thumbnail'),
152
                    false,
153
                    false
154
                );
155
                // save product:
156
                $product->save();
157
                // save image in relation table:
158
                $imageModel = clone($this->productImage);
159
                // image data:
160
                $imageData = [
161
                    'ean' => $image->EAN,
162
                    'product_id' => $product->getId(),
163
                    'image' => $imageName,
164
                    'timestamp' => date('Y-m-d H:i:s'),
165
                ];
166
                // save:
167
                $imageModel->setData($imageData)->save();
168
                // end process.
169
                $this->logger->debug('Product saved.');
170
                $newImagesCount++;
171
            } else {
172
                $this->logger->debug('There is an issue with the image: '.$newFileName);
173
            }
174
        }
175
        
176
        return $newImagesCount;
177
    }
178
179
    /**
180
     * Media directory name for the temporary file storage
181
     * pub/media/tmp
182
     *
183
     * @return string
184
     */
185
    private function getMediaDirTmpDir()
186
    {
187
        return $this->directoryList->getPath(DirectoryList::MEDIA).DIRECTORY_SEPARATOR.'tmp';
188
    }
189
}
190