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

Images::getImagesEans()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 2
c 1
b 0
f 0
nc 1
nop 0
dl 0
loc 4
rs 10
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
        $this->logger->info('EANs to be processed: '.count($eans));
115
        try {
116
            // if still need to process eans:
117
            if(count($eans) > 0) {
118
                $client = $this->stockbaseClientFactory->create();
119
                $images = $client->getImages($eans);
120
                // validate returned images:
121
                if(is_array($images->{'Items'}) && count($images->{'Items'}) > 0) {
122
                    // download and save the images locally:
123
                    $this->saveImageForProduct($images->{'Items'});
124
                    // update the processed images configuration:
125
                    $processedEans = array_merge($processedEans, $eans);
126
                    $encodedEans = json_encode($processedEans);
127
                    $this->saveImagesEans($encodedEans);
128
                    $this->logger->info('New images synchronized.');
129
                }
130
            }
131
        } 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...
132
            $this->logger->info('Cron runImageImport error: '.$e->getMessage());
133
            return false;
134
        }
135
        $this->logger->info('Stockbase images synchronization complete.');
136
    }
137
138
    /**
139
     * @return array
140
     */
141
    private function getAllEans()
142
    {
143
        // found eans:
144
        $eans = array();
145
        $this->logger->info('Get All EANs process');
146
        // get ean attribute:
147
        $attribute = $this->config->getEanFieldName();
148
        if($attribute) {
149
            // apply filters and paginate by 100:
150
            $collection = $this->productCollection->create()
151
                ->addAttributeToSelect($attribute)
152
                ->addAttributeToSelect('stockbase_product')
153
                ->addAttributeToFilter('stockbase_product', array('eq' => '1')) // stockbase product.
154
                ->addAttributeToFilter($attribute, array('notnull' => true, 'neq' => '')) // not null and not empty.
155
                ->setPageSize(100);
156
            // iterate over the pages:
157
            $currentPage = 0;
158
            $lastPage = $collection->getLastPageNumber();
159
            while ($currentPage < $lastPage) {
160
                // load the data of this page in a single query:
161
                $collection->setCurPage(++$currentPage);
162
                $collection->load();
163
                // iterate over the products:
164
                foreach ($collection as $product) {
165
                    $ean = $product->getData($attribute);
166
                    if ($ean) {
167
                        // add the ean if this product has one:
168
                        $eans[] = $ean;
169
                    }
170
                }
171
            }
172
            $this->logger->info('Found EANs: '.count($eans));
173
        } else {
174
            $this->logger->info('Please setup the EAN attribute.');
175
        }
176
        return $eans;
177
    }
178
179
    /**
180
     * Saves images array from stockbase for given $ean
181
     *
182
     * @param array $images
183
     *
184
     * @return bool
185
     */
186
    private function saveImageForProduct($images)
187
    {
188
        $this->logger->info('Save images process:');
189
        // get product model:
190
        $productModel = $this->product;
191
        // get ean attribute:
192
        $eanField = $this->config->getEanFieldName();
193
        // get client:
194
        $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...
195
        // loop images:
196
        foreach ($images as $image) {
197
            $this->logger->info('Image URL: '.$image->{'Url'});
198
            // load product by ean:
199
            $product = $productModel->loadByAttribute($eanField, $image->EAN);
200
            // continue looping if we do not have product:
201
            if (!$product) {
202
                continue;
203
            }
204
            // get image from stockbase:
205
            $stockbaseImage = (string)$image->{'Url'};
206
            // create temporal folder if it is not exists:
207
            $tmpDir = $this->getMediaDirTmpDir();
208
            $this->file->checkAndCreateFolder($tmpDir);
209
            // get new file path:
210
            $newFileName = $tmpDir . baseName($image->{'Url'});
211
            // read file from URL and copy it to the new destination:
212
            $result = $this->file->read($stockbaseImage, $newFileName);
213
            if ($result) {
214
                if ($product->getMediaGallery() == null) {
215
                    $product->setMediaGallery(array('images' => array(), 'values' => array()));
216
                }
217
                // add saved file to the $product gallery:
218
                $product->addImageToMediaGallery(
219
                    $newFileName,
220
                    array('image', 'small_image', 'thumbnail'),
221
                    false,
222
                    false
223
                );
224
                // save product:
225
                $product->save();
226
                $this->logger->info('Product saved.');
227
            } else {
228
                $this->logger->info('Can not read the image: '.$stockbaseImage);
229
            }
230
        }
231
        return true;
232
    }
233
234
    /**
235
     * Media directory name for the temporary file storage
236
     * pub/media/tmp
237
     *
238
     * @return string
239
     */
240
    private function getMediaDirTmpDir()
241
    {
242
        return $this->directoryList->getPath(DirectoryList::MEDIA) . DIRECTORY_SEPARATOR . 'tmp';
243
    }
244
245
    /**
246
     * @return mixed
247
     */
248
    private function getImagesEans()
249
    {
250
        return $this->config->getImagesEans();
251
    }
252
253
    /**
254
     * @param $eans
255
     */
256
    private function saveImagesEans($eans)
257
    {
258
        $this->config->saveImagesEans($eans);
259
    }
260
261
}
262