Completed
Push — develop ( fd7b2c...32742a )
by Stoea
01:56
created

LaravelMobilpayController::card()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
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 Stl30\LaravelMobilpay\CustomActionsAndNotifications;
11
use Stl30\LaravelMobilpay\Mobilpay\Payment\Request\Mobilpay_Payment_Request_Abstract;
12
use Stl30\LaravelMobilpay\Mobilpay\Payment\Request\Mobilpay_Payment_Request_Card;
13
use Stl30\LaravelMobilpay\Mobilpay\Payment\Invoice;
14
use Stl30\LaravelMobilpay\Mobilpay\Payment\Mobilpay_Payment_Address;
15
use Stl30\LaravelMobilpay\Mobilpay\Payment\Request\Mobilpay_Payment_Request_Notify;
16
use Stl30\LaravelMobilpay\Mobilpay\Payment\Mobilpay_Payment_Invoice;
17
use Stl30\LaravelMobilpay\MobilpayTransaction;
18
19
class LaravelMobilpayController extends Controller
20
{   /**
21
     * @var CustomActionsAndNotifications
22
     */
23
    public $actionsAndNotifications ;
24
25
    public function __construct()
26
    {
27
        $this -> actionsAndNotifications = new LaravelMobilpayCustomActionsAndNotifications();
28
    }
29
30
    public function card()
31
    {
32
        return view('vendor.laravel-mobilpay.card');
33
    }
34
35
    public function addTransaction(Mobilpay_Payment_Request_Card $mobilpayRequestObject,$customDataParameter='')
36
    {
37
        $this -> actionsAndNotifications ->setActions([
38
            'transaction' => 'start create',
39
            'time' => date('Y-m-d H:i:s')
40
        ]);
41
42
        $this -> actionsAndNotifications -> beforeCreatingTransaction($mobilpayRequestObject,$customDataParameter);
43
44
        $transaction = new MobilpayTransaction();
45
        $transaction->id_transaction = $mobilpayRequestObject->orderId;
46
        $transaction->request_status = 0;
47
        $transaction->status = 'initiated';
48
        $transaction->value = $mobilpayRequestObject->invoice->amount;
49
        $transaction->currency = $mobilpayRequestObject->invoice->currency;
50
        $transaction->details = $mobilpayRequestObject->invoice->details;
51
        $transaction->type = $mobilpayRequestObject->invoice->getBillingAddress()->type ?? null;
52
        $transaction->client_name = $mobilpayRequestObject->invoice->getBillingAddress()->first_name ?? null;
0 ignored issues
show
Bug introduced by
The property first_name does not seem to exist in Stl30\LaravelMobilpay\Mo...obilpay_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...
53
        $transaction->client_surname = $mobilpayRequestObject->invoice->getBillingAddress()->last_name ?? null;
0 ignored issues
show
Bug introduced by
The property last_name does not seem to exist in Stl30\LaravelMobilpay\Mo...obilpay_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...
54
        $transaction->client_email = $mobilpayRequestObject->invoice->getBillingAddress()->email ?? null;
55
        $transaction->client_address = $mobilpayRequestObject->invoice->getBillingAddress()->address ?? null;
56
        $transaction->client_phone = $mobilpayRequestObject->invoice->getBillingAddress()->mobilePhone ?? null;
57
        $transaction->request_object = json_encode($mobilpayRequestObject, true);
58
        $transaction->custom_data = $customDataParameter;
59
        $addTransactionIsSuccessful = $transaction->save();
60
61
        if($addTransactionIsSuccessful){
62
            $this -> actionsAndNotifications ->setNotifications([
63
                'request_status' => $transaction->request_status,
64
                'id_transaction_created' => $transaction->id,
65
            ]);
66
            $this -> actionsAndNotifications ->setActions([
67
                'transaction' => 'successfully created',
68
            ]);
69
        }
70
71
72
        $this -> actionsAndNotifications -> afterCreatingTransaction($transaction,$addTransactionIsSuccessful);
73
74
        return $addTransactionIsSuccessful;
75
    }
76
77
    public function updateTransaction(Mobilpay_Payment_Request_Abstract $mobilpayReturnObject, $orderStatus = 'possible error')
78
    {
79
        $this -> actionsAndNotifications ->setActions([
80
            'transaction' => 'start update',
81
            'time' => date('Y-m-d H:i:s')
82
        ]);
83
84
        $this -> actionsAndNotifications -> beforeUpdatingTransaction($mobilpayReturnObject, $orderStatus);
85
86
        $transaction = MobilpayTransaction::where('id_transaction', '=', $mobilpayReturnObject->orderId)->firstOrFail();
87
        $transaction->value = $mobilpayReturnObject->invoice->amount;
0 ignored issues
show
Documentation introduced by
The property invoice does not exist on object<Stl30\LaravelMobi...yment_Request_Abstract>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
88
        $transaction->currency = $mobilpayReturnObject->invoice->currency;
0 ignored issues
show
Documentation introduced by
The property invoice does not exist on object<Stl30\LaravelMobi...yment_Request_Abstract>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
89
        $transaction->details = $mobilpayReturnObject->invoice->details;
0 ignored issues
show
Documentation introduced by
The property invoice does not exist on object<Stl30\LaravelMobi...yment_Request_Abstract>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
90
        $transaction->request_status = 1;
91
        $transaction->status = $orderStatus;
92
        $transaction->client_name = $mobilpayReturnObject->objPmNotify->customer->firstName;
93
        $transaction->client_surname = $mobilpayReturnObject->objPmNotify->customer->lastName;
94
        $transaction->client_address = $mobilpayReturnObject->objPmNotify->customer->address;
95
        $transaction->client_email = $mobilpayReturnObject->objPmNotify->customer->email;
96
        $transaction->client_phone = $mobilpayReturnObject->objPmNotify->customer->mobilePhone;
97
        $transaction->return_request_object = json_encode($mobilpayReturnObject, true);
98
        $updatedIsSuccessful = $transaction->update();
99
100 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...
101
            $this -> actionsAndNotifications ->setNotifications([
102
                'status' => $transaction->status,
103
                'request_status' => $transaction->request_status,
104
                'id_transaction_created' => $transaction->id,
105
            ]);
106
            $this -> actionsAndNotifications ->setActions([
107
                'transaction' => 'successfully updated',
108
                'time' => date('Y-m-d H:i:s')
109
            ]);
110
        }
111
112
        $this -> actionsAndNotifications ->afterUpdatingTransaction($transaction, $updatedIsSuccessful);
113
114
        return $updatedIsSuccessful;
115
    }
