getOrderData()   C
last analyzed

Complexity

Conditions 7
Paths 24

Size

Total Lines 90
Code Lines 57

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 90
rs 6.5083
c 0
b 0
f 0
cc 7
eloc 57
nc 24
nop 1

How to fix   Long Method   

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
/**
4
 *
5
 *
6
 * @category Mygento
7
 * @package Mygento_Yandexdelivery
8
 * @copyright 2017 NKS LLC. (http://www.mygento.ru)
9
 * @license GPLv2
10
 */
11
class Mygento_Yandexdelivery_Model_Carrier {
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class must be in a namespace of at least one level to avoid collisions.

You can fix this by adding a namespace to your class:

namespace YourVendor;

class YourClass { }

When choosing a vendor namespace, try to pick something that is not too generic to avoid conflicts with other libraries.

Loading history...
12
13
    private $_name = 'yandexdelivery';
14
    private $_url = 'https://delivery.yandex.ru/api/last/';
15
16
    public function processApiKeys($data_string) {
17
        $json = json_decode(trim($data_string));
18
19
        if (!$json) {
20
            return;
21
        }
22
23
        Mage::helper($this->_name)->addLog('Processed API keys');
24
        Mage::helper($this->_name)->addLog($json);
25
26
        foreach ($json as $key => $element) {
27
            Mage::helper($this->_name)->setConfigData(trim($key), trim($element));
28
        }
29
    }
30
31
    public function processApiIds($data_string) {
32
33
        $json = json_decode(trim($data_string));
34
        $res = Mage::getSingleton('core/resource');
35
36
        Mage::helper($this->_name)->addLog('Processed API Ids');
37
        Mage::helper($this->_name)->addLog($json);
38
39
        if (empty($json)) {
40
            return;
41
        }
42
43
        Mage::helper($this->_name)->setConfigData('client_id', $json->client->id);
44
45
        $adapter = $res->getConnection('yandexdelivery_write');
46
        //process senders
47 View Code Duplication
        foreach ($json->senders as $value) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
48
            $insertData = [
49
                'id' => $value->id,
50
                'name' => $value->name
51
            ];
52
            $adapter->insertOnDuplicate($res->getTableName('yandexdelivery/sender'), $insertData, array_keys($insertData));
53
        }
54
        //process warehouses
55 View Code Duplication
        foreach ($json->warehouses as $value) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
56
            $insertData = [
57
                'id' => $value->id,
58
                'name' => $value->name
59
            ];
60
            $adapter->insertOnDuplicate($res->getTableName('yandexdelivery/warehouse'), $insertData, array_keys($insertData));
61
        }
62
        //process requisites
63 View Code Duplication
        foreach ($json->requisites as $value) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
64
            $insertData = [
65
                'id' => $value->id
66
            ];
67
            $adapter->insertOnDuplicate($res->getTableName('yandexdelivery/requisite'), $insertData, array_keys($insertData));
68
        }
69
70
        $this->getSenderInfo();
71
        $this->getRequisiteInfo();
72
        $this->getWarehouseInfo();
73
    }
74
75
    /**
76
     * автоподсказки адресов
77
     * @param string $search
78
     * @param string $type
79
     * @param string $city
80
     * @return json
81
     */
82
    public function getAutocomplete($search, $type, $city = false) {
83
        $data = [
84
            'term' => $search,
85
            'type' => $type,
86
        ];
87
88
        if ($city) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $city of type false|string is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== false instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
89
            $data['locality_name'] = $city;
90
        }
91
92
        $result = $this->sendRequest('autocomplete', $data, true);
93
94
        if ($result->status == 'ok') {
95
            return $result->data->suggestions;
96
        }
97
        return json_encode();
0 ignored issues
show
Bug Best Practice introduced by
The return type of return json_encode(); (string) is incompatible with the return type documented by Mygento_Yandexdelivery_M...arrier::getAutocomplete of type json.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
98
    }
