getAttributeValue()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 16
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 16
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 12
nc 3
nop 2
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_Helper_Data extends Mage_Core_Helper_Abstract
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
14
    private $_name = 'yandexdelivery';
15
16
    public function addLog($text)
17
    {
18
        if ($this->getConfigData('debug')) {
19
            Mage::log($text, null, $this->_name . '.log', true);
20
        }
21
    }
22
23
    public function requestApiPost($url, $data, $sign = false, $method = false)
24
    {
25
        $this->addLog('Request to: ' . $url);
26
27
        if ($sign) {
28
            $data = $this->sign($data, $method);
29
        }
30
31
        // @codingStandardsIgnoreStart
32
        $curl_handle = curl_init();
33
        curl_setopt($curl_handle, CURLOPT_URL, $url);
34
        curl_setopt($curl_handle, CURLOPT_FOLLOWLOCATION, 1);
35
        curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, 1);
36
        curl_setopt($curl_handle, CURLOPT_HEADER, false);
37
        curl_setopt($curl_handle, CURLOPT_TIMEOUT, 60);
38
        curl_setopt($curl_handle, CURLOPT_POST, 1);
39
        curl_setopt($curl_handle, CURLOPT_POSTFIELDS, http_build_query($data));
40
        curl_setopt($curl_handle, CURLOPT_SSL_VERIFYPEER, 1);
41
42
        $result = curl_exec($curl_handle);
43
44
        if ($result === false) {
45
            $this->addLog('Request error:');
46
            $this->addLog(curl_error($ch));
0 ignored issues
show
Bug introduced by
The variable $ch does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
47
        }
48
49
        curl_close($curl_handle);
50
        // @codingStandardsIgnoreEnd
51
52
        $this->addLog('Request result:');
53
        $this->addLog($result);
54
55
        return $result;
56
    }
57
58
    public function getConfigData($path)
59
    {
60
        return Mage::getStoreConfig('carriers/' . $this->_name . '/' . $path);
61
    }
62
63
    /**
64
     * формирование подписи запроса
65
     * @param array $data
66
     * @param string $method
67
     * @return array
68
     */
69
    private function sign($data, $method)
70
    {
71
        $data['client_id'] = $this->getConfigData('client_id');
72
73
        $secretKey = '';
74
        $keys = array_keys($data);
75
        sort($keys);
76
77
        foreach ($keys as $key) {
78
            if (!is_array($data[$key])) {
79
                $secretKey .= $data[$key];
80
            } else {
81
                $subkeys = array_keys($data[$key]);
82
                sort($subkeys);
83
                foreach ($subkeys as $subkey) {
84
                    if (!is_array($data[$key][$subkey])) {
85
                        $secretKey .= $data[$key][$subkey];
86
                    } else {
87
                        $subsubkeys = array_keys($data[$key][$subkey]);
88
                        sort($subsubkeys);
89
                        foreach ($subsubkeys as $subsubkey) {
90
                            if (!is_array($data[$key][$subkey][$subsubkey])) {
91
                                $secretKey .= $data[$key][$subkey][$subsubkey];
92
                            }
93
                        }
94
                    }
95
                }
96
            }
97
        }
98
99
        $preparedData = $secretKey . $this->getConfigData('' . $method);
100
        $data['secret_key'] = md5($preparedData);
101
102
        $this->addLog($data);
103
        return $data;
104
    }
105
106
    public function setConfigData($key, $value)
107
    {
108
        Mage::getModel('core/config')->saveConfig('carriers/' . $this->_name . '/' . $key, $value);
109
    }
110
111
    public function refreshAllCaches()
112
    {
113
        try {
114
            $allTypes = Mage::app()->useCache();
115
            foreach ($allTypes as $type) {
116
                Mage::app()->getCacheInstance()->cleanType($type);
117
            }
118
        } catch (Exception $e) {
119
            $this->addLog($e->getMessage());
120
        }
121
    }
122
123
    /**
124
     * алгоритм расчета суммарных габаритов всех товаров
125
     * @param array $dimensions
126
     * @return array
127
     */
128
    public function dimenAlgo(array $dimensions)
129
    {
130
        $this->addLog('Array before dimension sorting');
131
        $this->addLog($dimensions);
132
133
        $dim = [];
134
        $result = [
135
            'A' => 0,
136
            'B' => 0,
137
            'C' => 0,
138
        ];
139
        foreach ($dimensions as $d) {
140
            if ($this->isValidDimensionArr($d)) {
141
                rsort($d);
142
                $dim[] = $d;
143
            }
144
        }
145
146
        foreach ($dim as $d) {
147
            ($d[0] > $result['A']) ? $result['A'] = $d[0] : '';
148
            ($d[1] > $result['B']) ? $result['B'] = $d[1] : '';
149
            $result['C'] += $d[2];
150
        }
151
152
        $this->addLog('Array after dimension sorting');
153
        $this->addLog($result);
154
155
        return $result;
156
    }
157
158
    private function isValidDimensionArr($arr)
159
    {
160
        if (is_array($arr) and 3 == sizeof($arr)) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as and instead of && is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
161
            foreach ($arr as $a) {
162
                if ((!is_int($a) and ! is_float($a)) or $a < 0.1) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as and instead of && is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
Comprehensibility Best Practice introduced by
Using logical operators such as or instead of || is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
163
                    return false;
164
                }
165
            }
