LaravelMobilpayController::card()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 5
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
1
<?php
2
3
namespace Stl30\LaravelMobilpay\Http\Controllers;
4
5
use App\LaravelMobilpay\LaravelMobilpayCustomActionsAndNotifications;
6
use \Exception;
7
use Illuminate\Http\Request;
8
use Illuminate\Support\Facades\Log;
9
use Illuminate\Support\Facades\Validator;
10
use Netopia\Payment\Address;
11
use Netopia\Payment\Request\Card;
12
use Netopia\Payment\Request\PaymentAbstract;
13
use Stl30\LaravelMobilpay\CustomActionsAndNotifications;
14
use Stl30\LaravelMobilpay\Mobilpay\Payment\Request\Mobilpay_Payment_Request_Abstract;
15
use Stl30\LaravelMobilpay\Mobilpay\Payment\Request\Mobilpay_Payment_Request_Card;
16
use Stl30\LaravelMobilpay\Mobilpay\Payment\Invoice;
17
use Stl30\LaravelMobilpay\Mobilpay\Payment\Mobilpay_Payment_Address;
18
use Stl30\LaravelMobilpay\Mobilpay\Payment\Request\Mobilpay_Payment_Request_Notify;
19
use Stl30\LaravelMobilpay\Mobilpay\Payment\Mobilpay_Payment_Invoice;
20
use Stl30\LaravelMobilpay\MobilpayTransaction;
21
22
class LaravelMobilpayController extends Controller
23
{
24
    /**
25
     * @var CustomActionsAndNotifications
26
     */
27
    public $actionsAndNotifications;
28
29
    public function __construct()
30
    {
31
        $this->actionsAndNotifications = new LaravelMobilpayCustomActionsAndNotifications();
32
    }
33
34
    public function card()
35
    {
36
        //
37
        return view('vendor.laravel-mobilpay.card');
38
    }
39
40
    public function addTransaction(Card $mobilpayRequestObject, $customDataParameter = '')
41
    {
42
        $this->actionsAndNotifications->setActions([
43
            'transaction' => 'start create',
44
            'time' => date('Y-m-d H:i:s')
45
        ]);
46
47
        $this->actionsAndNotifications->beforeCreatingTransaction($mobilpayRequestObject, $customDataParameter);
48
        $transaction = new MobilpayTransaction();
49
        $transaction->id_transaction = $mobilpayRequestObject->orderId;
50
        $transaction->request_status = 0;
51
        $transaction->status = 'initiated';
52
        $transaction->value = $mobilpayRequestObject->invoice->amount;
53
        $transaction->currency = $mobilpayRequestObject->invoice->currency;
54
        $transaction->details = $mobilpayRequestObject->invoice->details;
55
        $transaction->type = $mobilpayRequestObject->invoice->getBillingAddress()->type ?? null;
56
        $transaction->client_name = $mobilpayRequestObject->invoice->getBillingAddress()->firstName ?? null;
57
        $transaction->client_surname = $mobilpayRequestObject->invoice->getBillingAddress()->lastName ?? null;
58
        $transaction->client_email = $mobilpayRequestObject->invoice->getBillingAddress()->email ?? null;
59
        $transaction->client_address = $mobilpayRequestObject->invoice->getBillingAddress()->address ?? null;
60
        $transaction->client_phone = $mobilpayRequestObject->invoice->getBillingAddress()->mobilePhone ?? null;
61
        $transaction->client_fiscal_number = $mobilpayRequestObject->invoice->getBillingAddress()->fiscal_number ?? null;
62
        $transaction->client_identity_number = $mobilpayRequestObject->invoice->getBillingAddress()->identity_number ?? null;
63
        $transaction->client_country = $mobilpayRequestObject->invoice->getBillingAddress()->country ?? null;
64
        $transaction->client_county = $mobilpayRequestObject->invoice->getBillingAddress()->county ?? null;
65
        $transaction->client_city = $mobilpayRequestObject->invoice->getBillingAddress()->city ?? null;
66
        $transaction->client_zip_code = $mobilpayRequestObject->invoice->getBillingAddress()->zip_code ?? null;
67
        $transaction->client_bank = $mobilpayRequestObject->invoice->getBillingAddress()->bank ?? null;
68
        $transaction->client_iban = $mobilpayRequestObject->invoice->getBillingAddress()->iban ?? null;
69
        $transaction->request_object = json_encode($mobilpayRequestObject, true);
70
        $transaction->custom_data = $customDataParameter;
71
        $addTransactionIsSuccessful = $transaction->save();
72
73
        if ($addTransactionIsSuccessful) {
74
            $this->actionsAndNotifications->setNotifications([
75
                'request_status' => $transaction->request_status,
76
                'id_transaction_created' => $transaction->id,
77
            ]);
78
            $this->actionsAndNotifications->setActions([
79
                'transaction' => 'successfully created',
80
            ]);
81
        }
82
83
84
        $this->actionsAndNotifications->afterCreatingTransaction($transaction, $addTransactionIsSuccessful);
85
86
        return $addTransactionIsSuccessful;
87
    }
88
89
    public function updateTransaction(PaymentAbstract $mobilpayReturnObject, $orderStatus = 'possible error')
90
    {
91
        $this->actionsAndNotifications->setActions([
92
            'transaction' => 'start update',
93
            'time' => date('Y-m-d H:i:s')
94
        ]);
95
96
        $this->actionsAndNotifications->beforeUpdatingTransaction($mobilpayReturnObject, $orderStatus);
97
98
        $transaction = MobilpayTransaction::where('id_transaction', '=', $mobilpayReturnObject->orderId)->firstOrFail();
99
        if (isset($mobilpayReturnObject->objPmNotify->token_id) && strlen($mobilpayReturnObject->objPmNotify->token_id)) {
100
            $transaction->token_id = $mobilpayReturnObject->objPmNotify->token_id;
101
            $transaction->token_expiration_date = $mobilpayReturnObject->objPmNotify->token_expiration_date;
102
        }
103
        $transaction->value = $mobilpayReturnObject->invoice->amount;
104
        $transaction->currency = $mobilpayReturnObject->invoice->currency;
105
        $transaction->details = $mobilpayReturnObject->invoice->details;
106
        $transaction->request_status = 1;
107
        $transaction->status = $orderStatus;
108
        $transaction->client_name = $mobilpayReturnObject->objPmNotify->customer->firstName;
109
        $transaction->client_surname = $mobilpayReturnObject->objPmNotify->customer->lastName;
110
        $transaction->client_address = $mobilpayReturnObject->objPmNotify->customer->address;
111
        $transaction->client_email = $mobilpayReturnObject->objPmNotify->customer->email;
112
        $transaction->client_phone = $mobilpayReturnObject->objPmNotify->customer->mobilePhone;
113
        $transaction->return_request_object = json_encode($mobilpayReturnObject, true);
114
        $updatedIsSuccessful = $transaction->update();
115
116 View Code Duplication
        if ($updatedIsSuccessful) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
117
            $this->actionsAndNotifications->setNotifications([
118
                'status' => $transaction->status,
119
                'request_status' => $transaction->request_status,
120
                'id_transaction_created' => $transaction->id,
121
            ]);
122
            $this->actionsAndNotifications->setActions([
123
                'transaction' => 'successfully updated',
124
                'time' => date('Y-m-d H:i:s')
125
            ]);
126
        }
127
128
        $this->actionsAndNotifications->afterUpdatingTransaction($transaction, $updatedIsSuccessful);
129
130
        return $updatedIsSuccessful;
131
    }