116
117
    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...
118
    {
119
120
121
        $this -> actionsAndNotifications ->setActions([
122
            'error transaction' => 'start creating',
123
            'time' => date('Y-m-d H:i:s')
124
        ]);
125
126
        $transaction = new MobilpayTransaction();
127
        $transaction->id_transaction = 'error code:' . $errorCode . '>> error type:' . $errorType . '>> error message:' . $errorMessage;
128
        $transaction->request_status = $errorType;
129
        $transaction->request_object = json_encode($mobilpayReturnObject, true);
130
        $transaction->status = $errorMessage;
131
        $addTransactionIsSuccessful = $transaction->save();
132
133 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...
134
            $this -> actionsAndNotifications ->setNotifications([
135
                'status' => $transaction->status,
136
                'request_status' => $transaction->request_status,
137
            ]);
138
            $this -> actionsAndNotifications ->setActions([
139
                'error transaction' => 'successfully created',
140
                'time' => date('Y-m-d H:i:s')
141
            ]);
142
        }
143
144
        return $addTransactionIsSuccessful;
145
    }
146
147
    public static function validatePaymentDetails(array $parameters = [])
148
    {
149
        $errorsText = '';
150
        $paymentParameters = [];
151
        $requiredParameters = [
152
            #must haves values
153
            'payment_amount' => 'value of payment',
154
            'payment_details' => 'payment details placeholder',
155
            'order_id' => '',
156
            'billing_type' => 'person',//or company
157
        ];
158
        foreach ($requiredParameters as $requiredName => $value) {
159 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...
160
                $paymentParameters[$requiredName] = $parameters[$requiredName];
161
                continue;
162
            }
163
            $errorsText .= '<br>Missing required parameter ' . $requiredName;
164
        }