166
        } else {
167
            return false;
168
        }
169
        return true;
170
    }
171
172
    public function isShippedBy($order)
173
    {
174
        if (strpos($order->getShippingMethod(), 'yandexdelivery') !== false) {
175
            return true;
176
        }
177
        return false;
178
    }
179
180
    /**
181
     * получение габаритов и веса товаров
182
     * @param type $items
183
     * @param type $is_quote
184
     * @return array
185
     */
186
    public function getSizes($items, $is_quote)
187
    {
188
        $temporary_dimensions = [];
189
        $weight = 0;
190
191
        foreach ($items as $_item) {
192
            if ($_item->getProduct() instanceof Mage_Catalog_Model_Product) {
0 ignored issues
show
Bug introduced by
The class Mage_Catalog_Model_Product does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
193
                $product = Mage::getModel('catalog/product')->load($_item->getProductId());
194
195
                if ($is_quote) {
196
                    $qty = $_item->getQty();
197
                } else {
198
                    $qty = $_item->getQtyOrdered();
199
                }
200
201
                $itemweight = round($this->getAttributeValue('weight', $product) * $qty * 1000 / $this->getConfigData('weightunit'), 3);
202
203
                if ($itemweight == 0) {
204
                    $itemweight = $_item->getWeight() * $qty / $this->getConfigData('weightunit');
205
                }
206
207
                $weight += $itemweight;
208
209
                $itemlength = round($this->getAttributeValue('length', $product) * 100 / $this->getConfigData('sizeunit'), 3);
210
                $itemwidth = round($this->getAttributeValue('width', $product) * 100 / $this->getConfigData('sizeunit'), 3);
211
                $itemheight = round($this->getAttributeValue('height', $product) * 100 / $this->getConfigData('sizeunit'), 3);
212
213
                for ($i = 1; $i <= $qty; $i++) {
214
                    array_push($temporary_dimensions, ['L' => $itemlength, 'W' => $itemwidth, 'H' => $itemheight]);
215
                }
216
            }
217
        }
218
219
        return [
220
            'dimensions' => $temporary_dimensions,
221
            'weight' => $weight
222
        ];
223
    }
224
225
    private function getAttributeValue($param, $product)
226
    {
227
        $attribute = $this->getConfigData('item' . $param);
228
        if ('0' != $attribute) {
229
            $attribute_mode = Mage::getModel('catalog/product')->getResource()->getAttribute($attribute)->getFrontendInput();
230
            if ('select' == $attribute_mode) {
231
                $value = $product->getAttributeText($attribute);
232
                Mage::helper($this->_name)->addLog('attribute ' . $attribute . ' is select with value -> ' . $value);
233
            } else {
234
                $value = $product->getData($attribute);
235
            }
236
        } else {
237
            $value = $this->getConfigData('fone' . $param);
238
        }
239
        return round($value, 0);
240
    }
241
242
    /**
243
     * получение стандартных габаритов посылки
244
     * @return array
245
     */
246
    public function getStandardSizes()
247
    {
248
249
        return [
250
            'A' => round($this->getConfigData('onelength') * 100 / $this->getConfigData('sizeunit'), 3),
251
            'B' => round($this->getConfigData('onewidth') * 100 / $this->getConfigData('sizeunit'), 3),
252
            'C' => round($this->getConfigData('oneheight') * 100 / $this->getConfigData('sizeunit'), 3)
253
        ];
254
    }
255
256
    public function toOptionArray($model)
257
    {
258
        $data_array = [];
259
        $model = Mage::getModel('yandexdelivery/' . $model);
260
        $data = $model->getCollection()->getData();
261
        foreach ($data as $track) {
262
            array_push($data_array, [
263
                'value' => $track['id'],
264
                'label' => (isset($track['name']) ? $track['name'] : $track['legal_name'])
265
            ]);
266
        }
267
        return $data_array;
268
    }
269
270
    public function toOptionsArray($model)
271
    {
272
        $data_array = [];
273
        $model = Mage::getModel('yandexdelivery/' . $model);
274
        $data = $model->getCollection()->getData();
275
        foreach ($data as $track) {
276
            $data_array[$track['id']] = (isset($track['name']) ? $track['name'] : $track['legal_name']);
277
        }
278
        return $data_array;
279
    }
280
281
    public function normalizePhone($phone)
282
    {
283
        $phone = trim($phone);
284
        $phone = str_replace('(', '', $phone);
285
        $phone = str_replace(')', '', $phone);
286
        $phone = str_replace('-', '', $phone);
287
        $phone = preg_replace('/\s+/', '', $phone);
288
        static $filter = null;
289
        if (is_null($filter)) {
290
            $filter = new Zend_Filter_Digits();
291
        }
292
        $num = $filter->filter($phone);
293
        if (strlen($num) == 11) {
294
            $phone = '7' . substr($num, 1);
295
        } elseif (strlen($num) == 10) {
296
            $phone = '7' . $num;
297
        } else {
298
            $phone = $num;
299
        }
300
        return $phone;
301
    }
302
}
303