132
133
    function addAutomatedTransactionError($errorCode, $errorType, $errorMessage, $mobilpayReturnObject)
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
134
    {
135
        $this->actionsAndNotifications->setActions([
136
            'error transaction' => 'start creating',
137
            'time' => date('Y-m-d H:i:s')
138
        ]);
139
140
        $transaction = new MobilpayTransaction();
141
        $transaction->id_transaction = 'error code:'.$errorCode.'>> error type:'.$errorType.'>> error message:'.$errorMessage;
142
        $transaction->request_status = $errorType;
143
        $transaction->request_object = json_encode($mobilpayReturnObject, true);
144
        $transaction->status = $errorMessage;
145
        $addTransactionIsSuccessful = $transaction->save();
146
147 View Code Duplication
        if ($addTransactionIsSuccessful) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
148
            $this->actionsAndNotifications->setNotifications([
149
                'status' => $transaction->status,
150
                'request_status' => $transaction->request_status,
151
            ]);
152
            $this->actionsAndNotifications->setActions([
153
                'error transaction' => 'successfully created',
154
                'time' => date('Y-m-d H:i:s')
155
            ]);
156
        }
157
158
        $this -> actionsAndNotifications ->onTransactionError($errorCode, $errorType, $errorMessage, $mobilpayReturnObject);
