Main   B
last analyzed

Complexity

Total Complexity 37

Size/Duplication

Total Lines 317
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Importance

Changes 0
Metric Value
wmc 37
lcom 1
cbo 0
dl 0
loc 317
rs 8.6
c 0
b 0
f 0

20 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A hookRouteList() 0 9 1
A hookModuleEnableBefore() 0 8 2
A hookModuleInstallBefore() 0 8 2
A hookPaymentMethods() 0 10 1
A hookOrderAddBefore() 0 8 2
A hookOrderCompleteMessage() 0 6 2
A hookOrderCompletePage() 0 11 2
A getGateway() 0 14 2
A processPurchase() 0 13 4
A cancelPurchase() 0 8 2
A submitPurchase() 0 17 3
A getPurchaseParams() 0 11 1
A finishPurchase() 0 12 3
A redirectError() 0 4 1
A redirectSuccess() 0 10 1
A updateOrderStatus() 0 6 1
A addTransaction() 0 15 1
A getStatus() 0 7 4
A getSetting() 0 4 1
1
<?php
2
3
/**
4
 * @package Authorize.Net
5
 * @author Iurii Makukh <[email protected]>
6
 * @copyright Copyright (c) 2017, Iurii Makukh <[email protected]>
7
 * @license https://www.gnu.org/licenses/gpl-3.0.en.html GNU General Public License 3.0
8
 */
9
10
namespace gplcart\modules\authorize;
11
12
use Exception;
13
use gplcart\core\Module;
14
use Omnipay\AuthorizeNet\SIMGateway;
15
use UnexpectedValueException;
16
17
/**
18
 * Main class for Authorize.Net module
19
 */
