Passed
Push — master ( 0cc6c6...451f1a )
by Brian
06:48 queued 27s
created

GetPaid_Checkout   F

Complexity

Total Complexity 66

Size/Duplication

Total Lines 474
Duplicated Lines 0 %

Importance

Changes 3
Bugs 0 Features 0
Metric Value
eloc 166
c 3
b 0
f 0
dl 0
loc 474
rs 3.12
wmc 66

15 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 2 1
A process_checkout() 0 24 1
B validate_submission() 0 34 9
A get_submission_invoice() 0 17 4
A get_submission_items() 0 10 3
B get_submission_customer() 0 35 9
A process_submission_invoice() 0 24 2
A process_payment() 0 35 4
A send_redirect_response() 0 3 1
F prepare_submission_data_for_saving() 0 85 19
A prepare_shipping_info() 0 9 2
A prepare_billing_info() 0 6 1
A post_process_submission() 0 35 6
A process_free_payment() 0 6 1
A prepare_address_details() 0 24 3

How to fix   Complexity   

Complex Class

Complex classes like GetPaid_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.

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 GetPaid_Checkout, and based on these observations, apply Extract Interface, too.

1
<?php
2
/**
3
 * Contains the Main Checkout Class.
4
 *
5
 */
6
7
defined( 'ABSPATH' ) || exit;
8
9
/**
10
 * Main Checkout Class.
11
 *
12
 */
