ProductWriter::writeItem()   D
last analyzed

Complexity

Conditions 16
Paths 320

Size

Total Lines 69
Code Lines 43

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 69
rs 4.2342
cc 16
eloc 43
nc 320
nop 1

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace Jh\DataImportMagento\Writer;
4
5
use Ddeboer\DataImport\Exception\WriterException;
6
use Ddeboer\DataImport\Writer\AbstractWriter;
7
use Jh\DataImportMagento\Exception\MagentoSaveException;
8
use Jh\DataImportMagento\Service\AttributeService;
9
use Jh\DataImportMagento\Service\ConfigurableProductService;
10
use Jh\DataImportMagento\Service\RemoteImageImporter;
11
use Jh\DataImportMagento\Factory\ConfigurableProductServiceFactory;
12
use Psr\Log\LoggerInterface;
13
14
/**
15
 * Class ProductWriter
16
 * @author Adam Paterson <[email protected]>
17
 * @author Aydin Hassan <[email protected]>
18
 * @package Jh\DataImportMagento\Writer
19
 */
20
class ProductWriter extends AbstractWriter
21
{
22
23
    /**
24
     * @var \Mage_Catalog_Model_Product
25
     */
26
    protected $productModel;
27
28
    /**
29
     * @var RemoteImageImporter
30
     */
31
    protected $remoteImageImporter;
32
33
    /**
34
     * @var ConfigurableProductService
35
     */
36
    protected $configurableProductService;
37
38
    /**
39
     * @var AttributeService
40
     */
41
    protected $attributeService;
42
43
    /**
44
     * @var null|string
45
     */
46
    protected $defaultAttributeSetId = null;
47
48
    /**
49
     * @var array
50
     */
51
    protected $defaultProductData = array();
52
53
    /**
54
     * @var array
55
     */
56
    protected $defaultStockData = array();
57
58
    /**
59
     * @var LoggerInterface
60
     */
61
    private $logger;
62
63
    /**
64
     * @param \Mage_Catalog_Model_Product $productModel
65
     * @param RemoteImageImporter         $remoteImageImporter
66
     * @param AttributeService            $attributeService
67
     * @param ConfigurableProductService  $configurableProductService
68
     * @param LoggerInterface             $logger
69
     */
70
    public function __construct(
71
        \Mage_Catalog_Model_Product $productModel,
72
        RemoteImageImporter $remoteImageImporter,
73
        AttributeService $attributeService,
74
        ConfigurableProductService $configurableProductService,
75
        LoggerInterface $logger
76
    ) {
77
        $this->productModel                 = $productModel;
78
        $this->remoteImageImporter          = $remoteImageImporter;
79
        $this->configurableProductService   = $configurableProductService;
80
        $this->attributeService             = $attributeService;
81
        $this->logger                       = $logger;
82
    }
83
84
    /**
85
     * @return \Ddeboer\DataImport\Writer\WriterInterface|void
86
     */
87
    public function prepare()
88
    {
89
        $this->defaultAttributeSetId = $this->productModel->getDefaultAttributeSetId();
90
        $this->defaultStockData = [
91
            'manage_stock'                  => 1,
92
            'use_config_manage_stock'       => 1,
93
            'qty'                           => 0,
94
            'min_qty'                       => 0,
95
            'use_config_min_qty'            => 1,
96
            'min_sale_qty'                  => 1,
97
            'use_config_min_sale_qty'       => 1,
98
            'max_sale_qty'                  => 10000,
99
            'use_config_max_sale_qty'       => 1,
100
            'is_qty_decimal'                => 0,
101
            'backorders'                    => 0,
102
            'use_config_backorders'         => 1,
103
            'notify_stock_qty'              => 1,
104
            'use_config_notify_stock_qty'   => 1,
105
            'enable_qty_increments'         => 0,
106
            'use_config_enable_qty_inc'     => 1,
107
            'qty_increments'                => 0,
108
            'use_config_qty_increments'     => 1,
109
            'is_in_stock'                   => 0,
110
            'low_stock_date'                => null,
111
            'stock_status_changed_auto'     => 0
112
        ];
113
        $this->defaultProductData = [
114
            'weight'        => '0',
115
            'status'        => '1',
116
            'tax_class_id'  => 2,   //Taxable Goods Tax Class
117
            'website_ids'   => [1],
118
            'type_id'       => 'simple',
119
            'url_key'       => null
120
        ];
121
    }
122
123
    /**
124
     *
125
     * @param array $item
126
     * @return \Ddeboer\DataImport\Writer\WriterInterface|void
127
     * @throws \Jh\DataImportMagento\Exception\MagentoSaveException
128
     */
129
    public function writeItem(array $item)
130
    {
131
        $product = clone $this->productModel;
132
133
        if (!isset($item['attribute_set_id'])) {
134
            $item['attribute_set_id'] = $this->defaultAttributeSetId;
135
        }
136
137
        if (!isset($item['stock_data'])) {
138
            $item['stock_data'] = $this->defaultStockData;
139
        }
140
141
        if (!isset($item['weight'])) {
142
            $item['weight'] = '0';
143
        }
144
145
        $item = array_merge($this->defaultProductData, $item);
146
147
        if (isset($item['attributes'])) {
148
            $this->processAttributes($item['attributes'], $product);
149
            unset($item['attributes']);
150
        }
151
152
        $product->addData($item);
153
        if ($this->isConfigurable($item)) {
154
            $this->processConfigurableProduct($item, $product);
155
        }
156
157
        try {
158
            $product->save();
159
        } catch (\Exception $e) {
160
            throw new MagentoSaveException($e);
161
        }
162
163
        if (isset($item['type_id']) &&
164
            $item['type_id'] === 'simple' &&
165
            isset($item['parent_sku']) &&
166
            !empty($item['parent_sku'])
167
        ) {
168
            try {
169
                $this->configurableProductService
170
                    ->assignSimpleProductToConfigurable(
171
                        $product,
172
                        $item['parent_sku']
173
                    );
174
            } catch (MagentoSaveException $e) {
175
                $product->delete();
176
                throw $e;
177
            }
178
        }
179
180
        if (isset($item['images']) && is_array($item['images'])) {
181
            $product->setData('url_key', false);
182
            foreach ($item['images'] as $image) {
183
                try {
184
                    $this->remoteImageImporter->importImage($product, $image);
185
                } catch (\RuntimeException $e) {
186
                    $product->delete();
187
                    throw new MagentoSaveException(
188
                        sprintf(
189
                            'Error importing image for product with SKU: "%s". Error: "%s"',
190
                            $item['sku'],
191
                            $e->getMessage()
192
                        )
193
                    );
194
                }
195
            }
196
        }
197
    }
198
199
    /**
200
     * @param array $attributes
201
     * @param \Mage_Catalog_Model_Product $product
202
     */
203
    private function processAttributes(array $attributes, \Mage_Catalog_Model_Product $product)
204
    {
205
        foreach ($attributes as $attributeCode => $attributeValue) {
206
            if (!$attributeValue) {
207
                continue;
208
            }
209
210
            $attrId = $this->attributeService
211
                ->getAttrCodeCreateIfNotExist('catalog_product', $attributeCode, $attributeValue);
212
213
            $product->setData($attributeCode, $attrId);
214
        }
215
    }
216
217
    /**
218
     * @param array $item
219
     * @return bool
220
     */
221
    private function isConfigurable(array $item)
222
    {
223
        return isset($item['type_id']) && $item['type_id'] === 'configurable';
224
    }
225
226
    /**
227
     * @param array                       $item
228
     * @param \Mage_Catalog_Model_Product $product
229
     *
230
     * @throws MagentoSaveException
231
     */
232
    private function processConfigurableProduct(array $item, \Mage_Catalog_Model_Product $product)
233
    {
234
        $attributes = [];
235
        if (isset($item['configurable_attributes']) && is_array($item['configurable_attributes'])) {
236
            $attributes = $item['configurable_attributes'];
237
        }
238
239
        if (count($attributes) === 0) {
240
            throw new MagentoSaveException(
241
                sprintf(
242
                    'Configurable product with SKU: "%s" must have at least one "configurable_attribute" defined',
243
                    $item['sku']
244
                )
245
            );
246
        }
247
248
        $this->configurableProductService
249
            ->setupConfigurableProduct(
250
                $product,
251
                $attributes
252
            );
253
    }
254
}
255