Completed
Push — master ( 0936f1...724599 )
by Iurii
01:34
created

Authorize::getSetting()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

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