159
160
        return $addTransactionIsSuccessful;
161
    }
162
163
    public static function validatePaymentDetails(array $parameters = [])
164
    {
165
        $errorsText = [];
166
        $paymentParameters = [];
167
        $requiredParameters = [
168
            #must haves values
169
            'payment_amount' => 'value of payment',
170
            'payment_details' => 'payment details placeholder',
171
            'order_id' => '',
172
            'billing_type' => 'person',//or company
173
        ];
174
        foreach ($requiredParameters as $requiredName => $value) {
175 View Code Duplication
            if (isset($parameters[$requiredName]) && $parameters[$requiredName] !== null) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
176
                $paymentParameters[$requiredName] = $parameters[$requiredName];
177
                continue;
178
            }
179
            $errorsText['errors'][]= 'Missing required parameter '.$requiredName;
180
        }
181
        if (count($errorsText)) {
182
            echo '<pre>';
183
            var_dump('>>>>>');
0 ignored issues
show
Security Debugging Code introduced by
var_dump('>>>>>'); looks like debug code. Are you sure you do not want to remove it? This might expose sensitive data.
Loading history...
184
            print_r($errorsText);
185
            echo('</pre>');
186
            die('>>>>>>>>>>>>>>>>>><<<<<<<<<<');
187
188
        }
189
190
        $optionalParameters = [
191
            #custom data / if you need some custom data save on the transactions table
192
            'custom_data' => '',
193
            #optional values
194
            'promotion_code' => '',
195
            'currency' => '',
196
            #details on the cardholder address (optional)
197
198
            'billing_first_name' => '',//client first name
199
            'billing_last_name' => '',//client last name
200
            'billing_address' => '',//client adress
201
            'billing_email' => '',//client email
202
            'billing_mobile_phone' => '',//client phone/mobile
203
            'billing_fiscal_number' => '',
204
            'billing_identity_number' => '',
205
            'billing_country' => '',
206
            'billing_county' => '',
207
            'billing_city' => '',
208
            'billing_zip_code' => '',
209
            'billing_bank' => '',
210
            'billing_iban' => '',
211
            #details on the shipping address
212
            'shipping_type' => 'person',//or company
213
            'shipping_first_name' => '',
214
            'shipping_last_name' => '',
215
            'shipping_address' => '',
216
            'shipping_email' => '',
217
            'shipping_mobile_phone' => '',
218
            'shipping_fiscal_number' => '',
219
            'shipping_identity_number' => '',
220
            'shipping_country' => '',
221
            'shipping_county' => '',
222
            'shipping_city' => '',
223
            'shipping_zip_code' => '',
224
            'shipping_bank' => '',
225
            'shipping_iban' => '',
226
        ];
227
228
229
        foreach ($optionalParameters as $key => $Value) {
230 View Code Duplication
            if (isset($parameters[$key]) && $parameters[$key] !== null) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
231
                $paymentParameters[$key] = $parameters[$key];
232
            }
233
        }
234
235
        return $paymentParameters;
236
    }
237
238
    public function cardRedirect(array $paymentParameters = array(),$returnOnlyData = false)
