wpshop_checkout   F
last analyzed

Complexity

Total Complexity 89

Size/Duplication

Total Lines 309
Duplicated Lines 4.53 %

Coupling/Cohesion

Components 0
Dependencies 7

Importance

Changes 0
Metric Value
dl 14
loc 309
rs 1.5789
c 0
b 0
f 0
wmc 89
lcom 0
cbo 7

7 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 2 1
F process_checkout() 14 212 52
F send_order_email_to_administrator() 0 29 22
A wps_direct_payment_link() 0 9 3
A wps_direct_payment_link_nopriv() 0 7 3
B wps_direct_payment_link_verify_token() 0 7 6
A wps_direct_payment_link_url() 0 3 2

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like wpshop_checkout often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use wpshop_checkout, and based on these observations, apply Extract Interface, too.

1
<?php if ( !defined( 'ABSPATH' ) ) exit;
2
3
/*	Check if file is include. No direct access possible with file url	*/
4
if ( !defined( 'WPSHOP_VERSION' ) ) {
5
	die( __('Access is not allowed by this way', 'wpshop') );
6
}
7
8
/**
9
 * Checkout
10
 *
11
 * The WPShop checkout class handles the checkout process, collecting user data and processing the payment.
12
 *
13
 * @class 		wpwhop_checkout
14
 * @package		WPShop
15
 * @category	Class
16
 * @author		Eoxia
17
 */
