Completed
Push — master ( 75e64a...76886e )
by Chris
01:32
created

EDU_SveaWebPay::create_checkout()   F

Complexity

Conditions 16
Paths 6144

Size

Total Lines 169

Duplication

Lines 6
Ratio 3.55 %

Importance

Changes 0
Metric Value
cc 16
nc 6144
nop 1
dl 6
loc 169
rs 1.1198
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
defined( 'ABSPATH' ) or die( 'This plugin must be run within the scope of WordPress.' );
3
4
require_once( __DIR__ . '/class-edu-sveawebpay-config.php' );
5
6
use Svea\WebPay\WebPay;
7
use Svea\WebPay\WebPayItem;
8
use Svea\WebPay\Config\ConfigurationService;
9
use Svea\WebPay\Response\SveaResponse;
10
11
if ( ! class_exists( 'EDU_SveaWebPay' ) ):
12
13
	/**
14
	 * EDU_SveaWebPay integrates EduAdmin-WordPress plugin with SveaWebPay as payment gateway
15
	 */
16
	class EDU_SveaWebPay extends EDU_Integration {
17
		/**
18
		 * Constructor
19
		 */
20
		public function __construct() {
21
			$this->id          = 'eduadmin-sveawebpay';
22
			$this->displayName = __( 'Svea Webpay (Checkout)', 'eduadmin-sveawebpay' );
23
			$this->description = '';
24
25
			$this->init_form_fields();
26
			$this->init_settings();
27
28
			add_action( 'eduadmin-checkpaymentplugins', array( $this, 'intercept_booking' ) );
29
			add_action( 'eduadmin-processbooking', array( $this, 'process_booking' ) );
30
			add_action( 'eduadmin-bookingcompleted', array( $this, 'process_svearesponse' ) );
31
			add_action( 'wp_loaded', array( $this, 'process_paymentstatus' ) );
32
33
			add_shortcode( 'eduadmin-svea-testpage', array( $this, 'test_page' ) );
34
		}
35
36
		/**
37
		 * @param $attributes
38
		 */
39
		public function test_page( $attributes ) {
40
			$attributes = shortcode_atts(
41
				array(
42
					'bookingid'          => 0,
43
					'programmebookingid' => 0,
44
				),
45
				normalize_empty_atts( $attributes ),
46
				'test_page'
47
			);
48
49
			if ( $attributes['bookingid'] > 0 ) {
50
				$event_booking = EDUAPI()->OData->Bookings->GetItem(
51
					$attributes['bookingid'],
52
					null,
53
					'Customer($select=CustomerId;),ContactPerson($select=PersonId;),OrderRows',
54
					false
55
				);
56
			} elseif ( $attributes['programmebookingid'] > 0 ) {
57
				$event_booking = EDUAPI()->OData->ProgrammeBookings->GetItem(
58
					$attributes['programmebookingid'],
59
					null,
60
					'Customer($select=CustomerId;),ContactPerson($select=PersonId;),OrderRows',
61
					false
62
				);
63
			}
64
65
			$_customer = EDUAPI()->OData->Customers->GetItem(
66
				$event_booking['Customer']['CustomerId'],
0 ignored issues
show
Bug introduced by
The variable $event_booking 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...
67
				null,
68
				"BillingInfo",
69
				false
70
			);
71
72
			$_contact = EDUAPI()->OData->Persons->GetItem(
73
				$event_booking['ContactPerson']['PersonId'],
74
				null,
75
				null,
76
				false
77
			);
78
79
			$ebi = new EduAdmin_BookingInfo( $event_booking, $_customer, $_contact );
80
81
			if ( ! empty( EDU()->session['svea-order-id'] ) && ! empty( $_GET['svea_order_id'] ) && EDU()->session['svea-order-id'] === $_GET['svea_order_id'] ) {
82
				do_action( 'eduadmin-bookingcompleted', $ebi );
83
			} else {
84
				do_action( 'eduadmin-processbooking', $ebi );
85
			}
86
		}
87
88
89
		/**
90
		 * @param EduAdmin_BookingInfo|null $ebi
91
		 */
92
		public function intercept_booking( $ebi = null ) {
93
			if ( 'no' === $this->get_option( 'enabled', 'no' ) ) {
94
				return;
95
			}
96
97
			if ( ! empty( $_POST['act'] ) && ( 'bookCourse' === $_POST['act'] || 'bookProgramme' === $_POST['act'] ) ) {
98
				$ebi->NoRedirect = true;
99
			}
100
		}
101
102
		/**
103
		 * Initializes the settingsfields
104
		 */
105
		public function init_form_fields() {
106
			$this->setting_fields = array(
107
				'enabled'         => array(
108
					'title'       => __( 'Enabled', 'eduadmin-sveawebpay' ),
109
					'type'        => 'checkbox',
110
					'description' => __( 'Enables/Disables the integration with Svea WebPay', 'eduadmin-sveawebpay' ),
111
					'default'     => 'no',
112
				),
113
				'testrun'         => array(
114
					'title'       => __( 'Sandbox mode', 'eduadmin-sveawebpay' ),
115
					'type'        => 'checkbox',
116
					'description' => __( 'Activate sandbox mode', 'eduadmin-sveawebpay' ),
117
					'default'     => 'no',
118
				),
119
				'merchant_key'    => array(
120
					'title'       => __( 'Merchant key', 'eduadmin-sveawebpay' ),
121
					'type'        => 'text',
122
					'description' => __( 'Please enter your merchant key from Svea WebPay.', 'eduadmin-sveawebpay' ),
123
					'placeholder' => __( 'Merchant key', 'eduadmin-sveawebpay' ),
124
				),
125
				'merchant_secret' => array(
126
					'title'       => __( 'Merchant secret', 'eduadmin-sveawebpay' ),
127
					'type'        => 'password',
128
					'description' => __( 'Please enter your merchant secret from Svea WebPay', 'eduadmin-sveawebpay' ),
129
					'placeholder' => __( 'Merchant secret', 'eduadmin-sveawebpay' ),
130
				),
131
			);
132
		}
133
134
		/**
135
		 *
136
		 */
137
		public function process_svearesponse() {
138
			if ( 'no' === $this->get_option( 'enabled', 'no' ) ) {
139
				return;
140
			}
141
142
			if ( isset( $_REQUEST['edu-thankyou'] ) && isset( $_REQUEST['svea'] ) ) {
143
				$booking_id           = intval( $_GET['booking_id'] );
144
				$programme_booking_id = intval( $_GET['programme_booking_id'] );
145
146
				$this->update_booking( intval( $_GET['edu-thankyou'] ), $booking_id, $programme_booking_id );
147
148
				EDU()->session['svea-order-id'] = null;
149
			}
150
		}
151
152
		/**
153
		 * @param $ebi EduAdmin_BookingInfo|null $bookingInfo
154
		 */
155
		public function process_booking( $ebi = null ) {
156
			if ( 'no' === $this->get_option( 'enabled', 'no' ) ) {
157
				return;
158
			}
159
160
			$ebi->NoRedirect = true;
161
162
			if ( empty( $_GET['svea_order_id'] ) || empty( EDU()->session['svea-order-id'] ) ) {
163
				$checkout = $this->create_checkout( $ebi );
164
165
				$snippet = $checkout['Gui']['Snippet'];
166
				echo "<div>{$snippet}</div>";
167
			}
168
		}
169
170
		/**
171
		 * @param $ebi EduAdmin_BookingInfo|null
172
		 *
173
		 * @returns array
174
		 */
175
		public function create_checkout( $ebi ) {
176
			$countries = EDUAPI()->OData->Countries->Search()['value'];
177
178
			$selectedCountry = 'SE';
179
			$selectedLocale  = 'sv-SE';
180
181
			$invoiceCountry = $ebi->Customer['BillingInfo']['Country'];
182
			if ( empty( $invoiceCountry ) ) {
183
				$invoiceCountry = $ebi->Customer['Country'];
184
			}
185
186
			foreach ( $countries as $country ) {
187
				if ( $invoiceCountry == $country['CountryName'] ) {
188
					$selectedCountry = $country['CountryCode'];
189
					if ( ! empty( $country['CultureName'] ) ) {
190
						$selectedLocale = $country['CultureName'];
191
					}
192
					break;
193
				}
194
			}
195
196
			$booking_id           = 0;
197
			$programme_booking_id = 0;
198
199
			$reference_id = 0;
200
201
			$_event = null;
0 ignored issues
show
Unused Code introduced by
$_event 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...
202
203
			$eventName = '';
204
205
			$locationAddress    = '';
0 ignored issues
show
Unused Code introduced by
$locationAddress 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...
206
			$locationCountry    = '';
0 ignored issues
show
Unused Code introduced by
$locationCountry 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...
207
			$locationPostalCode = '';
0 ignored issues
show
Unused Code introduced by
$locationPostalCode 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...
208
209
			if ( ! empty( $ebi->EventBooking['BookingId'] ) ) {
210
				$booking_id   = intval( $ebi->EventBooking['BookingId'] );
211
				$reference_id = $booking_id;
212
213
				$_event = EDUAPI()->OData->Events->GetItem( $ebi->EventBooking['EventId'], null, "LocationAddress" );
214
215
				$eventName = $_event['EventName'];
216
217
				if ( ! empty( $_event['LocationAddress'] ) && $_event['LocationAdress'] != null ) {
218
					$locationAddress    = $_event['LocationAddress']['Address'];
0 ignored issues
show
Unused Code introduced by
$locationAddress 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...
219
					$locationCountry    = $_event['LocationAddress']['Country'];
0 ignored issues
show
Unused Code introduced by
$locationCountry 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...
220
					$locationPostalCode = $_event['LocationAddress']['AddressZip'];
0 ignored issues
show
Unused Code introduced by
$locationPostalCode 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...
221
				}
222
			}
223
224
			if ( ! empty( $ebi->EventBooking['ProgrammeBookingId'] ) ) {
225
				$programme_booking_id = intval( $ebi->EventBooking['ProgrammeBookingId'] );
226
				$reference_id         = $programme_booking_id;
227
228
				$_event = EDUAPI()->OData->ProgrammeStarts->GetItem( $ebi->EventBooking['ProgrammeStartId'] );
229
230
				$eventName = $_event['ProgrammeStartName'];
231
			}
232
233
			$currency = EDU()->get_option( 'eduadmin-currency', 'SEK' );
234
235 View Code Duplication
			if ( 'no' !== $this->get_option( 'testrun', 'no' ) ) {
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...
236
				$wpConfig = new EduSveaWebPayTestConfig( $this );
237
			} else {
238
				$wpConfig = new EduSveaWebPayProductionConfig( $this );
239
			}
240
241
			$wpOrder = WebPay::checkout( $wpConfig );
242
243
			$orderRow = WebPayItem::orderRow();
244
			$orderRow->setName( $eventName );
245
			$orderRow->setQuantity( 1 );
246
247
			$vatPercent = ( $ebi->EventBooking['VatSum'] / $ebi->EventBooking['TotalPriceExVat'] ) * 100;
248
			$orderRow->setVatPercent( $vatPercent );
249
			$orderRow->setAmountIncVat( (float) $ebi->EventBooking['TotalPriceIncVat'] );
250
251
			$customer = WebPayItem::companyCustomer();
252
253
			$customerName  = ! empty( $ebi->Customer['BillingInfo']['InvoiceName'] ) ? $ebi->Customer['BillingInfo']['InvoiceName'] : $ebi->Customer['CustomerName'];
254
			$streetAddress = ! empty( $ebi->Customer['BillingInfo']['Address'] ) ? $ebi->Customer['BillingInfo']['Address'] : $ebi->Customer['Address'];
255
			$zipCode       = ! empty( $ebi->Customer['BillingInfo']['Zip'] ) ? $ebi->Customer['BillingInfo']['Zip'] : $ebi->Customer['Zip'];
256
			$city          = $ebi->Customer['BillingInfo']['City'] ? $ebi->Customer['BillingInfo']['City'] : $ebi->Customer['City'];
257
			$phone         = $ebi->Customer['Phone'];
258
			$email         = ! empty( $ebi->Customer['BillingInfo']['Email'] ) ? $ebi->Customer['BillingInfo']['Email'] : $ebi->Customer['Email'];
259
260
			$customer->setCompanyName( $customerName );
261
			$customer->setStreetAddress( $streetAddress );
262
			$customer->setZipCode( $zipCode );
263
			$customer->setLocality( $city );
264
265
			if ( ! empty( $phone ) ) {
266
				$customer->setPhoneNumber( $phone );
267
				$phonePreset = WebPayItem::presetValue()
268
				                         ->setTypeName( \Svea\WebPay\Checkout\Model\PresetValue::PHONE_NUMBER )
269
				                         ->setValue( $phone )
270
				                         ->setIsReadonly( false );
271
				$wpOrder->addPresetValue( $phonePreset );
272
			}
273
			$customer->setEmail( $email );
274
275
			$zipPreset = WebPayItem::presetValue()
276
			                       ->setTypeName( \Svea\WebPay\Checkout\Model\PresetValue::POSTAL_CODE )
277
			                       ->setValue( $zipCode )
278
			                       ->setIsReadonly( false );
279
			$wpOrder->addPresetValue( $zipPreset );
280
281
			$emailPreset = WebPayItem::presetValue()
282
			                         ->setTypeName( \Svea\WebPay\Checkout\Model\PresetValue::EMAIL_ADDRESS )
283
			                         ->setValue( $email )
284
			                         ->setIsReadonly( false );
285
			$wpOrder->addPresetValue( $emailPreset );
286
287
			$current_url = esc_url( "{$_SERVER['REQUEST_SCHEME']}://{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}" );
288
289
			$defaultThankYou = add_query_arg(
290
				array(
291
					'edu-thankyou'         => $reference_id,
292
					'svea'                 => '1',
293
					'booking_id'           => $booking_id,
294
					'programme_booking_id' => $programme_booking_id,
295
					'edu-valid-form'       => wp_create_nonce( 'edu-booking-confirm' ),
296
					'svea_order_id'        => '{checkout.order.uri}',
297
					'act'                  => 'paymentCompleted',
298
				),
299
				@get_page_link( get_option( 'eduadmin-thankYouPage', '/' ) )
300
			);
301
302
			$defaultCancel = add_query_arg(
303
				array(
304
					'edu-thankyou'         => $reference_id,
305
					'svea'                 => '1',
306
					'booking_id'           => $booking_id,
307
					'programme_booking_id' => $programme_booking_id,
308
					'svea_order_id'        => '{checkout.order.uri}',
309
					'status'               => 'cancel'
310
				),
311
				$current_url
312
			);
313
314
			$defaultPushUrl = add_query_arg(
315
				array(
316
					'edu-thankyou'         => $reference_id,
317
					'svea'                 => '1',
318
					'booking_id'           => $booking_id,
319
					'programme_booking_id' => $programme_booking_id,
320
					'svea_order_id'        => '{checkout.order.uri}',
321
					'status'               => 'push'
322
				),
323
				$current_url
324
			);
325
326
			$defaultTermsUrl = get_option( 'eduadmin-bookingTermsLink' );
327
328
			$wpBuild = $wpOrder
329
				->setCurrency( $currency )
330
				->setCountryCode( $selectedCountry )
331
				->setClientOrderNumber( $reference_id )
332
				->addOrderRow( $orderRow )
333
				->setLocale( $selectedLocale )
334
				->setTermsUri( $defaultTermsUrl )
335
				->setConfirmationUri( $defaultThankYou )
336
				->setPushUri( $defaultPushUrl )
337
				->setCheckoutUri( $defaultCancel ); // We have no "checkout"-url.. So we just cancel the booking instead.
338
			$wpForm  = $wpBuild->createOrder();
339
340
			EDU()->session['svea-order-id'] = $wpForm['OrderId'];
341
342
			return $wpForm;
343
		}
344
345
		public function process_paymentstatus() {
346
			if ( ! empty( $_GET['svea_order_id'] ) && ! empty( $_GET['status'] ) ) {
347
348
				$booking_id           = intval( $_GET['booking_id'] );
349
				$programme_booking_id = intval( $_GET['programme_booking_id'] );
350
351
				$this->update_booking( intval( $_GET['edu-thankyou'] ), $booking_id, $programme_booking_id );
352
353
				exit( 0 );
354
			}
355
		}
356
357
		private function update_booking( $ecl_id, $booking_id, $programme_booking_id ) {
358 View Code Duplication
			if ( 'no' !== $this->get_option( 'testrun', 'no' ) ) {
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...
359
				$wpConfig = new EduSveaWebPayTestConfig( $this );
360
			} else {
361
				$wpConfig = new EduSveaWebPayProductionConfig( $this );
362
			}
363
364
			$wpOrder = WebPay::checkout( $wpConfig );
365
			$wpOrder->setCheckoutOrderId( $ecl_id );
366
367
			$order = $wpOrder->getOrder();
368
369
			$patch_booking                  = new stdClass();
370
			$patch_booking->PaymentMethodId = 2;
371
372
			if ( 'Cancelled' === $order['Status'] ) {
373
				$patch_booking->Paid = false;
374
			} else if ( 'Final' === $order['Status'] ) {
375
				$patch_booking->Paid = true;
376
			} else if ( 'Created' === $order['Status'] ) {
377
				$patch_booking->Paid = false;
378
			}
379
380
			if ( $booking_id > 0 ) {
381
				EDUAPI()->REST->Booking->PatchBooking(
382
					$booking_id,
383
					$patch_booking
384
				);
385
			}
386
387
			if ( $programme_booking_id > 0 ) {
388
				EDUAPI()->REST->ProgrammeBooking->PatchBooking(
389
					$programme_booking_id,
390
					$patch_booking
391
				);
392
			}
393
		}
394
	}
395
396
endif;
397