239
    {
240
        $paymentParameters = self::validatePaymentDetails($paymentParameters);
241
242
        #for testing purposes, all payment requests will be sent to the sandbox server. Once your account will be active you must switch back to the live server https://secure.mobilpay.ro
243
        #in order to display the payment form in a different language, simply add the language identifier to the end of the paymentUrl, i.e https://secure.mobilpay.ro/en for English
244
        if (config('laravel-mobilpay.sandbox_active')) {
245
            $paymentUrl = config('laravel-mobilpay.sandbox_payment_link');
246
        } else {
247
            $paymentUrl = config('laravel-mobilpay.production_payment_link');
248
        }
249
250
        //$paymentUrl = 'https://secure.mobilpay.ro';
251
        // this is the path on your server to the public certificate. You may download this from Admin -> Conturi de comerciant -> Detalii -> Setari securitate
252
//        $x509FilePath 	= 'i.e: /home/certificates/public.cer';
253
254
        if (!config('laravel-mobilpay.sandbox_active')) {
255
            $x509FilePath = config('laravel-mobilpay.sandbox_public_key');
256
        } else {
257
            $x509FilePath = config('laravel-mobilpay.production_public_key');
258
        }
259
260
        try {
261
            mt_srand((double)microtime() * 1000000);
262
            $objPmReqCard = new Card();
263
            #merchant account signature - generated by mobilpay.ro for every merchant account
264
            #semnatura contului de comerciant - mergi pe www.mobilpay.ro Admin -> Conturi de comerciant -> Detalii -> Setari securitate
265
            $objPmReqCard->signature = config('laravel-mobilpay.merchant_account_signature');
266
            #you should assign here the transaction ID registered by your application for this commercial operation
267
            #order_id should be unique for a merchant account
268
            $objPmReqCard->orderId = $paymentParameters['order_id'];
269
            #below is where mobilPay will send the payment result. This URL will always be called first; mandatory
270
            $objPmReqCard->confirmUrl = config('laravel-mobilpay.confirmUrl');
271
            #below is where mobilPay redirects the client once the payment process is finished. Not to be mistaken for a "successURL" nor "cancelURL"; mandatory
272
            $objPmReqCard->returnUrl = config('laravel-mobilpay.returnUrl');
273
274
            #detalii cu privire la plata: moneda, suma, descrierea
275
            #payment details: currency, amount, description
276
            $objPmReqCard->invoice = new \Netopia\Payment\Invoice();
277
            #payment currency in ISO Code format; permitted values are RON, EUR, USD, MDL; please note that unless you have mobilPay permission to
278
            #process a currency different from RON, a currency exchange will occur from your currency to RON, using the official BNR exchange rate from that moment
279
            #and the customer will be presented with the payment amount in a dual currency in the payment page, i.e N.NN RON (e.ee EUR)
280
            $objPmReqCard->invoice->currency = $paymentParameters['currency'] ?? config('laravel-mobilpay.currency');
281
            $objPmReqCard->invoice->amount = $paymentParameters['payment_amount'];
282
            #available installments number; if this parameter is present, only its value(s) will be available
283
            //$objPmReqCard->invoice->installments= '2,3';
284
            #selected installments number; its value should be within the available installments defined above
285
            //$objPmReqCard->invoice->selectedInstallments= '3';
286
            //platile ulterioare vor contine in request si informatiile despre token. Prima plata nu va contine linia de mai jos.
287
            if ($paymentParameters['token_id'] ?? false) {
288
                $objPmReqCard->invoice->tokenId = $paymentParameters['token_id'];
289
            }
290
291
            $objPmReqCard->invoice->details = $paymentParameters['payment_details'];
292
293
            #detalii cu privire la adresa posesorului cardului
294
            #details on the cardholder address (optional)
295
            $billingAddress = new Address();
296
            $billingAddress->type = $paymentParameters['billing_type']; //should be "person"
297
            $billingAddress->firstName = $paymentParameters['billing_first_name'] ?? null;
298
            $billingAddress->lastName = $paymentParameters['billing_last_name'] ?? null;
299
            $billingAddress->address = $paymentParameters['billing_address'] ?? null;
300
            $billingAddress->email = $paymentParameters['billing_email'] ?? null;
301
            $billingAddress->mobilePhone = $paymentParameters['billing_mobile_phone'] ?? null;
302
            $billingAddress->fiscal_number = $paymentParameters['billing_fiscal_number'] ?? null;
0 ignored issues
show
Bug introduced by
The property fiscal_number does not seem to exist in Netopia\Payment\Address.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
303
            $billingAddress->identity_number = $paymentParameters['billing_identity_number'] ?? null;
0 ignored issues
show
Bug introduced by
The property identity_number does not seem to exist in Netopia\Payment\Address.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
304
            $billingAddress->country = $paymentParameters['billing_country'] ?? null;
0 ignored issues
show
Bug introduced by
The property country does not seem to exist in Netopia\Payment\Address.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
305
            $billingAddress->county = $paymentParameters['billing_county'] ?? null;
0 ignored issues
show
Bug introduced by
The property county does not seem to exist in Netopia\Payment\Address.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
306
            $billingAddress->city = $paymentParameters['billing_city'] ?? null;
0 ignored issues
show
Bug introduced by
The property city does not seem to exist in Netopia\Payment\Address.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
307
            $billingAddress->zip_code = $paymentParameters['billing_zip_code'] ?? null;
0 ignored issues
show
Bug introduced by
The property zip_code does not seem to exist in Netopia\Payment\Address.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
308
            $billingAddress->bank = $paymentParameters['billing_bank'] ?? null;
0 ignored issues
show
Bug introduced by
The property bank does not seem to exist in Netopia\Payment\Address.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
309
            $billingAddress->iban = $paymentParameters['billing_iban'] ?? null;
0 ignored issues
show
Bug introduced by
The property iban does not seem to exist in Netopia\Payment\Address.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
310
            $objPmReqCard->invoice->setBillingAddress($billingAddress);
311
312
            #detalii cu privire la adresa de livrare
313
            #details on the shipping address
314
            $shippingAddress = new Address();
315
            $shippingAddress->type = $paymentParameters['shipping_type'] ?? null;
316
            $shippingAddress->firstName = $paymentParameters['shipping_first_name'] ?? null;
317
            $shippingAddress->lastName = $paymentParameters['shipping_last_name'] ?? null;
318
            $shippingAddress->address = $paymentParameters['shipping_address'] ?? null;
319
            $shippingAddress->email = $paymentParameters['shipping_email'] ?? null;
320
            $shippingAddress->mobilePhone = $paymentParameters['shipping_mobile_phone'] ?? null;
321
            $objPmReqCard->invoice->setShippingAddress($shippingAddress);
322
323
            #uncomment the line below in order to see the content of the request
324
            // TODO for debug
325
//            dd(__METHOD__,$objPmReqCard,$objPmReqCard->signature,$objPmReqCard->orderId,get_class($objPmReqCard->invoice));
326
//            echo "<pre>";print_r($objPmReqCard);echo "</pre>";
327
            $objPmReqCard->encrypt($x509FilePath);
328
            $customDataForTransaction = $paymentParameters['custom_data'] ?? '';
329
            $this->addTransaction($objPmReqCard, $customDataForTransaction);
330
        } catch (\Exception $e) {
331
            $exception = isset($e) ? $e : null;
332
        }
333
        $exception = isset($exception) ? $exception : null;
334
        //
335
        if($returnOnlyData == true) {
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
336
            return [
337
                'paymentUrl' => $paymentUrl,
338
                'env_key' => $objPmReqCard->getEnvKey(),
0 ignored issues
show
Bug introduced by
The variable $objPmReqCard does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
339
                'data' => $objPmReqCard->getEncData(),
340
                'exception' => $exception,
341
                #uncomment the line below in order to see the content of the object created
342
//                'objPmReqCard' => $objPmReqCard,
343
            ];
344
        }
345
        return view('vendor.laravel-mobilpay.cardRedirect')->with([
0 ignored issues
show
Bug introduced by
The method with does only exist in Illuminate\Contracts\View\View, but not in Illuminate\Contracts\View\Factory.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
346
            'env_key' => $objPmReqCard->getEnvKey(),
347
            'data' => $objPmReqCard->getEncData(),
348
            'objPmReqCard' => $objPmReqCard,
349
            'e' => $exception,
350
            'paymentUrl' => $paymentUrl
351
        ]);
352
    }