165
        if (strlen($errorsText)) {
166
            die($errorsText);
167
        }
168
169
        $optionalParameters = [
170
            #custom data / if you need some custom data save on the transactions table
171
            'custom_data' => '',
172
            #optional values
173
            'promotion_code' => '',
174
            'currency' => '',
175
            #details on the cardholder address (optional)
176
177
            'billing_first_name' => '',//client first name
178
            'billing_last_name' => '',//client last name
179
            'billing_address' => '',//client adress
180
            'billing_email' => '',//client email
181
            'billing_mobile_phone' => '',//client phone/mobile
182
            'billing_fiscal_number' => '',
183
            'billing_identity_number' => '',
184
            'billing_country' => '',
185
            'billing_county' => '',
186
            'billing_city' => '',
187
            'billing_zip_code' => '',
188
            'billing_bank' => '',
189
            'billing_iban' => '',
190
            #details on the shipping address
191
            'shipping_type' => 'person',//or company
192
            'shipping_first_name' => '',
193
            'shipping_last_name' => '',
194
            'shipping_address' => '',
195
            'shipping_email' => '',
196
            'shipping_mobile_phone' => '',
197
            'shipping_fiscal_number' => '',
198
            'shipping_identity_number' => '',
199
            'shipping_country' => '',
200
            'shipping_county' => '',
201
            'shipping_city' => '',
202
            'shipping_zip_code' => '',
203
            'shipping_bank' => '',
204
            'shipping_iban' => '',
205
        ];
206
207
208
        foreach ($optionalParameters as $key => $Value) {
209 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...
210
                $paymentParameters[$key] = $parameters[$key];
211
            }
212
        }
213
214
        return $paymentParameters;
215
    }
216
217
    public function cardRedirect(array $paymentParameters = array())
