Completed
Pull Request — master (#398)
by Stefan
02:43
created

CronJob::importImages()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 7
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 4
nc 1
nop 1
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\Subscribers;
9
10
use Enlight\Event\SubscriberInterface;
11
use Shopware\Connect\SDK;
12
use Shopware\CustomModels\Connect\Attribute;
13
use Shopware\Models\ProductStream\ProductStream;
14
use ShopwarePlugins\Connect\Components\Config;
15
use ShopwarePlugins\Connect\Components\ErrorHandler;
16
use ShopwarePlugins\Connect\Components\Helper;
17
use ShopwarePlugins\Connect\Components\ImageImport;
18
use ShopwarePlugins\Connect\Components\Logger;
19
use ShopwarePlugins\Connect\Components\ConnectExport;
20
use ShopwarePlugins\Connect\Components\ProductStream\ProductSearch;
21
use ShopwarePlugins\Connect\Components\ProductStream\ProductStreamService;
22
use Shopware\Components\DependencyInjection\Container;
23
24
/**
25
 * Cronjob callback
26
 *
27
 * Class CronJob
28
 * @package ShopwarePlugins\Connect\Subscribers
29
 */
30
class CronJob implements SubscriberInterface
31
{
32
    /**
33
     * @var \ShopwarePlugins\Connect\Components\Config
34
     */
35
    private $configComponent;
36
37
    /**
38
     * @var SDK
39
     */
40
    protected $sdk;
41
42
    /**
43
     * @var ProductStreamService
44
     */
45
    protected $streamService;
46
47
    /**
48
     * @var ConnectExport
49
     */
50
    protected $connectExport;
51
52
    /**
53
     * @var Helper
54
     */
55
    private $helper;
56
57
    /**
58
     * @var ProductSearch
59
     */
60
    private $productSearch;
61
62
    /**
63
     * @var Container
64
     */
65
    private $container;
66
67
    /**
68
     * @param SDK $sdk
69
     * @param ConnectExport $connectExport
70
     * @param Config $configComponent
71
     * @param Container $container
72
     */
73 View Code Duplication
    public function __construct(
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
74
        SDK $sdk,
75
        ConnectExport $connectExport,
76
        Config $configComponent,
77
        Helper $helper,
78
        Container $container
79
    ) {
80
        $this->connectExport = $connectExport;
81
        $this->sdk = $sdk;
82
        $this->configComponent = $configComponent;
83
        $this->helper = $helper;
84
        $this->container = $container;
85
    }
86
87
    /**
88
     * {@inheritdoc}
89
     */
90
    public static function getSubscribedEvents()
91
    {
92
        return [
93
            'Shopware_CronJob_ShopwareConnectImportImages' => 'importImages',
94
            'Shopware_CronJob_ShopwareConnectUpdateProducts' => 'updateProducts',
95
            'Shopware_CronJob_ConnectExportDynamicStreams' => 'exportDynamicStreams',
96
        ];
97
    }
98
99
    /**
100
     * @return ImageImport
101
     */
102
    public function getImageImport()
103
    {
104
        return new ImageImport(
105
            Shopware()->Models(),
106
            $this->helper,
107
            $this->container->get('thumbnail_manager'),
108
            new Logger(Shopware()->Db())
109
        );
110
    }
111
112
    /**
113
     * Import images of new products
114
     *
115
     * @param \Shopware_Components_Cron_CronJob $job
116
     * @return bool
117
     */
118
    public function importImages(\Shopware_Components_Cron_CronJob $job)
119
    {
120
        $limit = $this->configComponent->getConfig('articleImagesLimitImport', 10);
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $limit is correct as $this->configComponent->...ImagesLimitImport', 10) (which targets ShopwarePlugins\Connect\...nts\Config::getConfig()) seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
121
        $this->getImageImport()->import($limit);
122
123
        return true;
124
    }
125
126
    /**
127
     * Collect all own products and send them
128
     * to Connect system.
129
     *
130
     * Used to update products with many variants.
131
     *
132
     * @param \Shopware_Components_Cron_CronJob $job
133
     * @return bool
134
     */
135
    public function updateProducts(\Shopware_Components_Cron_CronJob $job)
136
    {
137
        $sourceIds = Shopware()->Db()->fetchCol(
138
            'SELECT source_id FROM s_plugin_connect_items WHERE shop_id IS NULL AND cron_update = 1 LIMIT 100'
139
        );
140
141
        if (empty($sourceIds)) {
142
            return true;
143
        }
144
145
        $this->connectExport->export($sourceIds);
146
147
        $quotedSourceIds = Shopware()->Db()->quote($sourceIds);
148
        Shopware()->Db()->query("
149
            UPDATE s_plugin_connect_items
150
            SET cron_update = false
151
            WHERE source_id IN ($quotedSourceIds)"
152
        )->execute();
153
154
        return true;
155
    }
156
157
    /**
158
     * @param \Shopware_Components_Cron_CronJob $job
159
     */
160
    public function exportDynamicStreams(\Shopware_Components_Cron_CronJob $job)
161
    {
162
        /** @var ProductStreamService $streamService */
163
        $streamService = $this->getStreamService();
164
        $streams = $streamService->getAllExportedStreams(ProductStreamService::DYNAMIC_STREAM);
165
166
        /** @var ProductStream $stream */
167
        foreach ($streams as $stream) {
168
            $streamId = $stream->getId();
169
            $productSearchResult = $this->getProductSearch()->getProductFromConditionStream($stream);
170
            $orderNumbers = array_keys($productSearchResult->getProducts());
171
172
            //no products found
173
            if (!$orderNumbers) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $orderNumbers of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
174
                //removes all products from this stream
175
                $streamService->markProductsToBeRemovedFromStream($streamId);
176
            } else {
177
                $articleIds = $this->helper->getArticleIdsByNumber($orderNumbers);
178
179
                $streamService->markProductsToBeRemovedFromStream($streamId);
180
                $streamService->createStreamRelation($streamId, $articleIds);
181
            }
182
183
            try {
184
                $streamsAssignments = $streamService->prepareStreamsAssignments($streamId, false);
185
186
                //article ids must be taken from streamsAssignments
187
                $exportArticleIds = $streamsAssignments->getArticleIds();
188
189
                $removeArticleIds = $streamsAssignments->getArticleIdsWithoutStreams();
190
191
                if (!empty($removeArticleIds)) {
192
                    $this->removeArticlesFromStream($removeArticleIds);
193
194
                    //filter the $exportArticleIds
195
                    $exportArticleIds = array_diff($exportArticleIds, $removeArticleIds);
196
                }
197
198
                $sourceIds = $this->helper->getArticleSourceIds($exportArticleIds);
199
200
                $errorMessages = $this->connectExport->export($sourceIds, $streamsAssignments);
201
                $streamService->changeStatus($streamId, ProductStreamService::STATUS_EXPORT);
202
            } catch (\RuntimeException $e) {
203
                $streamService->changeStatus($streamId, ProductStreamService::STATUS_ERROR, $e->getMessage());
204
                continue;
205
            }
206
207
            if ($errorMessages) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $errorMessages of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
208
                $errorMessagesText = '';
209
                $displayedErrorTypes = [
210
                    ErrorHandler::TYPE_DEFAULT_ERROR,
211
                    ErrorHandler::TYPE_PRICE_ERROR
212
                ];
213
214
                foreach ($displayedErrorTypes as $displayedErrorType) {
215
                    $errorMessagesText .= implode('\n', $errorMessages[$displayedErrorType]);
216
                }
217
218
                $streamService->changeStatus($streamId, ProductStreamService::STATUS_ERROR, $errorMessagesText);
219
            }
220
        }
221
    }
