Completed
Pull Request — master (#1)
by
unknown
12:33
created

Images::saveImageForProduct()   B

Complexity

Conditions 5
Paths 5

Size

Total Lines 45
Code Lines 26

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 5
eloc 26
c 1
b 0
f 0
nc 5
nop 1
dl 0
loc 45
rs 8.439
1
<?php
2
3
namespace Stockbase\Integration\Cron;
4
5
use Magento\Framework\ObjectManagerInterface;
6
use Psr\Log\LoggerInterface;
7
use Stockbase\Integration\StockbaseApi\Client\StockbaseClientFactory;
8
use Stockbase\Integration\Model\Config\StockbaseConfiguration;
9
use Stockbase\Integration\Model\ResourceModel\StockItem as StockItemResource;
10
use Magento\Catalog\Model\ResourceModel\Product\CollectionFactory as ProductCollection;
11
use Magento\Catalog\Model\Product as ProductModel;
12
use Magento\Framework\Url as UrlHelper;
13
use Magento\Framework\App\Filesystem\DirectoryList;
14
use Magento\Framework\Filesystem\Io\File;
15
16
/**
17
 * Stockbase images synchronization cron job.
18
 */
19
class Images
20
{
21
22
    /**
23
     * @var LoggerInterface
24
     */
25
    private $logger;
26
    /**
27
     * @var StockbaseClientFactory
28
     */
29
    private $stockbaseClientFactory;
30
    /**
31
     * @var ObjectManagerInterface
32
     */
33
    private $objectManager;
34
    /**
35
     * @var StockbaseConfiguration
36
     */
37
    private $config;
38
    /**
39
     * @var ProductCollection
40
     */
41
    private $productCollection;
42
    /**
43
     * @var ProductModel
44
     */
45
    private $product;
46
    /**
47
     * @var UrlHelper
48
     */
49
    private $urlHelper;
50
    /**
51
     * Directory List
52
     *
53
     * @var DirectoryList
54
     */
55
    private $directoryList;
56
    /**
57
     * File interface
58
     *
59
     * @var File
60
     */
61
    private $file;
62
    
63
    /**
64
     * Images constructor.
65
     * @param LoggerInterface $logger
66
     * @param ObjectManagerInterface $objectManager
67
     * @param StockbaseClientFactory $stockbaseClientFactory
68
     * @param StockbaseConfiguration $config
69
     * @param ProductCollection $productCollection
70
     * @param ProductModel $product
71
     * @param UrlHelper $urlHelper
72
     * @param DirectoryList $directoryList
73
     * @param File $file
74
     */
75
    public function __construct(
76
        LoggerInterface $logger,
77
        ObjectManagerInterface $objectManager,
78
        StockbaseClientFactory $stockbaseClientFactory,
79
        StockbaseConfiguration $config,
80
        ProductCollection $productCollection,
81
        ProductModel $product,
82
        UrlHelper $urlHelper,
83
        DirectoryList $directoryList,
84
        File $file
85
    ) {
86
        $this->logger = $logger;
87
        $this->stockbaseClientFactory = $stockbaseClientFactory;
88
        $this->objectManager = $objectManager;
89
        $this->config = $config;
90
        $this->productCollection = $productCollection;
91
        $this->product = $product;
92
        $this->urlHelper = $urlHelper;
93
        $this->directoryList = $directoryList;
94
        $this->file = $file;
95
    }
96
97
    /**
98
     * Executes the job.
99
     */
100
    public function execute()
101
    {
102
        // validate configuration:
103
        if (!$this->config->isModuleEnabled() || !$this->config->isImagesSyncEnabled()) {
104
            return;
105
        }
106
        // start process:
107
        $this->logger->info('Synchronizing Stockbase images...');
108
        // get all the eans:
109
        $allEans = $this->getAllEans();
110
        // get processed eans:
111
        $processedEans = json_decode($this->getImagesEans()) ?: array();
112
        // process 100 unprocessed eans at a time:
113
        $eans = array_slice(array_diff($allEans, $processedEans), 0, 100);
114
        try {
115
            $client = $this->stockbaseClientFactory->create();
116
            $images = $client->getImages($eans);
117
        } catch (Exception $e) {
0 ignored issues
show
Bug introduced by
The class Stockbase\Integration\Cron\Exception 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...
118
            $this->logger->info('Cron runImageImport error: '.$e->getMessage());
119
            return false;
120
        }
121
        // validate returned images:
122
        if(is_array($images->{'Items'}) && count($images->{'Items'})>0) {
123
            // download and save the images locally:
124
            $this->saveImageForProduct($images->{'Items'});
125
            // update the processed images configuration:
126
            $processedEans = array_merge($processedEans, $eans);
127
            $encodedEans = json_encode($processedEans);
128
            $this->saveImagesEans($encodedEans);
129
            $this->logger->info('New images synchronized.');
130
        }
131
        $this->logger->info('Stockbase images synchronization complete.');
132
    }
133
134
    /**
135
     * @return array
136
     */
137
    private function getAllEans()
138
    {
139
        $this->logger->info('Get All EANs process');
140
        // get ean attribute:
141
        $attribute = $this->config->getEanFieldName();
142
        if($attribute) {
143
            // apply filters and paginate by 100:
144
            $collection = $this->productCollection->create()
145
                ->addAttributeToSelect($attribute)
146
                ->addAttributeToFilter($attribute, array('notnull' => true, 'neq' => '')) // not null and not empty.
147
                ->setPageSize(100);
148
            // iterate over the pages:
149
            $eans = array();
150
            $currentPage = 0;
151
            $lastPage = $collection->getLastPageNumber();
152
            while ($currentPage < $lastPage) {
153
                // load the data of this page in a single query:
154
                $collection->setCurPage(++$currentPage);
155
                $collection->load();
156
                // iterate over the products:
157
                foreach ($collection as $product) {
158
                    $ean = $product->getData($attribute);
159
                    if ($ean) {
160
                        // add the ean if this product has one:
161
                        $eans[] = $ean;
162
                    }
163
                }
164
            }
165
            $this->logger->info('Found EANs: '.count($eans));
166
            return $eans;
167
        } else {
168
            $this->logger->info('Please setup the EAN attribute.');
169
        }
170
    }
171
172
    /**
173
     * Saves images array from stockbase for given $ean
174
     *
175
     * @param array $images
176
     *
177
     * @return bool
178
     */
179
    private function saveImageForProduct($images)
180
    {
181
        $this->logger->info('Save images process:');
182
        // get product model:
183
        $productModel = $this->product;
184
        // get ean attribute:
185
        $eanField = $this->config->getEanFieldName();
186
        // get client:
187
        $client = $this->stockbaseClientFactory->create();
0 ignored issues
show
Unused Code introduced by
$client is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
188
        // loop images:
189
        foreach ($images as $image) {
190
            $this->logger->info($image->{'Url'});
191
            // load product by ean:
192
            $product = $productModel->loadByAttribute($eanField, $image->EAN);
193
            // continue looping if we do not have product:
194
            if (!$product) {
195
                continue;
196
            }
197
            // get image from stockbase:
198
            $stockbaseImage = (string)$image->{'Url'};
199
            // create temporal folder if it is not exists:
200
            $tmpDir = $this->getMediaDirTmpDir();
201
            $this->file->checkAndCreateFolder($tmpDir);
202
            // get new file path:
203
            $newFileName = $tmpDir . baseName($image->{'Url'});
204
            // read file from URL and copy it to the new destination:
205
            $result = $this->file->read($stockbaseImage, $newFileName);
206
            if ($result) {
207
                if ($product->getMediaGallery() == null) {
208
                    $product->setMediaGallery(array('images' => array(), 'values' => array()));
209
                }
210
                // add saved file to the $product gallery:
211
                $product->addImageToMediaGallery(
212
                    $newFileName,
213
                    array('image', 'small_image', 'thumbnail'),
214
                    false,
215
                    false
216
                );
217
                // save product:
218
                $product->{'save'}();
219
                $this->logger->info('Saved.');
220
            }
221
        }
222
        return true;
223
    }
224
225
    /**
226
     * Media directory name for the temporary file storage
227
     * pub/media/tmp
228
     *
229
     * @return string
230
     */
231
    private function getMediaDirTmpDir()
232
    {
233
        return $this->directoryList->getPath(DirectoryList::MEDIA) . DIRECTORY_SEPARATOR . 'tmp';
234
    }
235
236
    /**
237
     * @return mixed
238
     */
239
    private function getImagesEans()
240
    {
241
        return $this->config->getImagesEans();
242
    }
243
244
    /**
245
     * @param $eans
246
     */
247
    private function saveImagesEans($eans)
248
    {
249
        $this->config->saveImagesEans($eans);
250
    }
251
252
}
253