99
100
    private function getSenderInfo() {
101
        $result = $this->sendRequest('getSenderInfo', [], true);
102
103
        if ($result->status == 'ok') {
104
            $sender = Mage::getModel('yandexdelivery/sender')->load($result->data->id);
105
            $sender->setName($result->data->field_name);
106
            $sender->save();
107
        }
108
    }
109
110
    private function getWarehouseInfo() {
111
        $data = [
112
            'warehouse_id' => Mage::helper($this->_name)->getConfigData('warehouse'),
113
        ];
114
        $result = $this->sendRequest('getWarehouseInfo', $data, true);
115
116
        if ($result->status == 'ok') {
117
            $sender = Mage::getModel('yandexdelivery/warehouse')->load($result->data->id);
118
119
            $sender->setName($result->data->field_name);
120
            $sender->setAddress($result->data->address);
121
            $sender->save();
122
        }
123
    }
124
125
    private function getRequisiteInfo() {
126
        $data = [
127
            'requisite_id' => Mage::getStoreConfig('carriers/' . $this->_name . '/requisite')
128
        ];
129
130
        $result = $this->sendRequest('getRequisiteInfo', $data, true);
131
132
        if ($result->status != "ok") {
133
            return;
134
        }
135
        foreach ($result->data->requisites as $requsite) {
136
            $requsiteId = $requsite->id;
137
            Mage::helper($this->_name)->addLog('FFF ' . $requsiteId);
138
            if (!$requsiteId) {
139
                continue;
140
            }
141
            $requisite = Mage::getModel('yandexdelivery/requisite')->load($requsiteId);
142
            $requisite->setLegalForm($requsite->legal_form);
143
            $requisite->setLegalName($requsite->legal_name);
144
            $address = implode(', ', (array) $requsite->address_legal);
145
            $requisite->setAddress($address);
146
            $requisite->save();
147
        }
148
    }
149
150
    public function createOrder($orderId, $warehouseId, $senderId, $requisiteId, $date, $street, $house) {
151
        //создание заявки на отправку заказа в ЯД
152
        $order = Mage::getModel('sales/order')->load($orderId);
153
154
        if (!$order || !$order->getId()) {
155
            return false;
156
        }
157
158
        $data = $this->getOrderData($order);
159
160
        $data ['order_requisite'] = $requisiteId;
161
        $data ['order_warehouse'] = $warehouseId;
162
        $data['order_shipment_date'] = date('Y-m-d', strtotime($date));
163
        $data['deliverypoint']['street'] = $street;
164
        $data['deliverypoint']['house'] = $house;
165
166
        return $this->sendRequest('createOrder', $data, true, $senderId);
167
    }
168
169
    public function getTypes($addHypes = false) {
170
        $types = ['todoor', 'post', 'pickup'];
171
        $enabled = [];
172
        foreach ($types as $type) {
173
            if (Mage::getStoreConfig('carriers/yandexdelivery_' . $type . '/active')) {
174
                if ($addHypes) {
175
                    $enabled[] = "'" . $type . "'";
176
                } else {
177
                    $enabled[] = $type;
178
                }
179
            }
180
        }
181
        return $enabled;
182
    }
183
184
    public function confirmOrders($id, $type) {
185
        $data = [
186
            'order_ids' => $id,
187
            'type' => $type,
188
            'shipment_date' => date('Y-m-d')
189
        ];
190
191
        $result = $this->sendRequest('confirmSenderOrders', $data, true);
192
193
        if (!isset($result->data->result) || count($result->data->result->error) != 0 || count($result->data->errors)) {
194
            return $result;
195
        }
196
197
        //set parcel_id to DB
198
        foreach ($result->data->result->success as $success) {
199
            $yd_id_collection = Mage::getModel('yandexdelivery/shipment')->getCollection();
200
            $yd_id_collection->addFieldToFilter('yd_id', ['in' => $success->orders]);
201
            foreach ($yd_id_collection as $ydShipment) {
202
                $ydShipment->setParcelId($success->parcel_id);
203
                $ydShipment->save();
204
            }
205
        }
206
207
        return $result;
208
    }
