Completed
Push — master ( 0aeb50...c7919b )
by Chris
02:47
created

EDU_SveaWebPay::process_svearesponse()   C

Complexity

Conditions 10
Paths 14

Size

Total Lines 59
Code Lines 37

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 10
eloc 37
nc 14
nop 0
dl 0
loc 59
rs 6.5919
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 ( 'no' === $this->get_option( 'enabled', 'no' ) ) {
68
				return;
69
			}
70
			if ( isset( $_REQUEST['edu-thankyou'] ) && isset( $_REQUEST['svea'] ) && isset( $_REQUEST['response'] ) ) {
71
				$filter = new XFiltering();
72
				$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...
73
				$filter->AddItem( $f );
74
75
				$eventBooking = EDU()->api->GetEventBookingV2( EDU()->get_token(), '', $filter->ToString() )[0];
76
77
				$filter = new XFiltering();
78
				$f      = new XFilter( 'CustomerID', '=', $eventBooking->CustomerID );
79
				$filter->AddItem( $f );
80
81
				$_customer = EDU()->api->GetCustomerV3( EDU()->get_token(), '', $filter->ToString(), false )[0];
82
83
				$filter = new XFiltering();
84
				$f      = new XFilter( 'CustomerContactID', '=', $eventBooking->CustomerContactID );
85
				$filter->AddItem( $f );
86
87
				$_contact = EDU()->api->GetCustomerContactV2( EDU()->get_token(), '', $filter->ToString(), false )[0];
88
89
				$ebi = new EduAdminBookingInfo( $eventBooking, $_customer, $_contact );
90
91
				$countries = EDU()->api->GetCountries( EDU()->get_token(), 'Swedish' );
92
93
				$selectedCountry = 'SE';
94
95
				$invoiceCountry = $ebi->Customer->InvoiceCountry;
96
				if ( empty( $invoiceCountry ) ) {
97
					$invoiceCountry = $ebi->Customer->Country;
98
				}
99
100
				foreach ( $countries as $country ) {
101
					if ( $invoiceCountry == $country->CountryName ) {
102
						$selectedCountry = $country->CountryCode;
103
						break;
104
					}
105
				}
106
107
				$wpConfig = ConfigurationService::getDefaultConfig();
108
109
				$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...
110
111
				if ( $response->accepted ) {
112
					EDU()->api->SetValidPayment( EDU()->get_token(), $ebi->EventBooking->EventCustomerLnkID );
113
				} else {
114
					EDU()->api->SetInvalidPayment( EDU()->get_token(), $ebi->EventBooking->EventCustomerLnkID );
115
				}
116
117
				$surl    = get_home_url();
118
				$cat     = get_option( 'eduadmin-rewriteBaseUrl' );
119
				$baseUrl = $surl . '/' . $cat;
120
121
				wp_redirect( $baseUrl . '/profile/myprofile?payment=' . ( $response->accepted ? '1' : '0' ) );
122
				exit();
123
			}
124
		}
125
126
		/**
127
		 * @param $bookingInfo EduAdminBookingInfo
128
		 */