218
    {
219
        $paymentParameters = self::validatePaymentDetails($paymentParameters);
220
221
        #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
222
        #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
223
        if (config('laravel-mobilpay.sandbox_active')) {
224
            $paymentUrl = config('laravel-mobilpay.sandbox_payment_link');
225
        } else {
226
            $paymentUrl = config('laravel-mobilpay.production_payment_link');
227
        }
228
229
        //$paymentUrl = 'https://secure.mobilpay.ro';
230
        // this is the path on your server to the public certificate. You may download this from Admin -> Conturi de comerciant -> Detalii -> Setari securitate
231
//        $x509FilePath 	= 'i.e: /home/certificates/public.cer';
232
233
        if (config('laravel-mobilpay.sandbox_active')) {
234
            $x509FilePath = config('laravel-mobilpay.sandbox_public_key');
235
        } else {
236
            $x509FilePath = config('laravel-mobilpay.production_public_key');
237
        }
238
239
        try {
240
            srand((double)microtime() * 1000000);
241
            $objPmReqCard = new Mobilpay_Payment_Request_Card();
242
            #merchant account signature - generated by mobilpay.ro for every merchant account
243
            #semnatura contului de comerciant - mergi pe www.mobilpay.ro Admin -> Conturi de comerciant -> Detalii -> Setari securitate
244
            $objPmReqCard->signature = config('laravel-mobilpay.merchant_account_signature');
245
            #you should assign here the transaction ID registered by your application for this commercial operation
246
            #order_id should be unique for a merchant account
247
            $objPmReqCard->orderId = $paymentParameters['order_id'];
248
            #below is where mobilPay will send the payment result. This URL will always be called first; mandatory
249
            $objPmReqCard->confirmUrl = config('laravel-mobilpay.confirmUrl');
250
            #below is where mobilPay redirects the client once the payment process is finished. Not to be mistaken for a "successURL" nor "cancelURL"; mandatory
251
            $objPmReqCard->returnUrl = config('laravel-mobilpay.returnUrl');
252
253
            #detalii cu privire la plata: moneda, suma, descrierea
254
            #payment details: currency, amount, description
255
            $objPmReqCard->invoice = new Mobilpay_Payment_Invoice();
256
            #payment currency in ISO Code format; permitted values are RON, EUR, USD, MDL; please note that unless you have mobilPay permission to
257
            #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
258
            #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)
259
            $objPmReqCard->invoice->currency = $paymentParameters['currency'] ?? config('laravel-mobilpay.currency');
260
            $objPmReqCard->invoice->amount = $paymentParameters['payment_amount'];
261
            #available installments number; if this parameter is present, only its value(s) will be available
262
            //$objPmReqCard->invoice->installments= '2,3';
263
            #selected installments number; its value should be within the available installments defined above
264
            //$objPmReqCard->invoice->selectedInstallments= '3';
265
            //platile ulterioare vor contine in request si informatiile despre token. Prima plata nu va contine linia de mai jos.
266
//            $objPmReqCard->invoice->tokenId = 'token_id';
267
            $objPmReqCard->invoice->details = $paymentParameters['payment_details'];
268
269
            #detalii cu privire la adresa posesorului cardului
270
            #details on the cardholder address (optional)
271
            $billingAddress = new Mobilpay_Payment_Address();
272
            $billingAddress->type = $paymentParameters['billing_type']; //should be "person"
273
            $billingAddress->firstName = $paymentParameters['billing_first_name'] ?? null;
274
            $billingAddress->lastName = $paymentParameters['billing_last_name'] ?? null;
275
            $billingAddress->address = $paymentParameters['billing_address'] ?? null;
276
            $billingAddress->email = $paymentParameters['billing_email'] ?? null;
277
            $billingAddress->mobilePhone = $paymentParameters['billing_mobile_phone'] ?? null;
278
            $objPmReqCard->invoice->setBillingAddress($billingAddress);
279
280
            #detalii cu privire la adresa de livrare
281
            #details on the shipping address
282
            $shippingAddress = new Mobilpay_Payment_Address();
283
            $shippingAddress->type = $paymentParameters['shipping_type'] ?? null;
284
            $shippingAddress->firstName = $paymentParameters['shipping_first_name'] ?? null;
285
            $shippingAddress->lastName = $paymentParameters['shipping_last_name'] ?? null;
286
            $shippingAddress->address = $paymentParameters['shipping_address'] ?? null;
287
            $shippingAddress->email = $paymentParameters['shipping_email'] ?? null;
288
            $shippingAddress->mobilePhone = $paymentParameters['shipping_mobile_phone'] ?? null;
289
            $objPmReqCard->invoice->setShippingAddress($shippingAddress);
290
291
            #uncomment the line below in order to see the content of the request
292
            // TODO for debug
293
//            dd(__METHOD__,$objPmReqCard,$objPmReqCard->signature,$objPmReqCard->orderId,get_class($objPmReqCard->invoice));
294
//            echo "<pre>";print_r($objPmReqCard);echo "</pre>";
295
            $objPmReqCard->encrypt($x509FilePath);
296
            $customDataForTransaction = $paymentParameters['custom_data'] ?? '';
297
            $this->addTransaction($objPmReqCard,$customDataForTransaction);
298
        } catch (\Exception $e) {
299
            $exception = isset($e) ? $e : null;
300
        }
301
        $exception = isset($exception) ? $exception : null;
302
        //
303
        return view('vendor.laravel-mobilpay.cardRedirect')->with([
0 ignored issues
show
Bug introduced by
The method with does only exist in Illuminate\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...
304
            'objPmReqCard' => $objPmReqCard,
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...
305
            'e' => $exception,
306
            'paymentUrl' => $paymentUrl
307
        ]);
308
    }
