Completed
Pull Request — master (#358)
by Stefan
02:49
created

CronJob::getSubscribedEvents()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 8
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 5
nc 1
nop 0
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\ProductStreamService;
21
22
class CronJob implements SubscriberInterface
23
{
24
    /**
25
     * @var \ShopwarePlugins\Connect\Components\Config
26
     */
27
    private $configComponent;
28
29
    /**
30
     * @var SDK
31
     */
32
    protected $sdk;
33
34
    /**
35
     * @var ProductStreamService
36
     */
37
    protected $streamService;
38
39
    /**
40
     * @var ConnectExport
41
     */
42
    protected $connectExport;
43
44
    /**
45
     * @var Helper
46
     */
47
    private $helper;
48
49
    /**
50
     * @param SDK $sdk
51
     * @param ConnectExport $connectExport
52
     * @param Config $configComponent
53
     */
54 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...
55
        SDK $sdk,
56
        ConnectExport $connectExport,
57
        Config $configComponent,
58
        Helper $helper
59
    ) {
60
        $this->connectExport = $connectExport;
61
        $this->sdk = $sdk;
62
        $this->configComponent = $configComponent;
63
        $this->helper = $helper;
64
    }
65
66
    /**
67
     * {@inheritdoc}
68
     */
69
    public static function getSubscribedEvents()
70
    {
71
        return [
72
            'Shopware_CronJob_ShopwareConnectImportImages' => 'importImages',
73
            'Shopware_CronJob_ShopwareConnectUpdateProducts' => 'updateProducts',
74
            'Shopware_CronJob_ConnectExportDynamicStreams' => 'exportDynamicStreams',
75
        ];
76
    }
77
78
    /**
79
     * @return ImageImport
80
     */
81
    public function getImageImport()
82
    {
83
        return new ImageImport(
84
            Shopware()->Models(),
85
            $this->helper,
86
            Shopware()->Container()->get('thumbnail_manager'),
87
            new Logger(Shopware()->Db())
88
        );
89
    }
90
91
    /**
92
     * Import images of new products
93
     *
94
     * @param \Shopware_Components_Cron_CronJob $job
95
     * @return bool
96
     */
97
    public function importImages(\Shopware_Components_Cron_CronJob $job)
98
    {
99
        $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...
100
        $this->getImageImport()->import($limit);
101
102
        return true;
103
    }
104
105
    /**
106
     * Collect all own products and send them
107
     * to Connect system.
108
     *
109
     * Used to update products with many variants.
110
     *
111
     * @param \Shopware_Components_Cron_CronJob $job
112
     * @return bool
113
     */
114
    public function updateProducts(\Shopware_Components_Cron_CronJob $job)
115
    {
116
        $sourceIds = Shopware()->Db()->fetchCol(
117
            'SELECT source_id FROM s_plugin_connect_items WHERE shop_id IS NULL AND cron_update = 1 LIMIT 100'
118
        );
119
120
        if (empty($sourceIds)) {
121
            return true;
122
        }
123
124
        $this->connectExport->export($sourceIds);
125
126
        $quotedSourceIds = Shopware()->Db()->quote($sourceIds);
127
        Shopware()->Db()->query("
128
            UPDATE s_plugin_connect_items
129
            SET cron_update = false
130
            WHERE source_id IN ($quotedSourceIds)"
131
        )->execute();
132
133
        return true;
134
    }
135
136
    /**
137
     * @param \Shopware_Components_Cron_CronJob $job
138
     */
139
    public function exportDynamicStreams(\Shopware_Components_Cron_CronJob $job)
140
    {
141
        /** @var ProductStreamService $streamService */
142
        $streamService = $this->getStreamService();
143
        $streams = $streamService->getAllExportedStreams(ProductStreamService::DYNAMIC_STREAM);
144
145
        /** @var ProductStream $stream */
146
        foreach ($streams as $stream) {
147
            $streamId = $stream->getId();
148
            $productSearchResult = $streamService->getProductFromConditionStream($stream);
149
            $orderNumbers = array_keys($productSearchResult->getProducts());
150
151
            //no products found
152
            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...
153
                //removes all products from this stream
154
                $streamService->markProductsToBeRemovedFromStream($streamId);
155
            } else {
156
                $articleIds = $this->helper->getArticleIdsByNumber($orderNumbers);
157
158
                $streamService->markProductsToBeRemovedFromStream($streamId);
159
                $streamService->createStreamRelation($streamId, $articleIds);
160
            }
161
162
            try {
163
                $streamsAssignments = $streamService->prepareStreamsAssignments($streamId, false);
164
165
                //article ids must be taken from streamsAssignments
166
                $exportArticleIds = $streamsAssignments->getArticleIds();
167
168
                $removeArticleIds = $streamsAssignments->getArticleIdsWithoutStreams();
169
170
                if (!empty($removeArticleIds)) {
171
                    $this->removeArticlesFromStream($removeArticleIds);
172
173
                    //filter the $exportArticleIds
174
                    $exportArticleIds = array_diff($exportArticleIds, $removeArticleIds);
175
                }
176
177
                $sourceIds = $this->helper->getArticleSourceIds($exportArticleIds);
178
179
                $errorMessages = $this->connectExport->export($sourceIds, $streamsAssignments);
180
                $streamService->changeStatus($streamId, ProductStreamService::STATUS_EXPORT);
181
            } catch (\RuntimeException $e) {
182
                $streamService->changeStatus($streamId, ProductStreamService::STATUS_ERROR);
183
                $streamService->log($streamId, $e->getMessage());
184
                continue;
185
            }
186
187
            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...
188
                $streamService->changeStatus($streamId, ProductStreamService::STATUS_ERROR);
189
190
                $errorMessagesText = '';
191
                $displayedErrorTypes = [
192
                    ErrorHandler::TYPE_DEFAULT_ERROR,
193
                    ErrorHandler::TYPE_PRICE_ERROR
194
                ];
195
196
                foreach ($displayedErrorTypes as $displayedErrorType) {
197
                    $errorMessagesText .= implode('\n', $errorMessages[$displayedErrorType]);
198
                }
199
200
                $streamService->log($streamId, $errorMessagesText);
201
            }
202
        }
203
    }
204
205
    /**
206
     * If article is not taking part of any shopware stream it will be removed
207
     * @param array $articleIds
208
     */
209
    private function removeArticlesFromStream(array $articleIds)
210
    {
211
        $sourceIds = $this->helper->getArticleSourceIds($articleIds);
212
        $items = $this->connectExport->fetchConnectItems($sourceIds, false);
213
214
        foreach ($items as $item) {
215
            $this->sdk->recordDelete($item['sourceId']);
216
        }
217
218
        $this->getStreamService()->removeMarkedStreamRelations();
219
        $this->connectExport->updateConnectItemsStatus($sourceIds, Attribute::STATUS_DELETE);
220
    }
221
222
    /**
223
     * @return ProductStreamService $streamService
224
     */
225
    private function getStreamService()
226
    {
227
        if (!$this->streamService) {
228
            $this->streamService = Shopware()->Container()->get('swagconnect.product_stream_service');
229
        }
230
231
        return $this->streamService;
232
    }
233
}
234