353
354
    public function cardConfirm()
355
    {
356
        $errorCode = 0;
357
        $errorType = PaymentAbstract::CONFIRM_ERROR_TYPE_NONE;
358
        $errorMessage = '';
359
        $orderStatus = '';
360
        if (strcasecmp($_SERVER['REQUEST_METHOD'], 'post') == 0) {
361
            if (isset($_POST['env_key']) && isset($_POST['data'])) {
362
                #calea catre cheia privata
363
                #cheia privata este generata de mobilpay, accesibil in Admin -> Conturi de comerciant -> Detalii -> Setari securitate
364
                $privateKeyFilePath = config('laravel-mobilpay.sandbox_private_key');
365
366
                try {
367
                    $objPmReq = PaymentAbstract::factoryFromEncrypted($_POST['env_key'], $_POST['data'], $privateKeyFilePath);
368
//                    Log::debug('Obiect venit pe confirm url:'.json_encode($objPmReq,true),json_encode($objPmReq,true));
369
                    #uncomment the line below in order to see the content of the request
370
                    //print_r($objPmReq);
371
                    $rrn = $objPmReq->objPmNotify->rrn;
0 ignored issues
show
Unused Code introduced by
$rrn is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
372
                    // action = status only if the associated error code is zero
373
                    if ($objPmReq->objPmNotify->errorCode == 0) {
374
                        switch ($objPmReq->objPmNotify->action) {
375
                            #orice action este insotit de un cod de eroare si de un mesaj de eroare. Acestea pot fi citite folosind $cod_eroare = $objPmReq->objPmNotify->errorCode; respectiv $mesaj_eroare = $objPmReq->objPmNotify->errorMessage;
376
                            #pentru a identifica ID-ul comenzii pentru care primim rezultatul platii folosim $id_comanda = $objPmReq->orderId;
377
                            case 'confirmed':
378
                                #cand action este confirmed avem certitudinea ca banii au plecat din contul posesorului de card si facem update al starii comenzii si livrarea produsului
379
                                //update DB, SET status = "confirmed/captured"
380
                                $orderStatus = 'confirmed/captured';
381
                                $errorMessage = $objPmReq->objPmNotify->errorMessage;
382
                                break;
383
                            case 'confirmed_pending':
384
                                #cand action este confirmed_pending inseamna ca tranzactia este in curs de verificare antifrauda. Nu facem livrare/expediere. In urma trecerii de aceasta verificare se va primi o noua notificare pentru o actiune de confirmare sau anulare.
385
                                //update DB, SET status = "pending"
386
                                $orderStatus = 'pending';
387
                                $errorMessage = $objPmReq->objPmNotify->errorMessage;
388
                                break;
389
                            case 'paid_pending':
390
                                #cand action este paid_pending inseamna ca tranzactia este in curs de verificare. Nu facem livrare/expediere. In urma trecerii de aceasta verificare se va primi o noua notificare pentru o actiune de confirmare sau anulare.
391
                                //update DB, SET status = "pending"
392
                                $orderStatus = 'pending';
393
                                $errorMessage = $objPmReq->objPmNotify->errorMessage;
394
                                break;
395
                            case 'paid':
396
                                #cand action este paid inseamna ca tranzactia este in curs de procesare. Nu facem livrare/expediere. In urma trecerii de aceasta procesare se va primi o noua notificare pentru o actiune de confirmare sau anulare.
397
                                //update DB, SET status = "open/preauthorized"
398
                                $orderStatus = 'open/preauthorized';
399
                                $errorMessage = $objPmReq->objPmNotify->errorMessage;
400
                                break;
401
                            case 'canceled':
402
                                #cand action este canceled inseamna ca tranzactia este anulata. Nu facem livrare/expediere.
403
                                //update DB, SET status = "canceled"
404
                                $orderStatus = 'canceled';
405
                                $errorMessage = $objPmReq->objPmNotify->errorMessage;
406
                                break;
407
                            case 'credit':
408
                                #cand action este credit inseamna ca banii sunt returnati posesorului de card. Daca s-a facut deja livrare, aceasta trebuie oprita sau facut un reverse.
409
                                //update DB, SET status = "refunded"
410
                                $orderStatus = 'refunded';
411
                                $errorMessage = $objPmReq->objPmNotify->errorMessage;
412
                                break;
413
                            default:
414
                                $errorType = PaymentAbstract::CONFIRM_ERROR_TYPE_PERMANENT;
415
                                $errorCode = PaymentAbstract::ERROR_CONFIRM_INVALID_ACTION;
416
                                $orderStatus = $errorMessage = __('mobilpay_refference_action paramaters is invalid');
417
                                break;
418
                        }
419
                    } else {
420
                        //update DB, SET status = "rejected"
421
                        $orderStatus = 'rejected';
422
                        $errorMessage = $objPmReq->objPmNotify->errorMessage;
423
                    }
424
                } catch (Exception $e) {
425
                    $errorType = PaymentAbstract::CONFIRM_ERROR_TYPE_TEMPORARY;
426
                    $errorCode = $e->getCode();
427
                    $orderStatus = $errorMessage = $e->getMessage();
428
                }
429 View Code Duplication
            } else {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
430
                $errorType = PaymentAbstract::CONFIRM_ERROR_TYPE_PERMANENT;
431
                $errorCode = PaymentAbstract::ERROR_CONFIRM_INVALID_POST_PARAMETERS;
432
                $orderStatus = $errorMessage = __('mobilpay.ro posted invalid parameters');
433
            }
434 View Code Duplication
        } else {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
435
            $errorType = PaymentAbstract::CONFIRM_ERROR_TYPE_PERMANENT;
436
            $errorCode = PaymentAbstract::ERROR_CONFIRM_INVALID_POST_METHOD;
437
            $orderStatus = $errorMessage = __('invalid request method for payment confirmation');
438
        }
439
440
        header('Content-type: application/xml');
441
        echo "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n";
442
        if ($errorCode == 0) {
443
            $updateTransaction = $this->updateTransaction($objPmReq, $orderStatus);
0 ignored issues
show
Bug introduced by
The variable $objPmReq does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
444
            if ($updateTransaction !== true) {
445
//                Log::debug('Could not update transaction <<>> ' . json_encode($objPmReq, true) . ' <<<>>> with orderStatus:' . $orderStatus);
446
            } else {
447
//                Log::debug('Update transaction success <<>> ' . json_encode($objPmReq, true) . ' <<<>>> with orderStatus:' . $orderStatus);
448
            }
449
//            Log::debug('No errors');
450
//            Log::debug(json_encode($errorMessage, true));
451
            echo "<crc>{$errorMessage}</crc>";
452
        } else {
453
            $objPmReq = (isset($objPmReq) && is_object($objPmReq)) ? $objPmReq : '';
454
            if ($this->addAutomatedTransactionError($errorCode, $errorType, $errorMessage, $objPmReq) !== true) {
455
                Log::debug('Could not addAutomatedTransactionError <<>> errortype:'.$errorType.'<<<>>> error code:'.$errorCode.'<<<<>>>'.json_encode($errorMessage, true));
456
            } else {
457
//                Log::debug('addedAutomatedTransactionError <<>> errortype:' . $errorType . '<<<>>> error code:' . $errorCode . '<<<<>>>' . json_encode($errorMessage, true));
458
            }
459
//            Log::debug('With errors');
460
//            Log::debug('errortype:' . $errorType . '<<<>>> error code:' . $errorCode . '<<<<>>>' . json_encode($errorMessage, true));
461
            echo "<crc error_type=\"{$errorType}\" error_code=\"{$errorCode}\">{$errorMessage}</crc>";
462
        }
463
    }
464
465
    public function cardReturn(Request $request)
466
    {
467
        $orderStatus = 'eroare';
468
        $orderId = (isset($request->orderId) && $request->orderId !== null) ? $request->orderId : '';
469
        $order = MobilpayTransaction::where('id_transaction', '=', $request->orderId)->first();
470
        if ($order !== null) {
471
            switch ($order->status) {
472
                case 'confirmed/captured':
473
                    $orderStatus = 'succes';
474
                    break;
475
                case 'rejected':
476
                    $orderStatus = 'rejected';
477
                    break;
478
                case 'pending':
479
                    $orderStatus = 'pending';
480
                    break;
481
                default:
482
                    $orderStatus = 'error';
483
                    break;
484
            }
485
        }
486
487
        return view('vendor.laravel-mobilpay.cardReturn')->with([
0 ignored issues
show
Bug introduced by
The method with does only exist in Illuminate\Contracts\View\View, but not in Illuminate\Contracts\View\Factory.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
488
            'orderId' => $orderId,
489
            'orderStatus' => $orderStatus
490
        ]);
491
    }
492
}
493