20
class Main
21
{
22
23
    /**
24
     * The current order
25
     * @var array
26
     */
27
    protected $data_order;
28
29
    /**
30
     * Omnipay response instance
31
     * @var object
32
     */
33
    protected $response;
34
35
    /**
36
     * Frontend controller instance
37
     * @var \gplcart\core\controllers\frontend\Controller $controller
38
     */
39
    protected $controller;
40
41
    /**
42
     * Order model instance
43
     * @var \gplcart\core\models\Order $order
44
     */
45
    protected $order;
46
47
    /**
48
     * Module class instance
49
     * @var \gplcart\core\Module
50
     */
51
    protected $module;
52
53
    /**
54
     * @param Module $module
55
     */
56
    public function __construct(Module $module)
57
    {
58
        $this->module = $module;
59
    }
60
61
    /**
62
     * Implements hook "route.list"
63
     * @param array $routes
64
     */
65
    public function hookRouteList(array &$routes)
66
    {
67
        $routes['admin/module/settings/authorize'] = array(
68
            'access' => 'module_edit',
69
            'handlers' => array(
70
                'controller' => array('gplcart\\modules\\authorize\\controllers\\Settings', 'editSettings')
71
            )
72
        );
73
    }
74
75
    /**
76
     * Implements hook "module.enable.before"
77
     * @param mixed $result
78
     */
79
    public function hookModuleEnableBefore(&$result)
80
    {
81
        try {
82
            $this->getGateway();
83
        } catch (Exception $ex) {
84
            $result = $ex->getMessage();
85
        }
86
    }
87
88
    /**
89
     * Implements hook "module.install.before"
90
     * @param mixed $result
91
     */
92
    public function hookModuleInstallBefore(&$result)
93
    {
94
        try {
95
            $this->getGateway();
96
        } catch (Exception $ex) {
97
            $result = $ex->getMessage();
98
        }
99
    }
100
101
    /**
102
     * Implements hook "payment.methods"
103
     * @param array $methods
104
     */
105
    public function hookPaymentMethods(array &$methods)
106
    {
107
        $methods['authorize_sim'] = array(
108
            'module' => 'authorize',
109
            'image' => 'image/icon.png',
110
            'status' => $this->getStatus(),
111
            'title' => 'Authorize.Net',
112
            'template' => array('complete' => 'pay')
113
        );
114
    }
115
116
    /**
117
     * Implements hook "order.add.before"
118
     * @param array $order
119
     * @param \gplcart\core\models\Order $order_model
120
     */
121
    public function hookOrderAddBefore(array &$order, $order_model)
122
    {
123
        // Adjust order status before creation
124
        // We want to get payment in advance, so assign "awaiting payment" status
125
        if ($order['payment'] === 'authorize_sim') {
126
            $order['status'] = $order_model->getStatusAwaitingPayment();
127
        }
128
    }
129
130
    /**
131
     * Implements hook "order.checkout.complete"
132
     * @param string $message
133
     * @param array $order
134
     */
135
    public function hookOrderCompleteMessage(&$message, $order)
136
    {
137
        if ($order['payment'] === 'authorize_sim') {
138
            $message = ''; // Hide default message
139
        }
140
    }
141
142
    /**
143
     * Implements hook "order.complete.page"
144
     * @param array $order
145
     * @param \gplcart\core\models\Order $order_model
146
     * @param \gplcart\core\controllers\frontend\Controller $controller
147
     */
148
    public function hookOrderCompletePage(array $order, $order_model, $controller)
149
    {
150
        if ($order['payment'] === 'authorize_sim') {
151
152
            $this->data_order = $order;
153
            $this->order = $order_model;
154
            $this->controller = $controller;
155
156
            $this->processPurchase();
157
        }
158
    }
159
160
    /**
161
     * Get gateway instance
162
     * @return \Omnipay\AuthorizeNet\SIMGateway
163
     * @throws UnexpectedValueException
164
     */
165
    protected function getGateway()
166
    {
167
        /* @var $module \gplcart\modules\omnipay_library\Main */
168
        $module = $this->module->getInstance('omnipay_library');
169
170
        /** @var \Omnipay\AuthorizeNet\SIMGateway $gateway */
171
        $gateway = $module->getGatewayInstance('AuthorizeNet_SIM');
172
173
        if (!$gateway instanceof SIMGateway) {
0 ignored issues
show
Bug introduced by
The class Omnipay\AuthorizeNet\SIMGateway 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...
174
            throw new UnexpectedValueException('Gateway must be instance of Omnipay\AuthorizeNet\SIMGateway');
175
        }
176
177
        return $gateway;
178
    }
179
180
    /**
181
     * Process payment
182
     */
183
    protected function processPurchase()
184
    {
185
        if ($this->controller->isPosted('pay')) {
186
            $this->submitPurchase();
187
        } else if ($this->controller->isQuery('authorize_return')) {
188
            $this->response = $this->getGateway()->completePurchase($this->getPurchaseParams())->send();
189
            if ($this->controller->isQuery('cancel')) {
190
                $this->cancelPurchase();
191
            } else {
192
                $this->finishPurchase();
193
            }
194
        }
195
    }
196
197
    /**
198
     * Performs actions when a payment is canceled
199
     */
200
    protected function cancelPurchase()
201
    {
202
        $this->controller->setMessage($this->controller->text('Payment has been canceled'), 'warning');
203
        $gateway_message = $this->response->getMessage();
204
        if (!empty($gateway_message)) {
205
            $this->controller->setMessage($gateway_message, 'warning');
206
        }
207
    }
208
209
    /**
210
     * Handles submitted payment
211
     */
212
    protected function submitPurchase()
213
    {
214
        $gateway = $this->getGateway();
215
        $gateway->setApiLoginId($this->getSetting('apiLoginId'));
216
        $gateway->setHashSecret($this->getSetting('hashSecret'));
217
        $gateway->setTestMode((bool) $this->getSetting('testMode'));
218
        $gateway->setDeveloperMode((bool) $this->getSetting('testMode'));
219
        $gateway->setTransactionKey($this->getSetting('transactionKey'));
220
221
        $this->response = $gateway->purchase($this->getPurchaseParams())->send();
222
223
        if ($this->response->isRedirect()) {
224
            $this->response->redirect();
225
        } else if (!$this->response->isSuccessful()) {
226
            $this->redirectError();
227
        }
228
    }
229
230
    /**
231
     * Returns an array of purchase parameters
232
     * @return array
233
     */
234
    protected function getPurchaseParams()
235
    {
236
        $url = "checkout/complete/{$this->data_order['order_id']}";
237
238
        return array(
239
            'currency' => $this->data_order['currency'],
240
            'amount' => $this->data_order['total_formatted_number'],
241
            'returnUrl' => $this->controller->url($url, array('authorize_return' => true), true),
242
            'cancelUrl' => $this->controller->url($url, array('authorize_return' => true, 'cancel' => true), true)
243
        );
244
    }
245
246
    /**
247
     * Performs final actions on success payment
248
     */
249
    protected function finishPurchase()
250
    {
251
        if ($this->response->isSuccessful()) {
252
            $this->updateOrderStatus();
253
            $this->addTransaction();
254
            $this->redirectSuccess();
255
        } else if ($this->response->isRedirect()) {
256
            $this->response->redirect();
257
        } else {
258
            $this->redirectError();
259
        }
260
    }
261
262
    /**
263
     * Redirect on error payment
264
     */
265
    protected function redirectError()
266
    {
267
        $this->controller->redirect('', $this->response->getMessage(), 'warning', true);
268
    }
269
270
    /**
271
     * Redirect on successful payment
272
     */
273
    protected function redirectSuccess()
274
    {
275
        $vars = array(
276
            '@num' => $this->data_order['order_id'],
277
            '@status' => $this->order->getStatusName($this->data_order['status'])
278
        );
279
280
        $message = $this->controller->text('Thank you! Payment has been made. Order #@num, status: @status', $vars);
281
        $this->controller->redirect('/', $message, 'success', true);
282
    }
283
284
    /**
285
     * Update order status after successful transaction
286
     */
287
    protected function updateOrderStatus()
288
    {
289
        $data = array('status' => $this->getSetting('order_status_success'));
290
        $this->order->update($this->data_order['order_id'], $data);
291
        $this->data_order = $this->order->get($this->data_order['order_id']);
292
    }
293
294
    /**
295
     * Adds a transaction
296
     */
297
    protected function addTransaction()
298
    {
299
300
        $transaction = array(
301
            'total' => $this->data_order['total'],
302
            'order_id' => $this->data_order['order_id'],
303
            'currency' => $this->data_order['currency'],
304
            'payment_method' => $this->data_order['payment'],
305
            'gateway_transaction_id' => $this->response->getTransactionReference()
306
        );
307
308
        /* @var $model \gplcart\core\models\Transaction */
309
        $model = gplcart_instance_model('Transaction');
310
        return $model->add($transaction);
311
    }
312
313
    /**
314
     * Returns the current status for the payment method
315
     * @return bool
316
     */
317
    protected function getStatus()
318
    {
319
        return $this->getSetting('status')
320
            && $this->getSetting('apiLoginId')
321
            && $this->getSetting('hashSecret')
322
            && $this->getSetting('transactionKey');
323
    }
324
325
    /**
326
     * Returns a module setting
327
     * @param string $name
328
     * @param mixed $default
329
     * @return mixed
330
     */
331
    protected function getSetting($name, $default = null)
332
    {
333
        return $this->module->getSettings('authorize', $name, $default);
334
    }
335
336
}
337