309
310
    public function cardConfirm()
311
    {
312
313
        $errorCode = 0;
314
        $errorType = Mobilpay_Payment_Request_Abstract::CONFIRM_ERROR_TYPE_NONE;
315
        $errorMessage = '';
0 ignored issues
show
Unused Code introduced by
$errorMessage 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...
316
        $orderStatus = '';
0 ignored issues
show
Unused Code introduced by
$orderStatus 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...
317
        if (strcasecmp($_SERVER['REQUEST_METHOD'], 'post') == 0) {
318
            if (isset($_POST['env_key']) && isset($_POST['data'])) {
319
                #calea catre cheia privata
320
                #cheia privata este generata de mobilpay, accesibil in Admin -> Conturi de comerciant -> Detalii -> Setari securitate
321
                $privateKeyFilePath = config('laravel-mobilpay.sandbox_private_key');
322
323
                try {
324
                    $objPmReq = Mobilpay_Payment_Request_Abstract::factoryFromEncrypted($_POST['env_key'], $_POST['data'], $privateKeyFilePath);
325
                    #uncomment the line below in order to see the content of the request
326
                    //print_r($objPmReq);
327
                    $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...
328
                    // action = status only if the associated error code is zero
329
                    if ($objPmReq->objPmNotify->errorCode == 0) {
330
                        switch ($objPmReq->objPmNotify->action) {
331
                            #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;
332
                            #pentru a identifica ID-ul comenzii pentru care primim rezultatul platii folosim $id_comanda = $objPmReq->orderId;
333
                            case 'confirmed':
334
                                #cand action este confirmed avem certitudinea ca banii au plecat din contul posesorului de card si facem update al starii comenzii si livrarea produsului
335
                                //update DB, SET status = "confirmed/captured"
336
                                $orderStatus = 'confirmed/captured';
337
                                $errorMessage = $objPmReq->objPmNotify->errorMessage;
338
                                break;
339
                            case 'confirmed_pending':
340
                                #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.
341
                                //update DB, SET status = "pending"
342
                                $orderStatus = 'pending';
343
                                $errorMessage = $objPmReq->objPmNotify->errorMessage;
344
                                break;
345
                            case 'paid_pending':
346
                                #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.
347
                                //update DB, SET status = "pending"
348
                                $orderStatus = 'pending';
349
                                $errorMessage = $objPmReq->objPmNotify->errorMessage;
350
                                break;
351
                            case 'paid':
352
                                #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.
353
                                //update DB, SET status = "open/preauthorized"
354
                                $orderStatus = 'open/preauthorized';
355
                                $errorMessage = $objPmReq->objPmNotify->errorMessage;
356
                                break;
357
                            case 'canceled':
358
                                #cand action este canceled inseamna ca tranzactia este anulata. Nu facem livrare/expediere.
359
                                //update DB, SET status = "canceled"
360
                                $orderStatus = 'canceled';
361
                                $errorMessage = $objPmReq->objPmNotify->errorMessage;
362
                                break;
363
                            case 'credit':
364
                                #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.
365
                                //update DB, SET status = "refunded"
366
                                $orderStatus = 'refunded';
367
                                $errorMessage = $objPmReq->objPmNotify->errorMessage;
368
                                break;
369
                            default:
370
                                $errorType = Mobilpay_Payment_Request_Abstract::CONFIRM_ERROR_TYPE_PERMANENT;
371
                                $errorCode = Mobilpay_Payment_Request_Abstract::ERROR_CONFIRM_INVALID_ACTION;
372
                                $orderStatus = $errorMessage = 'mobilpay_refference_action paramaters is invalid';
373
                                break;
374
                        }
375
                    } else {
376
                        //update DB, SET status = "rejected"
377
                        $orderStatus = 'rejected';
378
                        $errorMessage = $objPmReq->objPmNotify->errorMessage;
379
                    }
380
                } catch (Exception $e) {
381
                    $errorType = Mobilpay_Payment_Request_Abstract::CONFIRM_ERROR_TYPE_TEMPORARY;
382
                    $errorCode = $e->getCode();
383
                    $orderStatus = $errorMessage = $e->getMessage();
384
                }
385
            } else {
386
                $errorType = Mobilpay_Payment_Request_Abstract::CONFIRM_ERROR_TYPE_PERMANENT;
387
                $errorCode = Mobilpay_Payment_Request_Abstract::ERROR_CONFIRM_INVALID_POST_PARAMETERS;
388
                $orderStatus = $errorMessage = 'mobilpay.ro posted invalid parameters';
389
            }
390
        } else {
391
            $errorType = Mobilpay_Payment_Request_Abstract::CONFIRM_ERROR_TYPE_PERMANENT;
392
            $errorCode = Mobilpay_Payment_Request_Abstract::ERROR_CONFIRM_INVALID_POST_METHOD;
393
            $orderStatus = $errorMessage = 'invalid request metod for payment confirmation';
394
        }
395
396
        header('Content-type: application/xml');
397
        echo "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n";
398
        if ($errorCode == 0) {
399
            $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...
400
            if ($updateTransaction !== true) {
401
//                Log::debug('Could not update transaction <<>> ' . json_encode($objPmReq, true) . ' <<<>>> with orderStatus:' . $orderStatus);
402
            } else {
403
//                Log::debug('Update transaction success <<>> ' . json_encode($objPmReq, true) . ' <<<>>> with orderStatus:' . $orderStatus);
404
            }
405
//            Log::debug('No errors');
406
//            Log::debug(json_encode($errorMessage, true));
407
            echo "<crc>{$errorMessage}</crc>";
408
        } else {
409
            $objPmReq = (isset($objPmReq) && is_object($objPmReq)) ? $objPmReq : '';
410
            if ($this->addAutomatedTransactionError($errorCode, $errorType, $errorMessage, $objPmReq) !== true) {
411
                Log::debug('Could not addAutomatedTransactionError <<>> errortype:' . $errorType . '<<<>>> error code:' . $errorCode . '<<<<>>>' . json_encode($errorMessage,true));
412
            } else {
413
//                Log::debug('addedAutomatedTransactionError <<>> errortype:' . $errorType . '<<<>>> error code:' . $errorCode . '<<<<>>>' . json_encode($errorMessage, true));
414
            }
415
//            Log::debug('With errors');
416
//            Log::debug('errortype:' . $errorType . '<<<>>> error code:' . $errorCode . '<<<<>>>' . json_encode($errorMessage, true));
417
            echo "<crc error_type=\"{$errorType}\" error_code=\"{$errorCode}\">{$errorMessage}</crc>";
418
        }
419
    }
420
421
    public function cardReturn(Request $request)
422
    {
423
        $orderStatus = 'eroare';
424
        $orderId = (isset($request->orderId) && $request->orderId !== null) ? $request->orderId : '';
425
        $order = MobilpayTransaction::where('id_transaction', '=', $request->orderId)->first();
426
        if ($order !== null) {
427
            switch ($order->status) {
428
                case 'confirmed/captured':
429
                    $orderStatus = 'succes';
430
                    break;
431
                case 'rejected':
432
                    $orderStatus = 'rejected';
433
                    break;
434
                case 'pending':
435
                    $orderStatus = 'pending';
436
                    break;
437
                default:
438
                    $orderStatus = 'error';
439
                    break;
440
            }
441
        }
442
443
        return view('vendor.laravel-mobilpay.cardReturn')->with([
0 ignored issues
show
Bug introduced by
The method with does only exist in Illuminate\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...
444
            'orderId' => $orderId,
445
            'orderStatus' => $orderStatus
446
        ]);
447
    }
448
}
449