13
class GetPaid_Checkout {
14
15
	/**
16
	 * @var GetPaid_Payment_Form_Submission
17
	 */
18
	protected $payment_form_submission;
19
20
	/**
21
	 * Class constructor.
22
	 * 
23
	 * @param GetPaid_Payment_Form_Submission $submission
24
	 */
25
	public function __construct( $submission ) {
26
		$this->payment_form_submission = $submission;
27
	}
28
29
	/**
30
	 * Processes the checkout.
31
	 *
32
	 */
33
	public function process_checkout() {
34
35
		// Validate the submission.
36
		$this->validate_submission();
37
38
		// Prepare the invoice.
39
		$items      = $this->get_submission_items();
40
		$invoice    = $this->get_submission_invoice();
41
		$invoice    = $this->process_submission_invoice( $invoice, $items );
42
		$prepared   = $this->prepare_submission_data_for_saving();
43
44
		$this->prepare_billing_info( $invoice );
45
46
		$shipping   = $this->prepare_shipping_info( $invoice );
47
48
		// Save the invoice.
49
		$invoice->set_is_viewed( true );
50
		$invoice->recalculate_total();
51
        $invoice->save();
52
53
		do_action( 'getpaid_checkout_invoice_updated', $invoice );
54
55
		// Send to the gateway.
56
		$this->post_process_submission( $invoice, $prepared, $shipping );
57
	}
58
59
	/**
60
	 * Validates the submission.
61
	 *
62
	 */
63
	protected function validate_submission() {
64
65
		$submission = $this->payment_form_submission;
66
		$data       = $submission->get_data();
67
68
		// Do we have an error?
69
        if ( ! empty( $submission->last_error ) ) {
70
			wp_send_json_error( $submission->last_error );
71
        }
72
73
		// We need a billing email.
74
        if ( ! $submission->has_billing_email() ) {
75
            wp_send_json_error( __( 'Provide a valid billing email.', 'invoicing' ) );
76
		}
77
78
		// Non-recurring gateways should not be allowed to process recurring invoices.
79
		if ( $submission->should_collect_payment_details() && $submission->has_recurring && ! wpinv_gateway_support_subscription( $data['wpi-gateway'] ) ) {
80
			wp_send_json_error( __( 'The selected payment gateway does not support subscription payments.', 'invoicing' ) );
81
		}
82
83
		// Ensure the gateway is active.
84
		if ( $submission->should_collect_payment_details() && ! wpinv_is_gateway_active( $data['wpi-gateway'] ) ) {
85
			wpinv_set_error( 'invalid_gateway', __( 'The selected payment gateway is not active', 'invoicing' ) );
86
		}
87
88
		// Clear any existing errors.
89
		wpinv_clear_errors();
90
91
		// Allow themes and plugins to hook to errors
92
		do_action( 'getpaid_checkout_error_checks', $submission );
93
94
		// Do we have any errors?
95
        if ( wpinv_get_errors() ) {
96
            wp_send_json_error( getpaid_get_errors_html() );
97
		}
98
99
	}
100
101
	/**
102
	 * Retrieves submission items.
103
	 *
104
	 * @return GetPaid_Form_Item[]
105
	 */
106
	protected function get_submission_items() {
107
108
		$items = $this->payment_form_submission->get_items();
109
110
        // Ensure that we have items.
111
        if ( empty( $items ) && ! $this->payment_form_submission->has_fees() ) {
112
            wp_send_json_error( __( 'Please provide at least one item or amount.', 'invoicing' ) );
113
		}
114
115
		return $items;
116
	}
117
118
	/**
119
	 * Retrieves submission invoice.
120
	 *
121
	 * @return WPInv_Invoice
122
	 */
123
	protected function get_submission_invoice() {
124
		$submission = $this->payment_form_submission;
125
126
		if ( ! $submission->has_invoice() ) {
127
			$invoice = new WPInv_Invoice();
128
			$invoice->set_created_via( 'payment_form' );
129
			return $invoice;
130
        }
131
132
		$invoice = $submission->get_invoice();
133
134
		// Make sure that it is neither paid or refunded.
135
		if ( $invoice->is_paid() || $invoice->is_refunded() ) {
136
			wp_send_json_error( __( 'This invoice has already been paid for.', 'invoicing' ) );
137
		}
138
139
		return $invoice;
140
	}
141
142
	/**
143
	 * Processes the submission invoice.
144
	 *
145
	 * @param WPInv_Invoice $invoice
146
	 * @param GetPaid_Form_Item[] $items
147
	 * @return WPInv_Invoice
148
	 */
149
	protected function process_submission_invoice( $invoice, $items ) {
150
151
		$submission = $this->payment_form_submission;
152
153
		// Set-up the invoice details.
154
		$invoice->set_email( sanitize_email( $submission->get_billing_email() ) );
155
		$invoice->set_user_id( $this->get_submission_customer() );
156
		$invoice->set_payment_form( absint( $submission->get_payment_form()->get_id() ) );
157
        $invoice->set_items( $items );
158
        $invoice->set_fees( $submission->get_fees() );
159
        $invoice->set_taxes( $submission->get_taxes() );
160
		$invoice->set_discounts( $submission->get_discounts() );
161
		$invoice->set_gateway( $submission->get_field( 'wpi-gateway' ) );
0 ignored issues
show
Bug introduced by
Are you sure the usage of $submission->get_field('wpi-gateway') targeting GetPaid_Payment_Form_Submission::get_field() seems to always return null.

This check looks for function or method calls that always return null and whose return value is used.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
if ($a->getObject()) {

The method getObject() can return nothing but null, so it makes no sense to use the return value.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
162
		$invoice->set_currency( $submission->get_currency() );
163
164
		$address_confirmed = $submission->get_field( 'confirm-address' );
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $address_confirmed is correct as $submission->get_field('confirm-address') targeting GetPaid_Payment_Form_Submission::get_field() seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
165
		$invoice->set_address_confirmed( ! empty( $address_confirmed ) );
166
167
		if ( $submission->has_discount_code() ) {
168
            $invoice->set_discount_code( $submission->get_discount_code() );
169
		}
170
171
		getpaid_maybe_add_default_address( $invoice );
172
		return $invoice;
173
	}
174
175
	/**
176
	 * Retrieves the submission's customer.
177
	 *
178
	 * @return int The customer id.
179
	 */
180
	protected function get_submission_customer() {
181
		$submission = $this->payment_form_submission;
182
183
		// If this is an existing invoice...
184
		if ( $submission->has_invoice() ) {
185
			return $submission->get_invoice()->get_user_id();
186
		}
187
188
		// (Maybe) create the user.
189
        $user = get_current_user_id();
190
191
        if ( empty( $user ) ) {
192
            $user = get_user_by( 'email', $submission->get_billing_email() );
193
        }
194
195
        if ( empty( $user ) ) {
196
            $user = wpinv_create_user( $submission->get_billing_email() );
197
198
			// (Maybe) send new user notification.
199
			$should_send_notification = wpinv_get_option( 'disable_new_user_emails' );
200
			if ( ! empty( $user ) && is_numeric( $user ) && apply_filters( 'getpaid_send_new_user_notification', empty( $should_send_notification ), $user ) ) {
201
				wp_send_new_user_notifications( $user, 'user' );
202
			}
203
204
        }
205
206
        if ( is_wp_error( $user ) ) {
207
            wp_send_json_error( $user->get_error_message() );
208
        }
209
210
        if ( is_numeric( $user ) ) {
211
            return $user;
212
		}
213
214
		return $user->ID;
215
216
	}
217
218
	/**
219
     * Prepares submission data for saving to the database.
220
     *
221
	 * @return array
222
     */
223
    public function prepare_submission_data_for_saving() {
224
225
		$submission = $this->payment_form_submission;
226
227
		// Prepared submission details.
228
        $prepared = array(
229
			'all'  => array(),
230
			'meta' => array(),
231
		);
232
233
        // Raw submission details.
234
		$data     = $submission->get_data();
235
236
		// Loop through the submitted details.
237
        foreach ( $submission->get_payment_form()->get_elements() as $field ) {
238
239
			// Skip premade fields.
240
            if ( ! empty( $field['premade'] ) ) {
241
                continue;
242
            }
243
244
			// Ensure address is provided.
245
			if ( $field['type'] == 'address' ) {
246
                $address_type = 'shipping' === $field['address_type'] ? 'shipping' : 'billing';
247
248
				foreach ( $field['fields'] as $address_field ) {
249
250
					if ( ! empty( $address_field['visible'] ) && ! empty( $address_field['required'] ) && '' === trim( $_POST[ $address_type ][ $address_field['name'] ] ) ) {
251
						wp_send_json_error( __( 'Please fill all required fields.', 'invoicing' ) );
252
					}
253
254
				}
255
256
            }
257
258
            // If it is required and not set, abort.
259
            if ( ! $submission->is_required_field_set( $field ) ) {
260
                wp_send_json_error( __( 'Please fill all required fields.', 'invoicing' ) );
261
            }
262
263
            // Handle misc fields.
264
            if ( isset( $data[ $field['id'] ] ) ) {
265
266
				// Uploads.
267
				if ( $field['type'] == 'file_upload' ) {
268
					$max_file_num = empty( $field['max_file_num'] ) ? 1 : absint( $field['max_file_num'] );
269
270
					if ( count( $data[ $field['id'] ] ) > $max_file_num ) {
271
						wp_send_json_error( __( 'Maximum number of allowed files exceeded.', 'invoicing' ) );
272
					}
273
274
					$value = array();
275
276
					foreach ( $data[ $field['id'] ] as $url => $name ) {
277
						$value[] = sprintf(
278
							'<a href="%s" target="_blank">%s</a>',
279
							esc_url_raw( $url ),
280
							esc_html( $name )
281
						);
282
					}
283
284
					$value = implode( ' | ', $value );
285
286
				} else if ( $field['type'] == 'checkbox' ) {
287
					$value = isset( $data[ $field['id'] ] ) ? __( 'Yes', 'invoicing' ) : __( 'No', 'invoicing' );
288
				} else {
289
					$value = wp_kses_post( $data[ $field['id'] ] );
290
				}
291
292
                $label = $field['id'];
293
294
                if ( isset( $field['label'] ) ) {
295
                    $label = $field['label'];
296
                }
297
298
				if ( ! empty( $field['add_meta'] ) ) {
299
					$prepared['meta'][ wpinv_clean( $label ) ] = wp_kses_post_deep( $value );
300
				}
301
				$prepared['all'][ wpinv_clean( $label ) ] = wp_kses_post_deep( $value );
302
303
            }
304
305
		}
306
307
		return $prepared;
308
309
	}
310
311
	/**
312
     * Retrieves address details.
313
     *
314
	 * @return array
315
	 * @param WPInv_Invoice $invoice
316
	 * @param string $type
317
     */
318
    public function prepare_address_details( $invoice, $type = 'billing' ) {
319
320
		$data     = $this->payment_form_submission->get_data();
321
		$type     = sanitize_key( $type );
322
		$address  = array();
323
		$prepared = array();
324
325
		if ( ! empty( $data[ $type ] ) ) {
326
			$address = $data[ $type ];
327
		}
328
329
		// Clean address details.
330
		foreach ( $address as $key => $value ) {
331
			$key             = sanitize_key( $key );
332
			$key             = str_replace( 'wpinv_', '', $key );
333
			$value           = wpinv_clean( $value );
334
			$prepared[ $key] = apply_filters( "getpaid_checkout_{$type}_address_$key", $value, $this->payment_form_submission, $invoice );
335
		}
336
337
		// Filter address details.
338
		$prepared = apply_filters( "getpaid_checkout_{$type}_address", $prepared, $this->payment_form_submission, $invoice );
339
340
		// Remove non-whitelisted values.
341
		return array_filter( $prepared, 'getpaid_is_address_field_whitelisted', ARRAY_FILTER_USE_KEY );
342
343
	}
344
345
	/**
346
     * Prepares the billing details.
347
     *
348
	 * @return array
349
	 * @param WPInv_Invoice $invoice
350
     */
351
    protected function prepare_billing_info( &$invoice ) {
352
353
		$billing_address = $this->prepare_address_details( $invoice, 'billing' );
354
355
		// Update the invoice with the billing details.
356
		$invoice->set_props( $billing_address );
357
358
	}
359
360
	/**
361
     * Prepares the shipping details.
362
     *
363
	 * @return array
364
	 * @param WPInv_Invoice $invoice
365
     */
366
    protected function prepare_shipping_info( $invoice ) {
367
368
		$data = $this->payment_form_submission->get_data();
369
370
		if ( empty( $data['same-shipping-address'] ) ) {
371
			return $this->prepare_address_details( $invoice, 'shipping' );
372
		}
373
374
		return $this->prepare_address_details( $invoice, 'billing' );
375
376
	}
377
378
	/**
379
	 * Confirms the submission is valid and send users to the gateway.
380
	 *
381
	 * @param WPInv_Invoice $invoice
382
	 * @param array $prepared_payment_form_data
383
	 * @param array $shipping
384
	 */
385
	protected function post_process_submission( $invoice, $prepared_payment_form_data, $shipping ) {
386
387
		// Ensure the invoice exists.
388
        if ( ! $invoice->exists() ) {
389
            wp_send_json_error( __( 'An error occured while saving your invoice. Please try again.', 'invoicing' ) );
390
        }
391
392
		// Save payment form data.
393
		$prepared_payment_form_data = apply_filters( 'getpaid_prepared_payment_form_data', $prepared_payment_form_data, $invoice );
394
        delete_post_meta( $invoice->get_id(), 'payment_form_data' );
395
		delete_post_meta( $invoice->get_id(), 'additional_meta_data' );
396
		if ( ! empty( $prepared_payment_form_data ) ) {
397
398
			if ( ! empty( $prepared_payment_form_data['all'] ) ) {
399
				update_post_meta( $invoice->get_id(), 'payment_form_data', $prepared_payment_form_data['all'] );
400
			}
401
402
			if ( ! empty( $prepared_payment_form_data['meta'] ) ) {
403
				update_post_meta( $invoice->get_id(), 'additional_meta_data', $prepared_payment_form_data['meta'] );
404
			}
405
406
		}
407
408
		// Save payment form data.
409
        if ( ! empty( $shipping ) ) {
410
            update_post_meta( $invoice->get_id(), 'shipping_address', $shipping );
411
		}
412
413
		// Backwards compatibility.
414
        add_filter( 'wp_redirect', array( $this, 'send_redirect_response' ) );
415
416
		$this->process_payment( $invoice );
417
418
        // If we are here, there was an error.
419
		wpinv_send_back_to_checkout( $invoice );
420
421
	}
422
423
	/**
424
	 * Processes the actual payment.
425
	 *
426
	 * @param WPInv_Invoice $invoice
427
	 */
428
	protected function process_payment( $invoice ) {
429
430
		// Clear any checkout errors.
431
		wpinv_clear_errors();
432
433
		// No need to send free invoices to the gateway.
434
		if ( $invoice->is_free() ) {
435
			$this->process_free_payment( $invoice );
436
		}
437
438
		$submission = $this->payment_form_submission;
439
440
		// Fires before sending to the gateway.
441
		do_action( 'getpaid_checkout_before_gateway', $invoice, $submission );
442
443
		// Allow the sumission data to be modified before it is sent to the gateway.
444
		$submission_data    = $submission->get_data();
445
		$submission_gateway = apply_filters( 'getpaid_gateway_submission_gateway', $invoice->get_gateway(), $submission, $invoice );
446
		$submission_data    = apply_filters( 'getpaid_gateway_submission_data', $submission_data, $submission, $invoice );
447
448
		// Validate the currency.
449
		if ( ! apply_filters( "getpaid_gateway_{$submission_gateway}_is_valid_for_currency", true, $invoice->get_currency() ) ) {
450
			wpinv_set_error( 'invalid_currency', __( 'The chosen payment gateway does not support this currency', 'invoicing' ) );
451
		}
452
453
		// Check to see if we have any errors.
454
		if ( wpinv_get_errors() ) {
455
			wpinv_send_back_to_checkout( $invoice );
456
		}
457
458
		// Send info to the gateway for payment processing
459
		do_action( "getpaid_gateway_$submission_gateway", $invoice, $submission_data, $submission );
460
461
		// Backwards compatibility.
462
		wpinv_send_to_gateway( $submission_gateway, $invoice );
0 ignored issues
show
Deprecated Code introduced by
The function wpinv_send_to_gateway() has been deprecated. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

462
		/** @scrutinizer ignore-deprecated */ wpinv_send_to_gateway( $submission_gateway, $invoice );
Loading history...
463
464
	}
465
466
	/**
467
	 * Marks the invoice as paid in case the checkout is free.
468
	 *
469
	 * @param WPInv_Invoice $invoice
470
	 */
471
	protected function process_free_payment( $invoice ) {
472
473
		$invoice->set_gateway( 'none' );
474
		$invoice->add_note( __( "This is a free invoice and won't be sent to the payment gateway", 'invoicing' ), false, false, true );
475
		$invoice->mark_paid();
476
		wpinv_send_to_success_page( array( 'invoice_key' => $invoice->get_key() ) );
477
478
	}
479
480
	/**
481
     * Sends a redrect response to payment details.
482
     *
483
     */
484
    public function send_redirect_response( $url ) {
485
        $url = urlencode( $url );
486
        wp_send_json_success( $url );
487
    }
488
489
}
490