222
223
    /**
224
     * If article is not taking part of any shopware stream it will be removed
225
     * @param array $articleIds
226
     */
227
    private function removeArticlesFromStream(array $articleIds)
228
    {
229
        $sourceIds = $this->helper->getArticleSourceIds($articleIds);
230
        $items = $this->connectExport->fetchConnectItems($sourceIds, false);
231
232
        foreach ($items as $item) {
233
            $this->sdk->recordDelete($item['sourceId']);
234
        }
235
236
        $this->getStreamService()->removeMarkedStreamRelations();
237
        $this->connectExport->updateConnectItemsStatus($sourceIds, Attribute::STATUS_DELETE);
238
    }
239
240
    /**
241
     * @return ProductStreamService $streamService
242
     */
243
    private function getStreamService()
244
    {
245
        if (!$this->streamService) {
246
            $this->streamService = $this->container->get('swagconnect.product_stream_service');
247
        }
248
249
        return $this->streamService;
250
    }
251
252
    /**
253
     * @return ProductSearch
254
     */
255
    private function getProductSearch()
256
    {
257
        if (!$this->productSearch) {
258
            // HACK
259
            // do not use as a dependency!!!
0 ignored issues
show
Unused Code Comprehensibility introduced by
40% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
260
            // this class uses Shopware product search which depends on shop context
261
            // so if it's used as dependency of subscriber, plugin returns error on deactivate
262
            // see CON-4922
263
            $this->productSearch = $this->container->get('swagconnect.product_search');
264
        }
265
266
        return $this->productSearch;
267
    }
268
}
269