18
19
20
class wpshop_checkout {
21
22
	var $div_register, $div_infos_register, $div_login, $div_infos_login = 'display:block;';
23
	var $creating_account = true;
24
25
	/** Constructor of the class
26
	* @return void
0 ignored issues
show
Comprehensibility Best Practice introduced by
Adding a @return annotation to constructors is generally not recommended as a constructor does not have a meaningful return value.

Adding a @return annotation to a constructor is not recommended, since a constructor does not have a meaningful return value.

Please refer to the PHP core documentation on constructors.

Loading history...
27
	*/
28
	function __construct () {
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...
29
	}
30
31
32
	public static function process_checkout($paymentMethod='paypal', $order_id = 0, $customer_id = 0, $customer_billing_address_id = 0, $customer_shipping_address_id = 0) {
33
34
		global $wpdb, $wpshop, $wpshop_cart;
35
		$wps_message = new wps_message_ctr();
36
		$shipping_address_option = get_option('wpshop_shipping_address_choice');
37
38
		if (is_user_logged_in()) :
39
			$user_id = get_current_user_id();
40
41
		if ( $customer_id != 0 ) {
42
			$user_id = $customer_id;
43
		}
44
45
			// If the order is already created in the db
46
			if(!empty($order_id) && is_numeric($order_id)) {
47
				$order = get_post_meta($order_id, '_order_postmeta', true);
48
49
				if(!empty($order)) {
50
					if($order['customer_id'] == $user_id) {
51
						$order['payment_method'] = $paymentMethod;
52
						$_SESSION['order_id'] = (int) $order_id;
53
						// Store cart in session
54
						//wpshop_cart::store_cart_in_session($order);
0 ignored issues
show
Unused Code Comprehensibility introduced by
72% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
55
						// Add a payment
56
						$order['order_payment']['received'][] = array( 'method' => $paymentMethod, 'waited_amount' => $order['order_amount_to_pay_now'], 'status' => 'waiting_payment', 'author' => get_current_user_id() );
57
58
						// On enregistre la commande
59
						update_post_meta($order_id, '_order_postmeta', $order);
60
						update_post_meta($order_id, '_wpshop_order_customer_id', $user_id);
61
					}
62
					else $wpshop->add_error(__('You don\'t own the order', 'wpshop'));
63
				}
64
				else $wpshop->add_error(__('The order doesn\'t exist.', 'wpshop'));
65
			}
66
			else{
67
				$order_data = array(
68
					'post_type' => WPSHOP_NEWTYPE_IDENTIFIER_ORDER,
69
					'post_title' => sprintf(__('Order - %s','wpshop'), mysql2date('d M Y\, H:i:s', current_time('mysql', 0), true)),
70
					'post_status' => 'publish',
71
					'post_excerpt' => !empty($_POST['wps-customer-comment']) ? sanitize_text_field( $_POST['wps-customer-comment'] ) : '',
72
					'post_author' => $user_id,
73
					'comment_status' => 'closed'
74
				);
75
76
				// Cart items
77
				$order_items = array();
0 ignored issues
show
Unused Code introduced by
$order_items 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...
78
				$order_tva = array();
0 ignored issues
show
Unused Code introduced by
$order_tva 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...
79
80
				//$cart = (array)$wpshop_cart->cart;
0 ignored issues
show
Unused Code Comprehensibility introduced by
56% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
81
				if ( !empty($_SESSION['cart']) && !empty( $_SESSION['cart']['shipping_method']) ) {
82
					$_SESSION['cart']['shipping_method'] = __('Standard shipping method', 'wpshop');
83
				}
84
				$cart = (array)$_SESSION['cart'];
85
86
				$download_codes = array();
87
88
				// Nouvelle commande
89
				$order_id = wp_insert_post($order_data);
90
				$_SESSION['order_id'] = $order_id;
91
92
				// Cr�ation des codes de t�l�chargement si il y a des produits t�l�chargeable dans le panier
93
				if ( !empty( $cart['order_items'] ) ) {
94
					foreach($cart['order_items'] as $c) {
95
						$product_id = $c['item_id'];
96
						$product = null;
97 View Code Duplication
						if( isset( $c['item_meta']['variations'] ) ) {
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...
98
							foreach ( $c['item_meta']['variations'] as $variation_id => $variation ) {
99
								if( isset( $variation['item_meta']['is_downloadable_'] ) ) {
100
									$product_id = $c['item_id'] . '__' . $variation_id;
101
									$product = wpshop_products::get_product_data( $product_id );
102
								}
103
							}
104
						}
105
						if( !isset( $product ) ) {
106
							$product = wpshop_products::get_product_data( $c['item_id'] );
107
							$product_id = $c['item_id'];
108
							/** Check if it's a variation and check the parent product **/
109
							if ( get_post_type( $c['item_id'] ) == WPSHOP_NEWTYPE_IDENTIFIER_PRODUCT_VARIATION ) {
110
								$parent_def = wpshop_products::get_parent_variation( $c['item_id'] );
111
								if ( !empty($parent_def) && !empty($parent_def['parent_post_meta']) && !empty($parent_def['parent_post_meta']['is_downloadable_']) ) {
112
									$product['is_downloadable_'] = $parent_def['parent_post_meta']['is_downloadable_'];
113
								}
114
							}
115
						}
116
						if(!empty($product['is_downloadable_'])) {
117
							$download_codes[$product_id] = array('item_id' => $product_id, 'download_code' => uniqid('', true));
118
						}
119
					}
120
				}
121
				if(!empty($download_codes)) update_user_meta($user_id, '_order_download_codes_'.$order_id, $download_codes);
122
123
				// Informations de commande � stocker
124
				$currency = wpshop_tools::wpshop_get_currency(true);
125
				$order = array_merge(array(
126
					'order_key' 			=> NULL,
127
					'customer_id' 			=> $user_id,
128
					'order_status' 			=> 'awaiting_payment',
129
					'order_date' 			=> current_time('mysql', 0),
130
					'order_shipping_date' 	=> null,
131
					'order_invoice_ref'		=> '',
132
					'order_currency' 		=> $currency,
133
					'order_payment' 		=> array(
134
					'customer_choice' 		=> array('method' => $paymentMethod),
135
					'received'				=> array('0' => array('method' => $paymentMethod, 'waited_amount' => $cart['order_amount_to_pay_now'], 'status' =>  'waiting_payment', 'author' => $user_id)),
136
					'shipping_method'       => ( ( !empty( $_SESSION['shipping_method']) ) ? wpshop_tools::varSanitizer( $_SESSION['shipping_method']) : __('Standard shipping method', 'wpshop') )
137
					),
138
				), $cart);
139
140
				// Si c'est un devis
141
				if ( $paymentMethod == 'quotation' ) {
142
					$order['order_temporary_key'] = wpshop_orders::get_new_pre_order_reference();
143
				}
144
				else {
145
					$order['order_key'] = wpshop_orders::get_new_order_reference();
146
				}
147
148
				//Round final amount
149
				$order['order_grand_total'] = number_format( round($order['order_grand_total'], 2), 2, '.', '');
150
				$order['order_total_ttc'] = number_format( round($order['order_total_ttc'], 2), 2, '.', '');
151
				$order['order_amount_to_pay_now'] = number_format( round($order['order_amount_to_pay_now'], 2), 2, '.', '');
152
153
				/** On enregistre la commande	*/
154
				update_post_meta($order_id, '_order_postmeta', $order);
155
				update_post_meta($order_id, '_wpshop_order_customer_id', $order['customer_id']);
156
				update_post_meta($order_id, '_wpshop_order_shipping_date', $order['order_shipping_date']);
157
				update_post_meta($order_id, '_wpshop_order_status', $order['order_status']);
158
159
160
				do_action( 'wps_order_extra_save', $order_id );
161
162
				//Add an action to extra actions on order save
163
				// @TODO : REQUEST
164
				$args = array( 'order_id' => $order_id, 'posted_data' => $_REQUEST );
165
				wpshop_tools::create_custom_hook( 'wps_order_extra_save_action', $args );
166
167
				/**	Set custmer information for the order	*/
168
				$shipping_address =  ( !empty($shipping_address_option) && !empty($shipping_address_option['activate']) ) ? ( ( !empty($_SESSION['shipping_address']) ) ? wpshop_tools::varSanitizer($_SESSION['shipping_address']) : $customer_shipping_address_id ) : '';
169
				$billing_address =  ( !empty($_SESSION['billing_address']) ) ? wpshop_tools::varSanitizer($_SESSION['billing_address']) : $customer_billing_address_id;
170
171
172
				if ( !empty( $billing_address) ) {
173
					wpshop_orders::set_order_customer_addresses($user_id, $order_id, $shipping_address, $billing_address);
174
				}
175
176
				if ( !empty($_SESSION['shipping_address_to_save']) ) {
177
					$order_infos_postmeta = get_post_meta($order_id, '_order_info', true);
178
					$order_infos_postmeta['shipping']['address'] = $_SESSION['shipping_address_to_save'];
179
					$order_infos_postmeta['shipping']['address_id'] = '';
180
					update_post_meta($order_id, '_order_info', $order_infos_postmeta);
181
					unset( $_SESSION['shipping_address_to_save'] );
182
				}
183
184
185
				/** Save Coupon use **/
186
				if ( !empty($_SESSION['cart']['coupon_id']) ) {
187
					$wps_coupon_mdl = new wps_coupon_model();
188
					$wps_coupon_mdl->save_coupon_use( $_SESSION['cart']['coupon_id'] );
189
				}
190
191
				/**	Notify the customer as the case	*/
192
				$user_info = get_userdata($user_id);
193
				$email = $user_info->user_email;
194
				$first_name = $user_info->user_firstname ;
195
				$last_name = $user_info->user_lastname;
196
197
				// Envoie du message de confirmation de commande au client
198
				$order_meta = get_post_meta( $order_id, '_order_postmeta', true);
199
200
				$shipping_mode_option = get_option( 'wps_shipping_mode' );
201
				$shipping_method = ( !empty($order_meta['order_payment']['shipping_method']) && !empty($shipping_mode_option) && !empty($shipping_mode_option['modes']) && is_array($shipping_mode_option['modes']) && array_key_exists($order_meta['order_payment']['shipping_method'], $shipping_mode_option['modes'])) ? $shipping_mode_option['modes'][$order_meta['order_payment']['shipping_method']]['name'] : ( (!empty($order_meta['order_payment']['shipping_method']) ) ? $order_meta['order_payment']['shipping_method'] : '' );
202
203
				if ( !empty($order_meta) && !empty($order_meta['cart_type']) && $order_meta['cart_type'] == 'quotation' && empty($order_meta['order_key']) ) {
204
					$wps_message->wpshop_prepared_email($email, 'WPSHOP_QUOTATION_CONFIRMATION_MESSAGE', array('order_id' => $order_id,'customer_first_name' => $first_name, 'customer_last_name' => $last_name, 'customer_email' => $email, 'order_date' => current_time('mysql', 0), 'order_content' => '', 'order_addresses' => '', 'order_customer_comments' => '', 'order_billing_address' => '', 'order_shipping_address' => '', 'order_shipping_method' => $shipping_method, 'order_personnal_informations' => '') );
205
				}
206
				else {
207
					$email_option = get_option( 'wpshop_emails' );
208
					if ( empty($email_option['send_confirmation_order_message']) ) {
209
						$payment_method_option = get_option( 'wps_payment_mode' );
210
						$order_payment_method = ( !empty($payment_method_option) && !empty($payment_method_option['mode']) && !empty($order_meta['order_payment']['customer_choice']['method']) && !empty($payment_method_option['mode'][$order_meta['order_payment']['customer_choice']['method']])  ) ? $payment_method_option['mode'][$order_meta['order_payment']['customer_choice']['method']]['name'] : $order_meta['order_payment']['customer_choice']['method'];
211
212
						$wps_message->wpshop_prepared_email($email, 'WPSHOP_ORDER_CONFIRMATION_MESSAGE', array('order_id' => $order_id,'customer_first_name' => $first_name, 'customer_last_name' => $last_name, 'customer_email' => $email, 'order_key' => ( ( !empty($order_meta['order_key']) ) ? $order_meta['order_key'] : ''),'order_date' => current_time('mysql', 0),  'order_payment_method' => $order_payment_method, 'order_content' => '', 'order_addresses' => '', 'order_customer_comments' => '', 'order_billing_address' => '', 'order_shipping_address' => '',  'order_shipping_method' => $shipping_method, 'order_personnal_informations' => '' ) );
213
					}
214
				}
215
216 View Code Duplication
				if ( empty($_SESSION['wps-pos-addon']) ) {
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...
217
					$email_option = get_option('wpshop_emails');
218
					if( empty($email_option) || ( !empty($email_option) && empty($email_option['send_confirmation_order_message']) ) ){
219
						self::send_order_email_to_administrator( $order_id, $user_info );
220
					}
221
				}
222
223
224
				/** IF Order amount is 0, Finish the Order **/
225
				if ( $cart['order_amount_to_pay_now'] == 0 ) {
226
					$order_meta = get_post_meta($order_id, '_order_postmeta', true);
227
					$payment_status = 'completed';
228
					$params_array = array (
229
						'method' =>'free',
230
						'waited_amount' => $order_meta['order_amount_to_pay_now'],
231
						'status' =>  'payment_received',
232
						'author' => $order_meta['customer_id'],
233
						'payment_reference' => 'FREE_ORDER',
234
						'date' => current_time('mysql', 0),
235
						'received_amount' => $order_meta['order_amount_to_pay_now']
236
					);
237
					wpshop_payment::check_order_payment_total_amount($order_id, $params_array, $payment_status);
238
				}
239
				apply_filters( 'wpshop_finish_order_extra_actions', $order_id);
240
			}
241
		endif;
242
		return $order_id;
243
	}
244
245
	public static function send_order_email_to_administrator ( $order_id, $customer_infos = ''  ) {
246
		if ( !empty($order_id) ) {
247
			$wps_message = new wps_message_ctr();
248
			$order_infos = get_post_meta($order_id, '_order_postmeta', true);
249
			//Send email to administrator(s)
250
			$shop_admin_email_option = get_option('wpshop_emails');
251
			$shop_admin_email = $shop_admin_email_option['contact_email'];
252
			$order_tmp_key = '';
253
254
			$shipping_mode_option = get_option( 'wps_shipping_mode' );
255
			$shipping_method = ( !empty($order_infos['order_payment']['shipping_method']) && !empty($shipping_mode_option) && !empty($shipping_mode_option['modes']) && is_array($shipping_mode_option['modes']) && array_key_exists($order_infos['order_payment']['shipping_method'], $shipping_mode_option['modes'])) ? $shipping_mode_option['modes'][$order_infos['order_payment']['shipping_method']]['name'] : ( (!empty($order_infos['order_payment']['shipping_method']) ) ? $order_infos['order_payment']['shipping_method'] : '' );
256
257
258
			if( !empty( $order_infos ) && !empty($order_infos['cart_type']) && $order_infos['cart_type'] == 'normal' && !empty($order_infos['order_key']) ){
259
				$message_type = 'WPSHOP_NEW_ORDER_ADMIN_MESSAGE';
260
			}
261
			else {
262
				$message_type = 'WPSHOP_NEW_QUOTATION_ADMIN_MESSAGE';
263
				$order_tmp_key = $order_infos['order_temporary_key'];
264
			}
265
266
			$payment_method_option = get_option( 'wps_payment_mode' );
267
			$order_payment_method = ( !empty($payment_method_option) && !empty($payment_method_option['mode']) && !empty($order_infos['order_payment']['customer_choice']['method']) && !empty($payment_method_option['mode'][$order_infos['order_payment']['customer_choice']['method']])  ) ? $payment_method_option['mode'][$order_infos['order_payment']['customer_choice']['method']]['name'] : $order_infos['order_payment']['customer_choice']['method'];
268
269
			$data_to_send = array('order_id' => $order_id, 'order_key' => $order_infos['order_key'], 'customer_email' => ( !empty($customer_infos) && !empty($customer_infos->user_email) ) ? $customer_infos->user_email : '' , 'customer_last_name' => ( !empty($customer_infos) && !empty($customer_infos->user_lastname) ) ? $customer_infos->user_lastname : '', 'customer_first_name' => ( !empty($customer_infos) && !empty($customer_infos->user_firstname) ) ? $customer_infos->user_firstname : '', 'order_date' => $order_infos['order_date'], 'order_payment_method' => $order_payment_method, 'order_temporary_key' => $order_tmp_key, 'order_content' => '', 'order_addresses' => '', 'order_customer_comments' => '', 'order_billing_address' => '', 'order_shipping_address' => '','order_shipping_method' => $shipping_method, 'order_personnal_informations' => '' );
270
271
			$wps_message->wpshop_prepared_email( $shop_admin_email, $message_type, $data_to_send, array('object_type' => 'order', 'object_id' => $order_id));
272
		}
273
	}
274
275
	/**
276
	 * Check token connect user and move to step 5.
277
	 *
278
	 * @method wps_direct_payment_link
279
	 * @param mixed $data Array or false.
280
	 * @return void
281
	 */
282
	public static function wps_direct_payment_link( $data = false ) {
283
		$data = empty( $data ) ? self::wps_direct_payment_link_verify_token() : $data;
284
		if ( (bool) $data ) {
285
			wps_orders_ctr::pay_quotation( $data['oid'] );
286
			wpshop_tools::wpshop_safe_redirect( get_permalink( wpshop_tools::get_page_id( get_option( 'wpshop_checkout_page_id' ) ) ) . '?order_step=5' );
287
		} else {
288
			wpshop_tools::wpshop_safe_redirect( get_permalink( wpshop_tools::get_page_id( get_option( 'wpshop_myaccount_page_id' ) ) ) );
289
		}
290
	}
291
	/**
292
	 * Use wps_direct_payment_link and force connect.
293
	 *
294
	 * @method wps_direct_payment_link_nopriv
295
	 * @param mixed $data Array or false.
296
	 * @return void
297
	 */
298
	public static function wps_direct_payment_link_nopriv( $data = false ) {
299
		$data = empty( $data ) ? self::wps_direct_payment_link_verify_token() : $data;
300
		if ( (bool) $data ) {
301
			wp_set_auth_cookie( $data['cid'], true, is_ssl() );
302
		}
303
		self::wps_direct_payment_link( $data );
304
	}
305
	/**
306
	 * Verify token in request.
307
	 *
308
	 * @method wps_direct_payment_link_verify_token
309
	 * @return mixed Customer id or false.
310
	 */
311
	public static function wps_direct_payment_link_verify_token() {
312
		$token = ! empty( $_GET['token'] ) ? sanitize_text_field( $_GET['token'] ) : '';
313
		$order_id = ! empty( $_GET['order_id'] ) ? (int) $_GET['order_id'] : '';
314
		$order_metadata = get_post_meta( $order_id, '_order_postmeta', true );
315
		$customer_id = ! empty( $order_metadata['customer_id'] ) ? (int) $order_metadata['customer_id'] : false;
316
		return ( (bool) $customer_id && wps_orders_ctr::wps_verify_token_order( $token, (int) $order_id ) ) ? array( 'oid' => $order_id, 'cid' => $customer_id ) : false;
317
	}
318
	/**
319
	 * Get URL for wps_direct_link.
320
	 *
321
	 * @method wps_direct_payment_link_url
322
	 * @param  int $order_id OrderID.
323
	 * @return string Url or empty string.
324
	 */
325
	public static function wps_direct_payment_link_url( $order_id ) {
326
		return ( (bool) ( $token = wps_orders_ctr::wps_token_order_customer( (int) $order_id ) ) ) ? admin_url( 'admin-post.php?action=wps_direct_payment_link&token=' . $token . '&amp;order_id=' . (int) $order_id ) : '';
327
	}
328
}
329