209
210
    /**
211
     * получаем id заказа в ЯД по ордеру
212
     * @param int $orderId
213
     * @return boolean
214
     */
215
    public function getYdId($orderId) {
216
        if ($this->getShipment($orderId)) {
217
            return $this->getShipment($orderId)->getYdId();
0 ignored issues
show
Bug introduced by
The method getYdId cannot be called on $this->getShipment($orderId) (of type boolean).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
218
        }
219
        return false;
220
    }
221
222
    /**
223
     * получаем объект шипмента
224
     * @param int $orderId
225
     * @return boolean
226
     */
227 View Code Duplication
    public function getShipment($orderId) {
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...
228
        $yd_id_collection = Mage::getModel('yandexdelivery/shipment')->getCollection();
229
        $yd_id_collection->addFieldToFilter('order_id', $orderId);
230
        $yd_id_collection->load();
231
        if ($yd_id_collection->getSize() > 0) {
232
            return $yd_id_collection->getFirstItem();
233
        }
234
        return false;
235
    }
236
237
    /**
238
     * получаем id заказа в ЯД по id shipment
239
     * @param array $ids
240
     * @return boolean
241
     */
242 View Code Duplication
    public function getYdIdsByIds($ids) {
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...
243
        $yd_id_collection = Mage::getModel('yandexdelivery/shipment')->getCollection();
244
        $yd_id_collection->addFieldToFilter('id', ['in' => $ids]);
245
        $yd_id_collection->load();
246
        if ($yd_id_collection->getSize() > 0) {
247
            return $yd_id_collection->getColumnValues('yd_id');
248
        }
249
        return false;
250
    }
251
252
    public function deleteOrder($order_id) {
253
        $result = $this->sendRequest('deleteOrder', ['order_id' => $order_id], true);
254
255
        //удаляем запись в БД в случае успеха
256
        if ($result->status == "ok") {
257
            $yd_id_collection = Mage::getModel('yandexdelivery/shipment')->getCollection();
258
            $yd_id_collection->addFieldToFilter('yd_id', $order_id);
259
            $yd_id_collection->load();
260
            if ($yd_id_collection->getSize() > 0) {
261
                $item = $yd_id_collection->getFirstItem();
262
                $item->delete();
263
            }
264
        }
265
        return $result;
266
    }
267
268
    public function senderOrderStatuses($order_id) {
269
        return $this->sendRequest('getSenderOrderStatuses', ['order_id' => $order_id], true);
270
    }
271
272
    public function getSenderOrderLabel($order_id) {
273
        return $this->sendRequest('getSenderOrderLabel', ['order_id' => $order_id], true);
274
    }
275
276
    public function getSenderParcelDocs($parcel_id) {
277
        return $this->sendRequest('getSenderParcelDocs', ['parcel_id' => $parcel_id], true);
278
    }
279
280
    public function searchDeliveryList($data) {
281
        return $this->sendRequest('searchDeliveryList', $data, true);
282
    }
283
284
    public function statusOrder($order_id) {
285
        return $this->sendRequest('getOrderInfo', ['order_id' => $order_id], true);
286
    }
287
288
    protected function sendRequest($method, $data, $sign, $sender = null) {
289
        if ($sender) {
290
            $data['sender_id'] = $sender;
291
        } else {
292
            $data['sender_id'] = $this->getSender();
293
        }
294
        return json_decode(Mage::helper($this->_name)->requestApiPost($this->_url . $method, $data, $sign, $method));
295
    }
