Mygento_Payture_Helper_Data   A
last analyzed

Complexity

Total Complexity 34

Size/Duplication

Total Lines 258
Duplicated Lines 3.88 %

Coupling/Cohesion

Components 1
Dependencies 0

Importance

Changes 0
Metric Value
wmc 34
lcom 1
cbo 0
dl 10
loc 258
rs 9.2
c 0
b 0
f 0

15 Methods

Rating   Name   Duplication   Size   Complexity  
A addLog() 0 6 2
A getKey() 0 4 1
A getPassword() 0 4 1
A sendEmailByOrder() 0 8 2
A getLink() 0 21 2
A decodeid() 10 10 2
C addtransaction() 0 52 8
B sendCustomComment() 0 25 2
A checkTicket() 0 12 2
A getHost() 0 7 2
A getData() 0 14 1
A getConfig() 0 4 1
B getOrderItemsJson() 0 34 4
A isPaidBy() 0 7 2
A processTransaction() 0 20 2

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php
2
3
/**
4
 *
5
 *
6
 * @category Mygento
7
 * @package Mygento_Payture
8
 * @copyright 2017 NKS LLC. (https://www.mygento.ru)
9
 */
10
class Mygento_Payture_Helper_Data extends Mage_Core_Helper_Abstract
11
{
12
    public function addLog($text)
13
    {
14
        if (Mage::getStoreConfig('payment/payture/debug')) {
15
            Mage::log($text, null, 'payture.log', true);
16
        }
17
    }
18
19
    public function getKey()
20
    {
21
        return Mage::helper('core')->decrypt(Mage::getStoreConfig('payment/payture/key'));
22
    }
23
24
    public function getPassword()
25
    {
26
        return Mage::helper('core')->decrypt(Mage::getStoreConfig('payment/payture/password'));
27
    }
28
29
    public function sendEmailByOrder($order)
30
    {
31
        try {
32
            $order->sendNewOrderEmail();
33
        } catch (Exception $e) {
34
            $this->addLog($e->getMessage());
35
        }
36
    }
37
38
    public function getLink($order_id)
39
    {
40
        $collection = Mage::getModel('payture/keys')->getCollection();
41
        $collection->addFieldToFilter('orderid', $order_id);
42
        if (count($collection) == 0) {
43
            $model = Mage::getModel('payture/keys');
44
            $key   = strtr(base64_encode(microtime() . $order_id . rand(1, 1048576)), '+/=', '-_,');
45
            $model->setHkey($key);
46
            $model->setOrderid($order_id);
47
            $model->setSessionid(null);
48
            $model->setDate(null);
49
            $model->save();
50
            return Mage::getUrl('payture/payment/paynow/', array('_secure' => true, 'order' => $key));
51
        } else {
52
            $item = $collection->getFirstItem();
53
            return Mage::getUrl(
54
                'payture/payment/paynow/',
55
                array('_secure' => true, 'order' => $item->getHkey())
56
            );
57
        }
58
    }
59
60 View Code Duplication
    public function decodeid($link)
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...
61
    {
62
        $collection = Mage::getModel('payture/keys')->getCollection();
63
        $collection->addFieldToFilter('hkey', $link);
64
        if (count($collection) == 0) {
65
            return false;
66
        }
67
        $item = $collection->getFirstItem();
68
        return $item;
69
    }
70
71
    public function addtransaction($order)
72
    {
73
        $orders = Mage::getModel('sales/order_invoice')->getCollection()
74
            ->addAttributeToFilter('order_id', array('eq' => $order->getId()));
75
        $orders->getSelect()->limit(1);
76
        if ((int) $orders->count() !== 0) {
77
            return $this;
78
        }
79
        if ($order->getState() == Mage_Sales_Model_Order::STATE_NEW) {
80
            try {
81
                if (!$order->canInvoice()) {
82
                    $order->addStatusHistoryComment(
83
                        'Payture_Invoicer: Order cannot be invoiced.',
84
                        false
85
                    );
86
                    $order->save();
87
                }
88
                $invoice         = Mage::getModel('sales/service_order', $order)->prepareInvoice();
89
                $invoice->setRequestedCaptureCase(Mage_Sales_Model_Order_Invoice::CAPTURE_OFFLINE);
90
                $invoice->register();
91
                $invoice->getOrder()->setCustomerNoteNotify(false);
92
                $invoice->getOrder()->setIsInProcess(true);
93
                $order->addStatusHistoryComment('Automatically INVOICED by Payture_Invoicer.', false);
94
                $transactionSave = Mage::getModel('core/resource_transaction')
95
                    ->addObject($invoice)
96
                    ->addObject($invoice->getOrder());
97
                $transactionSave->save();
98
                if (Mage::getStoreConfig('payment/payture/send')) {
99
                    $order->sendOrderUpdateEmail(
100
                        $order->getStatus(),
101
                        Mage::getStoreConfig('payment/payture/text')
102
                    );
103
                }
104
                if (Mage::getStoreConfig('payment/payture/sendinvoice')) {
105
                    $invoice->sendEmail();
106
                }
107
                if (Mage::getStoreConfig('payment/payture/sendadmin') != '') {
108
                    $this->sendCustomComment(
109
                        $order,
110
                        Mage::getStoreConfig('payment/payture/sendadmin'),
111
                        Mage::getStoreConfig('payment/payture/text')
112
                    );
113
                }
114
            } catch (Exception $e) {
115
                $order->addStatusHistoryComment(
116
                    'Payture_Invoicer: Exception occurred during automaticall transaction action. Exception message: ' . $e->getMessage(),
117
                    false
118
                );
119
                $order->save();
120
            }
121
        }
122
    }
123
124
    private function sendCustomComment($order, $toemail, $comment)
125
    {
126
        $storeId = $order->getStore()->getId();
127
128
        $mailer    = Mage::getModel('core/email_template_mailer');
129
        $emailInfo = Mage::getModel('core/email_info');
130
        $emailInfo->addTo($toemail, Mage::getStoreConfig('trans_email/ident_sales/name'));
131
132
        if ($order->getCustomerIsGuest()) {
133
            $templateId = Mage::getStoreConfig(self::XML_PATH_UPDATE_EMAIL_GUEST_TEMPLATE, $storeId);
134
        } else {
135
            $templateId = Mage::getStoreConfig(self::XML_PATH_UPDATE_EMAIL_TEMPLATE, $storeId);
136
        }
137
        $mailer->addEmailInfo($emailInfo);
138
139
        $mailer->setSender(Mage::getStoreConfig(self::XML_PATH_UPDATE_EMAIL_IDENTITY, $storeId));
140
        $mailer->setStoreId($storeId);
141
        $mailer->setTemplateId($templateId);
142
        $mailer->setTemplateParams(array(
143
            'order'   => $order,
144
            'comment' => $comment,
145
            'billing' => $order->getBillingAddress()
146
        ));
147
        $mailer->send();
148
    }
149
150
    public function checkTicket($_ticket)
151
    {
152
        $url = $this->getHost() . 'PayStatus?Key=' . $this->getKey() . '&OrderId=' . $_ticket->getOrderid();
153
        $xml = simplexml_load_string($this->getData($url));
154
        if ($xml['Success'] == 'True') {
155
            Mage::getModel('payture/payture')->processStatus(
156
                $xml["State"],
157
                $_ticket->getOrderid(),
158
                $_ticket->getId()
159
            );
160
        }
161
    }
162
163
    public function getHost()
164
    {
165
        if (Mage::getStoreConfig('payment/payture/test')) {
166
            return 'https://sandbox3.payture.com/apim/';
167
        }
168
        return 'https://secure.payture.com/apim/';
169
    }
170
171
    public function getData($url)
172
    {
173
        // @codingStandardsIgnoreStart
174
        $ch      = curl_init();
175
        $timeout = 10;
176
        curl_setopt($ch, CURLOPT_URL, $url);
177
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
178
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
179
        $data    = curl_exec($ch);
180
        curl_close($ch);
181
        // @codingStandardsIgnoreEnd
182
        $this->addLog($data);
183
        return $data;
184
    }
185
186
    /**
187
     *
188
     * @param type string
189
     * @return mixed
190
     */
191
    public function getConfig($param)
192
    {
193
        return Mage::getStoreConfig('payment/payture/' . $param);
194
    }
195
196
    /**
197
     *
198
     * @param $entity Mage_Sales_Model_Order | Mage_Sales_Model_Order_Invoice | Mage_Sales_Model_Order_Creditmemo
199
     * @return type
200
     */
201
    public function getOrderItemsJson($entity)
202
    {
203
        $shippingTax   = Mage::getStoreConfig('payment/payture/shipping_tax');
204
        $taxValue      = Mage::getStoreConfig('payment/payture/tax_options');
205
        $attributeCode = '';
206
207
        if (!Mage::getStoreConfig('payment/payture/tax_all')) {
208
            $attributeCode = Mage::getStoreConfig('payment/payture/product_tax_attr');
209
        }
210
211
        if (!Mage::getStoreConfig('payment/payture/default_shipping_name')) {
212
            $entity->setShippingDescription(Mage::getStoreConfig('payment/payture/custom_shipping_name'));
213
        }
214
215
        $data   = Mage::helper('payture/discount')->getRecalculated(
216
            $entity,
217
            $taxValue,
218
            $attributeCode,
219
            $shippingTax
220
        );
221
        $result = [];
222
        foreach ($data['items'] as $item) {
223
            $result['Positions'][] = [
224
                'Quantity' => $item['quantity'],
225
                'Price'    => $item['price'],
226
                'Tax'      => $item['tax'],
227
                'Text'     => $item['name'],
228
            ];
229
        }
230
231
        $result['CustomerContact'] = $entity->getCustomerEmail();
232
233
        return Mage::helper('core')->jsonEncode($result);
234
    }
235
236
    public function isPaidBy($order)
237
    {
238
        if (strpos($order->getPayment()->getMethod(), 'payture') !== false) {
239
            return true;
240
        }
241
        return false;
242
    }
243
244
    /** Performs a request to Payture and processes incoming data (save to order and payture/key entity)
245
     *
246
     */
247
    public function processTransaction($type, $req, $order)
248
    {
249
        // @codingStandardsIgnoreStart
250
        $this->addLog('Cheque ' . $type . ' base64_json_decode: ' . print_r(Mage::helper('core')->jsonDecode(base64_decode($req['Cheque'])),1));
251
        // @codingStandardsIgnoreEnd
252
        $url = $this->getHost() . $type . '?' . http_build_query($req);
253
        $this->addLog($url);
254
        $xml = $this->getData($url);
255
        $this->addLog($xml);
256
        if ($xml["Success"] == 'True') {
257
            $collection = Mage::getModel('payture/keys')->getCollection();
258
            $collection->addFieldToFilter('orderid', $order->getId());
259
            $item = $collection->getFirstItem();
260
            $sess = Mage::getModel('payture/keys')->load($item->getId());
261
            $sess->setState($type . 'ed');
262
            $sess->save();
263
            $this->addTransaction($order);
264
        }
265
        return $xml;
266
    }
267
}
268