Completed
Push — master ( 3d848f...67432e )
by Iurii
01:33
created

Main::getStatus()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 5
rs 9.2
c 0
b 0
f 0
cc 4
eloc 3
nc 4
nop 0
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
    gplcart\core\Container;
15
use gplcart\core\exceptions\Dependency as DependencyException;
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 DependencyException
164
     */
165
    protected function getGateway()
166
    {
167
        /* @var $module \gplcart\modules\omnipay_library\Main */
168
        $module = $this->module->getInstance('omnipay_library');
169
        $gateway = $module->getGatewayInstance('AuthorizeNet_SIM');
170
171
        if ($gateway instanceof \Omnipay\AuthorizeNet\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...
172
            return $gateway;
173
        }
174
175
        throw new DependencyException('Gateway must be instance of Omnipay\AuthorizeNet\SIMGateway');
176
    }
177
178
    /**
179
     * Process payment
180
     */
181
    protected function processPurchase()
182
    {
183
        if ($this->controller->isPosted('pay')) {
184
            $this->submitPurchase();
185
        } else if ($this->controller->isQuery('authorize_return')) {
186
            $this->response = $this->getGateway()->completePurchase($this->getPurchaseParams())->send();
187
            if ($this->controller->isQuery('cancel')) {
188
                $this->cancelPurchase();
189
            } else {
190
                $this->finishPurchase();
191
            }
192
        }
193
    }
194
195
    /**
196
     * Performs actions when a payment is canceled
197
     */
198
    protected function cancelPurchase()
199
    {
200
        $this->controller->setMessage($this->controller->text('Payment has been canceled'), 'warning');
201
        $gateway_message = $this->response->getMessage();
202
        if (!empty($gateway_message)) {
203
            $this->controller->setMessage($gateway_message, 'warning');
204
        }
205
    }
206
207
    /**
208
     * Handles submitted payment
209
     */
210
    protected function submitPurchase()
211
    {
212
        $gateway = $this->getGateway();
213
        $gateway->setApiLoginId($this->getSetting('apiLoginId'));
214
        $gateway->setHashSecret($this->getSetting('hashSecret'));
215
        $gateway->setTestMode((bool) $this->getSetting('testMode'));
216
        $gateway->setDeveloperMode((bool) $this->getSetting('testMode'));
217
        $gateway->setTransactionKey($this->getSetting('transactionKey'));
218
219
        $this->response = $gateway->purchase($this->getPurchaseParams())->send();
220
221
        if ($this->response->isRedirect()) {
222
            $this->response->redirect();
223
        } else if (!$this->response->isSuccessful()) {
224
            $this->redirectError();
225
        }
226
    }
227
228
    /**
229
     * Returns an array of purchase parameters
230
     * @return array
231
     */
232
    protected function getPurchaseParams()
233
    {
234
        $url = "checkout/complete/{$this->data_order['order_id']}";
235
236
        return array(
237
            'currency' => $this->data_order['currency'],
238
            'amount' => $this->data_order['total_formatted_number'],
239
            'returnUrl' => $this->controller->url($url, array('authorize_return' => true), true),
240
            'cancelUrl' => $this->controller->url($url, array('authorize_return' => true, 'cancel' => true), true)
241
        );
242
    }
243
244
    /**
245
     * Performs final actions on success payment
246
     */
247
    protected function finishPurchase()
248
    {
249
        if ($this->response->isSuccessful()) {
250
            $this->updateOrderStatus();
251
            $this->addTransaction();
252
            $this->redirectSuccess();
253
        } else if ($this->response->isRedirect()) {
254
            $this->response->redirect();
255
        } else {
256
            $this->redirectError();
257
        }
258
    }
259
260
    /**
261
     * Redirect on error payment
262
     */
263
    protected function redirectError()
264
    {
265
        $this->controller->redirect('', $this->response->getMessage(), 'warning', true);
266
    }
267
268
    /**
269
     * Redirect on successful payment
270
     */
271
    protected function redirectSuccess()
272
    {
273
        $vars = array(
274
            '@num' => $this->data_order['order_id'],
275
            '@status' => $this->order->getStatusName($this->data_order['status'])
276
        );
277
278
        $message = $this->controller->text('Thank you! Payment has been made. Order #@num, status: @status', $vars);
279
        $this->controller->redirect('/', $message, 'success', true);
280
    }
281
282
    /**
283
     * Update order status after successful transaction
284
     */
285
    protected function updateOrderStatus()
286
    {
287
        $data = array('status' => $this->getSetting('order_status_success'));
288
        $this->order->update($this->data_order['order_id'], $data);
289
        $this->data_order = $this->order->get($this->data_order['order_id']);
290
    }
291
292
    /**
293
     * Adds a transaction
294
     */
295
    protected function addTransaction()
296
    {
297
        /* @var $model \gplcart\core\models\Transaction */
298
        $model = Container::get('gplcart\\core\\models\\Transaction');
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
        return $model->add($transaction);
309
    }
310
311
    /**
312
     * Returns the current status for the payment method
313
     * @return bool
314
     */
315
    protected function getStatus()
316
    {
317
        return $this->getSetting('status') && $this->getSetting('apiLoginId')//
318
                && $this->getSetting('hashSecret') && $this->getSetting('transactionKey');
319
    }
320
321
    /**
322
     * Returns a module setting
323
     * @param string $name
324
     * @param mixed $default
325
     * @return mixed
326
     */
327
    protected function getSetting($name, $default = null)
328
    {
329
        return $this->module->getSettings('authorize', $name, $default);
330
    }
331
332
}
333