Completed
Push — master ( 6d8164...bf7249 )
by Roy
03:26
created

WC_Gateway_Stripe_Bitcoin   B

Complexity

Total Complexity 53

Size/Duplication

Total Lines 413
Duplicated Lines 0 %

Coupling/Cohesion

Components 2
Dependencies 4

Importance

Changes 0
Metric Value
dl 0
loc 413
rs 7.4757
c 0
b 0
f 0
wmc 53
lcom 2
cbo 4

15 Methods

Rating   Name   Duplication   Size   Complexity  
F __construct() 0 40 11
A check_environment() 0 17 4
A get_environment_warning() 0 9 3
A get_supported_currency() 0 5 1
A is_available() 0 7 2
A payment_icons() 0 5 1
A get_icon() 0 9 1
B payment_scripts() 0 8 5
A init_form_fields() 0 3 1
B payment_fields() 0 28 5
A thankyou_page() 0 3 1
B email_instructions() 0 9 6
B get_instructions() 0 39 2
A save_instructions() 0 11 2
C process_payment() 0 59 8

How to fix   Complexity   

Complex Class

Complex classes like WC_Gateway_Stripe_Bitcoin 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 WC_Gateway_Stripe_Bitcoin, and based on these observations, apply Extract Interface, too.

1
<?php
2
if ( ! defined( 'ABSPATH' ) ) {
3
	exit;
4
}
5
6
/**
7
 * Class that handles Bitcoin payment method.
8
 *
9
 * @extends WC_Gateway_Stripe
10
 *
11
 * @since 4.0.0
12
 */
