Completed
Push — master ( 72d3ef...5d7ae0 )
by Iurii
03:23
created

Module::getStatus()   B

Complexity

Conditions 5
Paths 5

Size

Total Lines 12
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

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