Completed
Push — master ( 2cfcca...1b95e2 )
by Chris
03:25
created

EDU_SveaWebPay::process_booking()   F

Complexity

Conditions 15
Paths 1537

Size

Total Lines 110
Code Lines 74

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 15
eloc 74
nc 1537
nop 1
dl 0
loc 110
rs 2
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
use Svea\WebPay\WebPay;
5
use Svea\WebPay\WebPayItem;
6
use Svea\WebPay\Config\ConfigurationService;
7
use Svea\WebPay\Response\SveaResponse;
8
9
if ( ! class_exists( 'EDU_SveaWebPay' ) ):
10
11
	/**
12
	 * EDU_SveaWebPay integrates EduAdmin-WordPress plugin with SveaWebPay as payment gateway
13
	 */
14
	class EDU_SveaWebPay extends EDU_Integration {
15
		/**
16
		 * Constructor
17
		 */
18
		public function __construct() {
19
			$this->id          = 'eduadmin-sveawebpay';
20
			$this->displayName = __( 'Svea Webpay', 'eduadmin-sveawebpay' );
21
			$this->description = '';
22
23
			$this->init_form_fields();
24
			$this->init_settings();
25
26
			add_action( 'eduadmin-processbooking', array( $this, 'process_booking' ) );
27
28
			add_action( 'wp_loaded', array( $this, 'process_svearesponse' ) );
29
		}
30
31
		/**
32
		 * Initializes the settingsfields
33
		 */
34
		public function init_form_fields() {
35
			$this->setting_fields = array(
36
				'enabled'         => array(
37
					'title'       => __( 'Enabled', 'eduadmin-sveawebpay' ),
38
					'type'        => 'checkbox',
39
					'description' => __( 'Enables/Disables the integration with Svea WebPay', 'eduadmin-sveawebpay' ),
40
					'default'     => 'no',
41
				),
42
				'testrun'         => array(
43
					'title'       => __( 'Sandbox mode', 'eduadmin-sveawebpay' ),
44
					'type'        => 'checkbox',
45
					'description' => __( 'Activate sandbox mode', 'eduadmin-sveawebpay' ),
46
					'default'     => 'no',
47
				),
48
				'merchant_key'    => array(
49
					'title'       => __( 'Merchant key', 'eduadmin-sveawebpay' ),
50
					'type'        => 'text',
51
					'description' => __( 'Please enter your merchant key from Svea WebPay.', 'eduadmin-sveawebpay' ),
52
					'placeholder' => __( 'Merchant key', 'eduadmin-sveawebpay' ),
53
				),
54
				'merchant_secret' => array(
55
					'title'       => __( 'Merchant secret', 'eduadmin-sveawebpay' ),
56
					'type'        => 'password',
57
					'description' => __( 'Please enter your merchant secret from Svea WebPay', 'eduadmin-sveawebpay' ),
58
					'placeholder' => __( 'Merchant secret', 'eduadmin-sveawebpay' ),
59
				),
60
			);
61
		}
62
63
		/**
64
		 *
65
		 */
66
		public function process_svearesponse() {
67
			if ( isset( $_REQUEST['edu-thankyou'] ) && isset( $_REQUEST['svea'] ) && isset( $_REQUEST['response'] ) ) {
68
				$filter = new XFiltering();
69
				$f      = new XFilter( 'EventCustomerLnkID', '=', $_REQUEST['edu-thankyou'] );
0 ignored issues
show
introduced by
Detected access of super global var $_REQUEST, probably need manual inspection.
Loading history...
introduced by
Detected usage of a non-sanitized input variable: $_REQUEST
Loading history...
70
				$filter->AddItem( $f );
71
72
				$eventBooking = EDU()->api->GetEventBookingV2( EDU()->get_token(), '', $filter->ToString() )[0];
73
74
				$filter = new XFiltering();
75
				$f      = new XFilter( 'CustomerID', '=', $eventBooking->CustomerID );
76
				$filter->AddItem( $f );
77
78
				$_customer = EDU()->api->GetCustomerV3( EDU()->get_token(), '', $filter->ToString(), false )[0];
79
80
				$filter = new XFiltering();
81
				$f      = new XFilter( 'CustomerContactID', '=', $eventBooking->CustomerContactID );
82
				$filter->AddItem( $f );
83
84
				$_contact = EDU()->api->GetCustomerContactV2( EDU()->get_token(), '', $filter->ToString(), false )[0];
85
86
				$ebi = new EduAdminBookingInfo( $eventBooking, $_customer, $_contact );
87
88
				$countries = EDU()->api->GetCountries( EDU()->get_token(), 'Swedish' );
89
90
				$selectedCountry = 'SE';
91
92
				$invoiceCountry = $ebi->Customer->InvoiceCountry;
93
				if ( empty( $invoiceCountry ) ) {
94
					$invoiceCountry = $ebi->Customer->Country;
95
				}
96
97
				foreach ( $countries as $country ) {
98
					if ( $invoiceCountry == $country->CountryName ) {
99
						$selectedCountry = $country->CountryCode;
100
						break;
101
					}
102
				}
103
104
				$wpConfig = ConfigurationService::getDefaultConfig();
105
106
				$response = ( new SveaResponse( $_REQUEST, $selectedCountry, $wpConfig ) )->getResponse();
0 ignored issues
show
introduced by
Detected access of super global var $_REQUEST, probably need manual inspection.
Loading history...
107
108
				if ( $response->accepted ) {
109
					EDU()->api->SetValidPayment( EDU()->get_token(), $ebi->EventBooking->EventCustomerLnkID );
110
				} else {
111
					EDU()->api->SetInvalidPayment( EDU()->get_token(), $ebi->EventBooking->EventCustomerLnkID );
112
				}
113
114
				$surl    = get_home_url();
115
				$cat     = get_option( 'eduadmin-rewriteBaseUrl' );
116
				$baseUrl = $surl . '/' . $cat;
117
118
				wp_redirect( $baseUrl . '/profile/myprofile?payment=' . ( $response->accepted ? '1' : '0' ) );
119
				exit();
120
			}
121
		}
122
123
		/**
124
		 * @param $bookingInfo EduAdminBookingInfo
125
		 */
126
		public function process_booking( $bookingInfo = null ) {
127
			if ( isset( $_POST['act'] ) && 'bookCourse' === $_POST['act'] ) {
128
				$bookingInfo->NoRedirect = true;
129
130
				$countries = EDU()->api->GetCountries( EDU()->get_token(), 'Swedish' );
131
132
				$selectedCountry = 'SE';
133
				$selectedLocale  = 'sv-SE';
134
135
				$invoiceCountry = $bookingInfo->Customer->InvoiceCountry;
136
				if ( empty( $invoiceCountry ) ) {
137
					$invoiceCountry = $bookingInfo->Customer->Country;
138
				}
139
140
				foreach ( $countries as $country ) {
141
					if ( $invoiceCountry == $country->CountryName ) {
142
						$selectedCountry = $country->CountryCode;
143
						if ( ! empty( $country->CultureName ) ) {
144
							$selectedLocale = $country->CultureName;
145
						}
146
						break;
147
					}
148
				}
149
150
				$selectedLocale = explode( '-', $selectedLocale )[0];
151
152
				$currency = get_option( 'eduadmin-currency', 'SEK' );
153
154
				$wpConfig = ConfigurationService::getDefaultConfig();
155
				$wpOrder  = WebPay::createOrder( $wpConfig );
156
157
				$orderRow = WebPayItem::orderRow();
158
				$orderRow->setName( $bookingInfo->EventBooking->EventDescription );
159
				$orderRow->setQuantity( 1 );
160
161
				$vatPercent = ( $bookingInfo->EventBooking->VatSum / $bookingInfo->EventBooking->TotalPriceExVat ) * 100;
162
				$orderRow->setVatPercent( $vatPercent );
163
				$orderRow->setAmountIncVat( (float) $bookingInfo->EventBooking->TotalPriceIncVat );
164
165
				$customer = WebPayItem::companyCustomer();
166
167
				if ( ! empty( $bookingInfo->Customer->InvoiceName ) ) {
168
					$customer->setCompanyName( $bookingInfo->Customer->InvoiceName );
169
				} else {
170
					$customer->setCompanyName( $bookingInfo->Customer->CustomerName );
171
				}
172
173
				if ( ! empty( $bookingInfo->Customer->InvoiceAddress1 ) ) {
174
					$customer->setStreetAddress( $bookingInfo->Customer->InvoiceAddress1 );
175
				} else {
176
					$customer->setStreetAddress( $bookingInfo->Customer->Address1 );
177
				}
178
179
				if ( ! empty( $bookingInfo->Customer->InvoiceZip ) ) {
180
					$customer->setZipCode( $bookingInfo->Customer->InvoiceZip );
181
				} else {
182
					$customer->setZipCode( $bookingInfo->Customer->Zip );
183
				}
184
185
				if ( ! empty( $bookingInfo->Customer->InvoiceCity ) ) {
186
					$customer->setLocality( $bookingInfo->Customer->InvoiceCity );
187
				} else {
188
					$customer->setLocality( $bookingInfo->Customer->City );
189
				}
190
191
				if ( ! empty( $bookingInfo->Customer->Phone ) ) {
192
					$customer->setPhoneNumber( $bookingInfo->Customer->Phone );
193
				}
194
195
				if ( ! empty( $bookingInfo->Customer->InvoiceEmail ) ) {
196
					$customer->setEmail( $bookingInfo->Customer->InvoiceEmail );
197
				} else {
198
					$customer->setEmail( $bookingInfo->Customer->Email );
199
				}
200
201
				$customer->setIpAddress( EDU()->get_ip_adress() );
202
203
				$surl    = get_home_url();
204
				$cat     = get_option( 'eduadmin-rewriteBaseUrl' );
205
				$baseUrl = $surl . '/' . $cat;
206
207
				$defaultThankYou = @get_page_link( get_option( 'eduadmin-thankYouPage', '/' ) ) . "?edu-thankyou=" . $bookingInfo->EventBooking->EventCustomerLnkID . '&svea=1';
0 ignored issues
show
Coding Style introduced by
Silencing errors is discouraged
Loading history...
Coding Style Comprehensibility introduced by
The string literal ?edu-thankyou= does not require double quotes, as per coding-style, please use single quotes.

PHP provides two ways to mark string literals. Either with single quotes 'literal' or with double quotes "literal". The difference between these is that string literals in double quotes may contain variables with are evaluated at run-time as well as escape sequences.

String literals in single quotes on the other hand are evaluated very literally and the only two characters that needs escaping in the literal are the single quote itself (\') and the backslash (\\). Every other character is displayed as is.

Double quoted string literals may contain other variables or more complex escape sequences.

<?php

$singleQuoted = 'Value';
$doubleQuoted = "\tSingle is $singleQuoted";

print $doubleQuoted;

will print an indented: Single is Value

If your string literal does not contain variables or escape sequences, it should be defined using single quotes to make that fact clear.

For more information on PHP string literals and available escape sequences see the PHP core documentation.

Loading history...
208
				$defaultCancel   = $baseUrl . "?edu-cancel=" . $bookingInfo->EventBooking->EventCustomerLnkID . '&svea=1';
0 ignored issues
show
Coding Style Comprehensibility introduced by
The string literal ?edu-cancel= does not require double quotes, as per coding-style, please use single quotes.

PHP provides two ways to mark string literals. Either with single quotes 'literal' or with double quotes "literal". The difference between these is that string literals in double quotes may contain variables with are evaluated at run-time as well as escape sequences.

String literals in single quotes on the other hand are evaluated very literally and the only two characters that needs escaping in the literal are the single quote itself (\') and the backslash (\\). Every other character is displayed as is.

Double quoted string literals may contain other variables or more complex escape sequences.

<?php

$singleQuoted = 'Value';
$doubleQuoted = "\tSingle is $singleQuoted";

print $doubleQuoted;

will print an indented: Single is Value

If your string literal does not contain variables or escape sequences, it should be defined using single quotes to make that fact clear.

For more information on PHP string literals and available escape sequences see the PHP core documentation.

Loading history...
209
210
				$wpForm = $wpOrder
211
					->setCurrency( $currency )
212
					->setCountryCode( $selectedCountry )
213
					->setOrderDate( date( 'c' ) )
214
					->setClientOrderNumber( $bookingInfo->EventBooking->EventCustomerLnkID )
215
					->addOrderRow( $orderRow )
216
					->addCustomerDetails( $customer )
217
					->usePayPage()
218
					->setPayPageLanguage( $selectedLocale )
219
					->setReturnUrl( apply_filters( 'eduadmin-thankyou-url', $defaultThankYou ) )
220
					->setCancelUrl( apply_filters( 'eduadmin-cancel-url', $defaultCancel ) )
221
					->getPaymentUrl();
222
223
				if ( $wpForm->accepted ) {
224
					if ( 'no' === $this->get_option( 'testrun', 'no' ) ) {
225
						echo '<script type="text/javascript">location.href = "' . $wpForm->url . '";</script>';
0 ignored issues
show
introduced by
Expected next thing to be a escaping function, not '$wpForm'
Loading history...
226
					} else {
227
						echo '<script type="text/javascript">location.href = "' . $wpForm->testurl . '";</script>';
0 ignored issues
show
introduced by
Expected next thing to be a escaping function, not '$wpForm'
Loading history...
228
					}
229
				} else {
230
					add_filter( 'edu-booking-error', function( $errors ) use ( &$wpForm ) {
231
						$errors[] = $wpForm->errormessage;
232
					} );
233
				}
234
			}
235
		}
236
	}
237
238
endif;