13
class WC_Gateway_Stripe_Bitcoin extends WC_Stripe_Payment_Gateway {
14
	/**
15
	 * Notices (array)
16
	 * @var array
17
	 */
18
	public $notices = array();
19
20
	/**
21
	 * Is test mode active?
22
	 *
23
	 * @var bool
24
	 */
25
	public $testmode;
26
27
	/**
28
	 * Alternate credit card statement name
29
	 *
30
	 * @var bool
31
	 */
32
	public $statement_descriptor;
33
34
	/**
35
	 * API access secret key
36
	 *
37
	 * @var string
38
	 */
39
	public $secret_key;
40
41
	/**
42
	 * Api access publishable key
43
	 *
44
	 * @var string
45
	 */
46
	public $publishable_key;
47
48
	/**
49
	 * Should we store the users credit cards?
50
	 *
51
	 * @var bool
52
	 */
53
	public $saved_cards;
54
55
	/**
56
	 * Instructions for Bitcoin payment.
57
	 *
58
	 * @var string
59
	 */
60
	public $instructions;
61
62
	/**
63
	 * Constructor
64
	 */
65
	public function __construct() {
66
		$this->id                   = 'stripe_bitcoin';
67
		$this->method_title         = __( 'Stripe Bitcoin', 'woocommerce-gateway-stripe' );
68
		/* translators: link */
69
		$this->method_description   = sprintf( __( 'All other general Stripe settings can be adjusted <a href="%s">here</a>.', 'woocommerce-gateway-stripe' ), admin_url( 'admin.php?page=wc-settings&tab=checkout&section=stripe' ) );
70
		$this->supports             = array(
71
			'products',
72
			'refunds',
73
		);
74
75
		// Load the form fields.
76
		$this->init_form_fields();
77
78
		// Load the settings.
79
		$this->init_settings();
80
81
		$main_settings              = get_option( 'woocommerce_stripe_settings' );
82
		$this->title                = $this->get_option( 'title' );
83
		$this->description          = $this->get_option( 'description' );
84
		$this->enabled              = $this->get_option( 'enabled' );
85
		$this->testmode             = ( ! empty( $main_settings['testmode'] ) && 'yes' === $main_settings['testmode'] ) ? true : false;
86
		$this->saved_cards          = ( ! empty( $main_settings['saved_cards'] ) && 'yes' === $main_settings['saved_cards'] ) ? true : false;
87
		$this->publishable_key      = ! empty( $main_settings['publishable_key'] ) ? $main_settings['publishable_key'] : '';
88
		$this->secret_key           = ! empty( $main_settings['secret_key'] ) ? $main_settings['secret_key'] : '';
89
		$this->statement_descriptor = ! empty( $main_settings['statement_descriptor'] ) ? $main_settings['statement_descriptor'] : '';
90
91
		if ( $this->testmode ) {
92
			$this->publishable_key = ! empty( $main_settings['test_publishable_key'] ) ? $main_settings['test_publishable_key'] : '';
93
			$this->secret_key      = ! empty( $main_settings['test_secret_key'] ) ? $main_settings['test_secret_key'] : '';
94
		}
95
96
		add_action( 'woocommerce_update_options_payment_gateways_' . $this->id, array( $this, 'process_admin_options' ) );
97
		add_action( 'admin_notices', array( $this, 'check_environment' ) );
98
		add_action( 'admin_head', array( $this, 'remove_admin_notice' ) );
99
		add_action( 'wp_enqueue_scripts', array( $this, 'payment_scripts' ) );
100
		add_action( 'woocommerce_thankyou_stripe_bitcoin', array( $this, 'thankyou_page' ) );
101
102
		// Customer Emails
103
		add_action( 'woocommerce_email_before_order_table', array( $this, 'email_instructions' ), 10, 3 );
104
	}
105
106
	/**
107
	 * Checks to make sure environment is setup correctly to use this payment method.
108
	 *
109
	 * @since 4.0.0
110
	 * @version 4.0.0
111
	 */
112
	public function check_environment() {
113
		if ( ! current_user_can( 'manage_woocommerce' ) ) {
114
			return;
115
		}
116
117
		$environment_warning = $this->get_environment_warning();
118
119
		if ( $environment_warning ) {
120
			$this->add_admin_notice( 'bad_environment', 'error', $environment_warning );
121
		}
122
123
		foreach ( (array) $this->notices as $notice_key => $notice ) {
124
			echo "<div class='" . esc_attr( $notice['class'] ) . "'><p>";
125
			echo wp_kses( $notice['message'], array( 'a' => array( 'href' => array() ) ) );
126
			echo '</p></div>';
127
		}
128
	}
129
130
	/**
131
	 * Checks the environment for compatibility problems. Returns a string with the first incompatibility
132
	 * found or false if the environment has no problems.
133
	 *
134
	 * @since 4.0.0
135
	 * @version 4.0.0
136
	 */
137
	public function get_environment_warning() {
138
		if ( 'yes' === $this->enabled && ! in_array( get_woocommerce_currency(), $this->get_supported_currency() ) ) {
139
			$message = __( 'Bitcoin is enabled - it requires store currency to be set to USD.', 'woocommerce-gateway-stripe' );
140
141
			return $message;
142
		}
143
144
		return false;
145
	}
146
147
	/**
148
	 * Returns all supported currencies for this payment method.
149
	 *
150
	 * @since 4.0.0
151
	 * @version 4.0.0
152
	 * @return array
153
	 */
154
	public function get_supported_currency() {
155
		return apply_filters( 'wc_stripe_bitcoin_supported_currencies', array(
156
			'USD',
157
		) );
158
	}
159
160
	/**
161
	 * Checks to see if all criteria is met before showing payment method.
162
	 *
163
	 * @since 4.0.0
164
	 * @version 4.0.0
165
	 * @return bool
166
	 */
167
	public function is_available() {
168
		if ( ! in_array( get_woocommerce_currency(), $this->get_supported_currency() ) ) {
169
			return false;
170
		}
171
172
		return parent::is_available();
173
	}
174
175
	/**
176
	 * All payment icons that work with Stripe.
177
	 *
178
	 * @since 4.0.0
179
	 * @version 4.0.0
180
	 * @return array
181
	 */
182
	public function payment_icons() {
183
		return apply_filters( 'wc_stripe_payment_icons', array(
184
			'bitcoin' => '<i class="stripe-pf stripe-pf-bitcoin stripe-pf-right" alt="Bitcoin" aria-hidden="true"></i>',
185
		) );
186
	}
187
188
	/**
189
	 * Get_icon function.
190
	 *
191
	 * @since 1.0.0
192
	 * @version 4.0.0
193
	 * @return string
194
	 */
195
	public function get_icon() {
196
		$icons = $this->payment_icons();
197
198
		$icons_str = '';
199
200
		$icons_str .= $icons['bitcoin'];
201
202
		return apply_filters( 'woocommerce_gateway_icon', $icons_str, $this->id );
203
	}
204
205
	/**
206
	 * payment_scripts function.
207
	 *
208
	 * Outputs scripts used for stripe payment
209
	 *
210
	 * @access public
211
	 */
212
	public function payment_scripts() {
213
		if ( ! is_cart() && ! is_checkout() && ! isset( $_GET['pay_for_order'] ) && ! is_add_payment_method_page() ) {
214
			return;
215
		}
216
217
		wp_enqueue_style( 'stripe_paymentfonts' );
218
		wp_enqueue_script( 'woocommerce_stripe' );
219
	}
220
221
	/**
222
	 * Initialize Gateway Settings Form Fields.
223
	 */
224
	public function init_form_fields() {
225
		$this->form_fields = require( WC_STRIPE_PLUGIN_PATH . '/includes/admin/stripe-bitcoin-settings.php' );
226
	}
227
228
	/**
229
	 * Payment form on checkout page
230
	 */
231
	public function payment_fields() {
232
		$user                 = wp_get_current_user();
0 ignored issues
show
Unused Code introduced by
$user 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...
233
		$total                = WC()->cart->total;
234
235
		// If paying from order, we need to get total from order not cart.
236
		if ( isset( $_GET['pay_for_order'] ) && ! empty( $_GET['key'] ) ) {
237
			$order = wc_get_order( wc_get_order_id_by_order_key( wc_clean( $_GET['key'] ) ) );
238
			$total = $order->get_total();
239
		}
240
241
		if ( is_add_payment_method_page() ) {
242
			$pay_button_text = __( 'Add Payment', 'woocommerce-gateway-stripe' );
0 ignored issues
show
Unused Code introduced by
$pay_button_text 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...
243
			$total        = '';
244
		} else {
245
			$pay_button_text = '';
0 ignored issues
show
Unused Code introduced by
$pay_button_text 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...
246
		}
247
248
		echo '<div
249
			id="stripe-bitcoin-payment-data"
250
			data-amount="' . esc_attr( WC_Stripe_Helper::get_stripe_amount( $total ) ) . '"
251
			data-currency="' . esc_attr( strtolower( get_woocommerce_currency() ) ) . '">';
252
253
		if ( $this->description ) {
254
			echo apply_filters( 'wc_stripe_description', wpautop( wp_kses_post( $this->description ) ) );
255
		}
256
257
		echo '</div>';
258
	}
259
260
	/**
261
	 * Output for the order received page.
262
	 *
263
	 * @param int $order_id
264
	 */
265
	public function thankyou_page( $order_id ) {
266
		$this->get_instructions( $order_id );
267
	}
268
269
	/**
270
	 * Add content to the WC emails.
271
	 *
272
	 * @since 4.0.0
273
	 * @version 4.0.0
274
	 * @param WC_Order $order
275
	 * @param bool $sent_to_admin
276
	 * @param bool $plain_text
277
	 */
278
	public function email_instructions( $order, $sent_to_admin, $plain_text = false ) {
279
		$order_id = WC_Stripe_Helper::is_pre_30() ? $order->id : $order->get_id();
280
281
		$payment_method = WC_Stripe_Helper::is_pre_30() ? $order->payment_method : $order->get_payment_method();
282
283
		if ( ! $sent_to_admin && 'stripe_bitcoin' === $payment_method && $order->has_status( 'on-hold' ) ) {
284
			$this->get_instructions( $order_id, $plain_text );
285
		}
286
	}
287
288
	/**
289
	 * Gets the Bitcoin instructions for customer to pay.
290
	 *
291
	 * @since 4.0.0
292
	 * @version 4.0.0
293
	 * @param int $order_id
294
	 */
295
	public function get_instructions( $order_id, $plain_text = false ) {
296
		$data = get_post_meta( $order_id, '_stripe_bitcoin', true );
297
298
		if ( $plain_text ) {
299
			esc_html_e( 'Please pay the following:', 'woocommerce-gateway-stripe' ) . "\n\n";
300
			echo "=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\n\n";
301
			esc_html_e( 'Bitcoin Amount:', 'woocommerce-gateway-stripe' ) . "\n\n";
302
			echo $data['amount'] . "\n\n";
303
			echo "=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\n\n";
304
			esc_html_e( 'Receiver:', 'woocommerce-gateway-stripe' ) . "\n\n";
305
			echo $data['address'] . "\n\n";
306
			echo "=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\n\n";
307
			esc_html_e( 'URI:', 'woocommerce-gateway-stripe' ) . "\n\n";
308
			echo $data['uri'] . "\n\n";
309
		} else {
310
			?>
311
			<h3><?php esc_html_e( 'Please pay the following:', 'woocommerce-gateway-stripe' ); ?></h3>
312
			<ul class="woocommerce-order-overview woocommerce-thankyou-order-details order_details">
313
			<li class="woocommerce-order-overview__order order">
314
				<?php esc_html_e( 'Bitcoin Amount:', 'woocommerce-gateway-stripe' ); ?>
315
				<strong><?php echo $data['amount']; ?></strong>
316
			</li>
317
			<li class="woocommerce-order-overview__order order">
318
				<?php esc_html_e( 'Receiver:', 'woocommerce-gateway-stripe' ); ?>
319
				<strong><?php echo $data['address']; ?></strong>
320
			</li>
321
			<li class="woocommerce-order-overview__order order">
322
				<?php esc_html_e( 'URI:', 'woocommerce-gateway-stripe' ); ?>
323
				<strong>
324
				<?php
325
				/* translators: link */
326
				printf( __( '<a href="%s">Pay Bitcoin</a>', 'woocommerce-gateway-stripe' ), $data['uri'] );
327
				?>
328
				</strong>
329
			</li>
330
			</ul>
331
			<?php
332
		}
333
	}
334
335
	/**
336
	 * Saves Bitcoin information to the order meta for later use.
337
	 *
338
	 * @since 4.0.0
339
	 * @version 4.0.0
340
	 * @param object $order
341
	 * @param object $source_object
342
	 */
343
	public function save_instructions( $order, $source_object ) {
344
		$data = array(
345
			'amount'  => $source_object->bitcoin->amount,
346
			'address' => $source_object->bitcoin->address,
347
			'uri'     => $source_object->bitcoin->uri,
348
		);
349
350
		$order_id = WC_Stripe_Helper::is_pre_30() ? $order->id : $order->get_id();
351
352
		update_post_meta( $order_id, '_stripe_bitcoin', $data );
353
	}
354
355
	/**
356
	 * Process the payment
357
	 *
358
	 * @param int  $order_id Reference.
359
	 * @param bool $retry Should we retry on fail.
360
	 * @param bool $force_save_source Force save the payment source.
361
	 *
362
	 * @throws Exception If payment will not be accepted.
363
	 *
364
	 * @return array|void
365
	 */
366
	public function process_payment( $order_id, $retry = true, $force_save_source = false ) {
367
		try {
368
			$order = wc_get_order( $order_id );
369
			$source_object = ! empty( $_POST['stripe_source'] ) ? json_decode( stripslashes( $_POST['stripe_source'] ) ) : false;
370
371
			// This comes from the create account checkbox in the checkout page.
372
			$create_account = ! empty( $_POST['createaccount'] ) ? true : false;
373
374
			if ( $create_account ) {
375
				$new_customer_id     = WC_Stripe_Helper::is_pre_30() ? $order->customer_user : $order->get_customer_id();
376
				$new_stripe_customer = new WC_Stripe_Customer( $new_customer_id );
377
				$new_stripe_customer->create_customer();
378
			}
379
380
			$prepared_source = $this->prepare_source( get_current_user_id(), $force_save_source );
381
382
			if ( empty( $prepared_source->source ) ) {
383
				$error_msg = __( 'Payment processing failed. Please retry.', 'woocommerce-gateway-stripe' );
384
				throw new Exception( $error_msg );
385
			}
386
387
			// Store source to order meta.
388
			$this->save_source( $order, $prepared_source );
389
390
391
			// This will throw exception if not valid.
392
			$this->validate_minimum_order_amount( $order );
393
394
			$this->save_instructions( $order, $source_object );
395
396
			// Mark as on-hold (we're awaiting the payment)
397
			$order->update_status( 'on-hold', __( 'Awaiting Bitcoin payment', 'woocommerce-gateway-stripe' ) );
398
399
			wc_reduce_stock_levels( $order_id );
400
401
			// Remove cart
402
			WC()->cart->empty_cart();
403
404
			// Return thankyou redirect
405
			return array(
406
				'result'    => 'success',
407
				'redirect'  => $this->get_return_url( $order ),
408
			);
409
		} catch ( Exception $e ) {
410
			wc_add_notice( $e->getMessage(), 'error' );
411
			WC_Stripe_Logger::log( 'Error: ' . $e->getMessage() );
412
413
			do_action( 'wc_gateway_stripe_process_payment_error', $e, $order );
414
415
			if ( $order->has_status( array( 'pending', 'failed' ) ) ) {
416
				$this->send_failed_order_email( $order_id );
417
			}
418
419
			return array(
420
				'result'   => 'fail',
421
				'redirect' => '',
422
			);
423
		}
424
	}
425
}
426