129
		public function process_booking( $bookingInfo = null ) {
130
			if ( 'no' === $this->get_option( 'enabled', 'no' ) ) {
131
				return;
132
			}
133
			if ( isset( $_POST['act'] ) && 'bookCourse' === $_POST['act'] ) {
134
				$bookingInfo->NoRedirect = true;
135
136
				$countries = EDU()->api->GetCountries( EDU()->get_token(), 'Swedish' );
137
138
				$selectedCountry = 'SE';
139
				$selectedLocale  = 'sv-SE';
140
141
				$invoiceCountry = $bookingInfo->Customer->InvoiceCountry;
142
				if ( empty( $invoiceCountry ) ) {
143
					$invoiceCountry = $bookingInfo->Customer->Country;
144
				}
145
146
				foreach ( $countries as $country ) {
147
					if ( $invoiceCountry == $country->CountryName ) {
148
						$selectedCountry = $country->CountryCode;
149
						if ( ! empty( $country->CultureName ) ) {
150
							$selectedLocale = $country->CultureName;
151
						}
152
						break;
153
					}
154
				}
155
156
				$selectedLocale = explode( '-', $selectedLocale )[0];
157
158
				$currency = get_option( 'eduadmin-currency', 'SEK' );
159
160
				$wpConfig = ConfigurationService::getDefaultConfig();
161
				$wpOrder  = WebPay::createOrder( $wpConfig );
162
163
				$orderRow = WebPayItem::orderRow();
164
				$orderRow->setName( $bookingInfo->EventBooking->EventDescription );
165
				$orderRow->setQuantity( 1 );
166
167
				$vatPercent = ( $bookingInfo->EventBooking->VatSum / $bookingInfo->EventBooking->TotalPriceExVat ) * 100;
168
				$orderRow->setVatPercent( $vatPercent );
169
				$orderRow->setAmountIncVat( (float) $bookingInfo->EventBooking->TotalPriceIncVat );
170
171
				$customer = WebPayItem::companyCustomer();
172
173
				if ( ! empty( $bookingInfo->Customer->InvoiceName ) ) {
174
					$customer->setCompanyName( $bookingInfo->Customer->InvoiceName );
175
				} else {
176
					$customer->setCompanyName( $bookingInfo->Customer->CustomerName );
177
				}
178
179
				if ( ! empty( $bookingInfo->Customer->InvoiceAddress1 ) ) {
180
					$customer->setStreetAddress( $bookingInfo->Customer->InvoiceAddress1 );
181
				} else {
182
					$customer->setStreetAddress( $bookingInfo->Customer->Address1 );
183
				}
184
185
				if ( ! empty( $bookingInfo->Customer->InvoiceZip ) ) {
186
					$customer->setZipCode( $bookingInfo->Customer->InvoiceZip );
187
				} else {
188
					$customer->setZipCode( $bookingInfo->Customer->Zip );
189
				}
190
191
				if ( ! empty( $bookingInfo->Customer->InvoiceCity ) ) {
192
					$customer->setLocality( $bookingInfo->Customer->InvoiceCity );
193
				} else {
194
					$customer->setLocality( $bookingInfo->Customer->City );
195
				}
196
197
				if ( ! empty( $bookingInfo->Customer->Phone ) ) {
198
					$customer->setPhoneNumber( $bookingInfo->Customer->Phone );
199
				}
200
201
				if ( ! empty( $bookingInfo->Customer->InvoiceEmail ) ) {
202
					$customer->setEmail( $bookingInfo->Customer->InvoiceEmail );
203
				} else {
204
					$customer->setEmail( $bookingInfo->Customer->Email );
205
				}
206
207
				$customer->setIpAddress( EDU()->get_ip_adress() );
208
209
				$surl    = get_home_url();
210
				$cat     = get_option( 'eduadmin-rewriteBaseUrl' );
211
				$baseUrl = $surl . '/' . $cat;
212
213
				$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...
214
				$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...
215
216
				$wpForm = $wpOrder
217
					->setCurrency( $currency )
218
					->setCountryCode( $selectedCountry )
219
					->setOrderDate( date( 'c' ) )
220
					->setClientOrderNumber( $bookingInfo->EventBooking->EventCustomerLnkID )
221
					->addOrderRow( $orderRow )
222
					->addCustomerDetails( $customer )
223
					->usePayPage()
224
					->setPayPageLanguage( $selectedLocale )
225
					->setReturnUrl( apply_filters( 'eduadmin-thankyou-url', $defaultThankYou ) )
226
					->setCancelUrl( apply_filters( 'eduadmin-cancel-url', $defaultCancel ) )
227
					->getPaymentUrl();
228
229
				if ( $wpForm->accepted ) {
230
					if ( 'no' === $this->get_option( 'testrun', 'no' ) ) {
231
						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...
232
					} else {
233
						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...
234
					}
235
				} else {
236
					add_filter( 'edu-booking-error', function( $errors ) use ( &$wpForm ) {
237
						$errors[] = $wpForm->errormessage;
238
					} );
239
				}
240
			}
241
		}
242
	}
243
244
endif;