Completed
Push — master ( 371421...0010a1 )
by Iurii
01:53
created

Twocheckout::hookPaymentMethods()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 10
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

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