296
297
    protected function getOrderData($order) {
298
299
        if (Mage::getStoreConfig('carriers/' . $this->_name . '/onlyone')) {
300
            $weight = round(Mage::getStoreConfig('carriers/' . $this->_name . '/oneweight') * 1000 / Mage::getStoreConfig('carriers/' . $this->_name . '/weightunit'), 3);
301
            $dimensions = Mage::helper($this->_name)->getStandardSizes();
302
        } else {
303
            $processed_dimensions = Mage::helper($this->_name)->getSizes($order->getAllVisibleItems(), false);
304
            $weight = $processed_dimensions['weight'];
305
            $dimensions = Mage::helper($this->_name)->dimenAlgo($processed_dimensions['dimensions']);
306
        }
307
308
309
        $shipping_code = $order->getShippingMethod();
310
        $detect_code = str_replace('yandexdelivery_', '', $shipping_code);
311
312
        $info_array = explode('_', $detect_code);
313
314
        $data = [
315
            'order_num' => $order->getIncrementId(),
316
            'order_length' => $dimensions['A'],
317
            'order_width' => $dimensions['B'],
318
            'order_height' => $dimensions['C'],
319
            'order_weight' => $weight,
320
            'order_assessed_value' => round($order->getGrandTotal() - $order->getShippingAmount(), 0),
321
            'order_delivery_cost' => round($order->getShippingAmount(), 0),
322
            'order_shipment_type' => $info_array[0],
323
            'is_manual_delivery_cost' => 1,
324
            'recipient' => [
325
                'phone' => Mage::helper('yandexdelivery')->normalizePhone($order->getShippingAddress()->getTelephone()),
326
                'email' => $order->getShippingAddress()->getEmail(),
327
                'first_name' => $order->getShippingAddress()->getFirstname(),
328
                'last_name' => $order->getShippingAddress()->getLastname(),
329
            ],
330
            'delivery' => [
331
                'to_yd_warehouse' => Mage::getStoreConfig('carriers/' . $this->_name . '/yd_warehouse'),
332
                'delivery' => $info_array[3],
333
                'direction' => $info_array[2],
334
                'tariff' => $info_array[1],
335
            ],
336
            'deliverypoint' => [
337
                'city' => $order->getShippingAddress()->getCity(),
338
                'index' => $order->getShippingAddress()->getPostcode(),
339
            ],
340
        ];
341
342
        $invoicesSum = 0;
343
344
        if ($order->hasInvoices()) {
345
            //check all invoices sum
346
347
            $invoicesCollection = $order->getInvoiceCollection();
348
349
            foreach ($invoicesCollection as $invoice) {
350
                $invoicesSum += $invoice->getGrandTotal();
351
            }
352
353
            //check all credit memo sum ??
354
        }
355
        $data['order_amount_prepaid'] = $invoicesSum;
356
357
        if (isset($info_array[4])) {
358
            //если ПВЗ
359
            $data['delivery']['pickuppoint'] = $info_array[4];
360
        }
361
362
        $order_items = [];
363
364
        foreach ($order->getAllVisibleItems() as $item) {
365
            $data = [
366
                'orderitem_name' => $item->getName(),
367
                'orderitem_quantity' => round($item->getQtyOrdered(), 2),
368
                'orderitem_cost' => $item->getRowTotalInclTax() / ceil($item->getQtyOrdered()),
369
                'orderitem_article' => $item->getSku(),
370
            ];
371
372
            //get tax info
373
            if (Mage::getStoreConfig('carriers/' . $this->_name . '/tax_all')) {
374
                $data['orderitem_vat_value'] = Mage::getStoreConfig('carriers/' . $this->_name . '/tax_options');
375
            } else {
376
                $attributeCode = Mage::getStoreConfig('carriers/' . $this->_name . '/tax_all');
377
                $data['orderitem_vat_value'] = Mage::getResourceModel('catalog/product')->getAttributeRawValue($item->getProductId(), $attributeCode, $order->getStore());
378
            }
379
380
            $order_items[] = $data;
381
        }
382
383
        $data['order_items'] = $order_items;
384
385
        return $data;
386
    }
387
388
    protected function getSender() {
389
        return Mage::helper($this->_name)->getConfigData('sender');
390
    }
391
392
    //currently unused
393
394
    public function getPaymentMethods() {
395
        return $this->sendRequest('getPaymentMethods', [], true);
396
    }
397
398
}
399