WC_Gateway_Stripe_Multibanco   B
last analyzed

Complexity

Total Complexity 43

Size/Duplication

Total Lines 380
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 5

Importance

Changes 0
Metric Value
dl 0
loc 380
rs 8.96
c 0
b 0
f 0
wmc 43
lcom 1
cbo 5

13 Methods

Rating   Name   Duplication   Size   Complexity  
F __construct() 0 38 11
A get_supported_currency() 0 8 1
A is_available() 0 7 2
A payment_scripts() 0 8 5
A init_form_fields() 0 3 1
A get_icon() 0 9 2
A payment_fields() 0 30 5
A thankyou_page() 0 3 1
A get_instructions() 0 34 2
A email_instructions() 0 11 4
A save_instructions() 0 11 1
A create_source() 0 18 2
B process_payment() 0 60 6

How to fix   Complexity   

Complex Class

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

1
<?php
2
if ( ! defined( 'ABSPATH' ) ) {
3
	exit;
4
}
5
6
/**
7
 * Class that handles Multibanco payment method.
8
 *
9
 * @extends WC_Gateway_Stripe
10
 *
11
 * @since 4.1.0
12
 */
13
class WC_Gateway_Stripe_Multibanco 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
	 * Constructor
57
	 */
58
	public function __construct() {
59
		$this->id           = 'stripe_multibanco';
60
		$this->method_title = __( 'Stripe Multibanco', 'woocommerce-gateway-stripe' );
61
		/* translators: link */
62
		$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' ) );
63
		$this->supports           = array(
64
			'products',
65
			'refunds',
66
		);
67
68
		// Load the form fields.
69
		$this->init_form_fields();
70
71
		// Load the settings.
72
		$this->init_settings();
73
74
		$main_settings              = get_option( 'woocommerce_stripe_settings' );
75
		$this->title                = $this->get_option( 'title' );
76
		$this->description          = $this->get_option( 'description' );
77
		$this->enabled              = $this->get_option( 'enabled' );
78
		$this->testmode             = ( ! empty( $main_settings['testmode'] ) && 'yes' === $main_settings['testmode'] ) ? true : false;
79
		$this->saved_cards          = ( ! empty( $main_settings['saved_cards'] ) && 'yes' === $main_settings['saved_cards'] ) ? true : false;
80
		$this->publishable_key      = ! empty( $main_settings['publishable_key'] ) ? $main_settings['publishable_key'] : '';
81
		$this->secret_key           = ! empty( $main_settings['secret_key'] ) ? $main_settings['secret_key'] : '';
82
		$this->statement_descriptor = ! empty( $main_settings['statement_descriptor'] ) ? $main_settings['statement_descriptor'] : '';
83
84
		if ( $this->testmode ) {
85
			$this->publishable_key = ! empty( $main_settings['test_publishable_key'] ) ? $main_settings['test_publishable_key'] : '';
86
			$this->secret_key      = ! empty( $main_settings['test_secret_key'] ) ? $main_settings['test_secret_key'] : '';
87
		}
88
89
		add_action( 'woocommerce_update_options_payment_gateways_' . $this->id, array( $this, 'process_admin_options' ) );
90
		add_action( 'wp_enqueue_scripts', array( $this, 'payment_scripts' ) );
91
		add_action( 'woocommerce_thankyou_stripe_multibanco', array( $this, 'thankyou_page' ) );
92
93
		// Customer Emails
94
		add_action( 'woocommerce_email_before_order_table', array( $this, 'email_instructions' ), 10, 3 );
95
	}
96
97
	/**
98
	 * Returns all supported currencies for this payment method.
99
	 *
100
	 * @since 4.1.0
101
	 * @version 4.1.0
102
	 * @return array
103
	 */
104
	public function get_supported_currency() {
105
		return apply_filters(
106
			'wc_stripe_multibanco_supported_currencies',
107
			array(
108
				'EUR',
109
			)
110
		);
111
	}
112
113
	/**
114
	 * Checks to see if all criteria is met before showing payment method.
115
	 *
116
	 * @since 4.1.0
117
	 * @version 4.1.0
118
	 * @return bool
119
	 */
120
	public function is_available() {
121
		if ( ! in_array( get_woocommerce_currency(), $this->get_supported_currency() ) ) {
122
			return false;
123
		}
124
125
		return parent::is_available();
126
	}
127
128
	/**
129
	 * Get_icon function.
130
	 *
131
	 * @since 1.0.0
132
	 * @version 4.1.0
133
	 * @return string
134
	 */
135
	public function get_icon() {
136
		$icons = $this->payment_icons();
137
138
		$icons_str = '';
139
140
		$icons_str .= isset( $icons['multibanco'] ) ? $icons['multibanco'] : '';
141
142
		return apply_filters( 'woocommerce_gateway_icon', $icons_str, $this->id );
143
	}
144
145
	/**
146
	 * payment_scripts function.
147
	 *
148
	 * Outputs scripts used for stripe payment
149
	 *
150
	 * @access public
151
	 */
152
	public function payment_scripts() {
153
		if ( ! is_cart() && ! is_checkout() && ! isset( $_GET['pay_for_order'] ) && ! is_add_payment_method_page() ) {
154
			return;
155
		}
156
157
		wp_enqueue_style( 'stripe_styles' );
158
		wp_enqueue_script( 'woocommerce_stripe' );
159
	}
160
161
	/**
162
	 * Initialize Gateway Settings Form Fields.
163
	 */
164
	public function init_form_fields() {
165
		$this->form_fields = require( WC_STRIPE_PLUGIN_PATH . '/includes/admin/stripe-multibanco-settings.php' );
166
	}
167
168
	/**
169
	 * Payment form on checkout page
170
	 */
171
	public function payment_fields() {
172
		global $wp;
173
		$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...
174
		$total       = WC()->cart->total;
175
		$description = $this->get_description();
176
177
		// If paying from order, we need to get total from order not cart.
178
		if ( isset( $_GET['pay_for_order'] ) && ! empty( $_GET['key'] ) ) {
179
			$order = wc_get_order( wc_clean( $wp->query_vars['order-pay'] ) );
180
			$total = $order->get_total();
181
		}
182
183
		if ( is_add_payment_method_page() ) {
184
			$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...
185
			$total           = '';
186
		} else {
187
			$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...
188
		}
189
190
		echo '<div
191
			id="stripe-multibanco-payment-data"
192
			data-amount="' . esc_attr( WC_Stripe_Helper::get_stripe_amount( $total ) ) . '"
193
			data-currency="' . esc_attr( strtolower( get_woocommerce_currency() ) ) . '">';
194
195
		if ( $description ) {
196
			echo apply_filters( 'wc_stripe_description', wpautop( wp_kses_post( $description ) ), $this->id );
197
		}
198
199
		echo '</div>';
200
	}
201
202
	/**
203
	 * Output for the order received page.
204
	 *
205
	 * @param int $order_id
206
	 */
207
	public function thankyou_page( $order_id ) {
208
		$this->get_instructions( $order_id );
209
	}
210
211
	/**
212
	 * Add content to the WC emails.
213
	 *
214
	 * @since 4.1.0
215
	 * @version 4.1.0
216
	 * @param WC_Order $order
217
	 * @param bool $sent_to_admin
218
	 * @param bool $plain_text
219
	 */
220
	public function email_instructions( $order, $sent_to_admin, $plain_text = false ) {
221
		$order_id = $order->get_id();
222
223
		$payment_method = $order->get_payment_method();
224
225
		if ( ! $sent_to_admin && 'stripe_multibanco' === $payment_method && $order->has_status( 'on-hold' ) ) {
226
			WC_Stripe_Logger::log( 'Sending multibanco email for order #' . $order_id );
227
228
			$this->get_instructions( $order_id, $plain_text );
229
		}
230
	}
231
232
	/**
233
	 * Gets the Multibanco instructions for customer to pay.
234
	 *
235
	 * @since 4.1.0
236
	 * @version 4.1.0
237
	 * @param int $order_id
238
	 */
239
	public function get_instructions( $order_id, $plain_text = false ) {
240
		$data = get_post_meta( $order_id, '_stripe_multibanco', true );
241
242
		if ( $plain_text ) {
243
			esc_html_e( 'MULTIBANCO INFORMAÇÕES DE ENCOMENDA:', 'woocommerce-gateway-stripe' ) . "\n\n";
244
			echo "=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\n\n";
245
			esc_html_e( 'Montante:', 'woocommerce-gateway-stripe' ) . "\n\n";
246
			echo $data['amount'] . "\n\n";
247
			echo "=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\n\n";
248
			esc_html_e( 'Entidade:', 'woocommerce-gateway-stripe' ) . "\n\n";
249
			echo $data['entity'] . "\n\n";
250
			echo "=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\n\n";
251
			esc_html_e( 'Referencia:', 'woocommerce-gateway-stripe' ) . "\n\n";
252
			echo $data['reference'] . "\n\n";
253
		} else {
254
			?>
255
			<h3><?php esc_html_e( 'MULTIBANCO INFORMAÇÕES DE ENCOMENDA:', 'woocommerce-gateway-stripe' ); ?></h3>
256
			<ul class="woocommerce-order-overview woocommerce-thankyou-order-details order_details">
257
			<li class="woocommerce-order-overview__order order">
258
				<?php esc_html_e( 'Montante:', 'woocommerce-gateway-stripe' ); ?>
259
				<strong><?php echo $data['amount']; ?></strong>
260
			</li>
261
			<li class="woocommerce-order-overview__order order">
262
				<?php esc_html_e( 'Entidade:', 'woocommerce-gateway-stripe' ); ?>
263
				<strong><?php echo $data['entity']; ?></strong>
264
			</li>
265
			<li class="woocommerce-order-overview__order order">
266
				<?php esc_html_e( 'Referencia:', 'woocommerce-gateway-stripe' ); ?>
267
				<strong><?php echo $data['reference']; ?></strong>
268
			</li>
269
			</ul>
270
			<?php
271
		}
272
	}
273
274
	/**
275
	 * Saves Multibanco information to the order meta for later use.
276
	 *
277
	 * @since 4.1.0
278
	 * @version 4.1.0
279
	 * @param object $order
280
	 * @param object $source_object
281
	 */
282
	public function save_instructions( $order, $source_object ) {
283
		$data = array(
284
			'amount'    => $order->get_formatted_order_total(),
285
			'entity'    => $source_object->multibanco->entity,
286
			'reference' => $source_object->multibanco->reference,
287
		);
288
289
		$order_id = $order->get_id();
290
291
		update_post_meta( $order_id, '_stripe_multibanco', $data );
292
	}
293
294
	/**
295
	 * Creates the source for charge.
296
	 *
297
	 * @since 4.1.0
298
	 * @version 4.1.0
299
	 * @param object $order
300
	 * @return mixed
301
	 */
302
	public function create_source( $order ) {
303
		$currency              = $order->get_currency();
304
		$return_url            = $this->get_stripe_return_url( $order );
305
		$post_data             = array();
306
		$post_data['amount']   = WC_Stripe_Helper::get_stripe_amount( $order->get_total(), $currency );
307
		$post_data['currency'] = strtolower( $currency );
308
		$post_data['type']     = 'multibanco';
309
		$post_data['owner']    = $this->get_owner_details( $order );
310
		$post_data['redirect'] = array( 'return_url' => $return_url );
311
312
		if ( ! empty( $this->statement_descriptor ) ) {
313
			$post_data['statement_descriptor'] = WC_Stripe_Helper::clean_statement_descriptor( $this->statement_descriptor );
0 ignored issues
show
Documentation introduced by
$this->statement_descriptor is of type boolean, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
314
		}
315
316
		WC_Stripe_Logger::log( 'Info: Begin creating Multibanco source' );
317
318
		return WC_Stripe_API::request( $post_data, 'sources' );
319
	}
320
321
	/**
322
	 * Process the payment
323
	 *
324
	 * @param int  $order_id Reference.
325
	 * @param bool $retry Should we retry on fail.
326
	 * @param bool $force_save_source Force payment source to be saved.
327
	 *
328
	 * @throws Exception If payment will not be accepted.
329
	 *
330
	 * @return array|void
331
	 */
332
	public function process_payment( $order_id, $retry = true, $force_save_source = false ) {
333
		try {
334
			$order = wc_get_order( $order_id );
335
336
			// This will throw exception if not valid.
337
			$this->validate_minimum_order_amount( $order );
338
339
			// This comes from the create account checkbox in the checkout page.
340
			$create_account = ! empty( $_POST['createaccount'] ) ? true : false;
341
342
			if ( $create_account ) {
343
				$new_customer_id     = $order->get_customer_id();
344
				$new_stripe_customer = new WC_Stripe_Customer( $new_customer_id );
345
				$new_stripe_customer->create_customer();
346
			}
347
348
			$response = $this->create_source( $order );
349
350
			if ( ! empty( $response->error ) ) {
351
				$order->add_order_note( $response->error->message );
352
353
				throw new Exception( $response->error->message );
354
			}
355
356
			$order->update_meta_data( '_stripe_source_id', $response->id );
357
			$order->save();
358
359
			$this->save_instructions( $order, $response );
360
361
			// Mark as on-hold (we're awaiting the payment)
362
			$order->update_status( 'on-hold', __( 'Awaiting Multibanco payment', 'woocommerce-gateway-stripe' ) );
363
364
			// Reduce stock levels
365
			wc_reduce_stock_levels( $order_id );
366
367
			// Remove cart
368
			WC()->cart->empty_cart();
369
370
			WC_Stripe_Logger::log( 'Info: Redirecting to Multibanco...' );
371
372
			return array(
373
				'result'   => 'success',
374
				'redirect' => esc_url_raw( $response->redirect->url ),
375
			);
376
		} catch ( Exception $e ) {
377
			wc_add_notice( $e->getMessage(), 'error' );
378
			WC_Stripe_Logger::log( 'Error: ' . $e->getMessage() );
379
380
			do_action( 'wc_gateway_stripe_process_payment_error', $e, $order );
381
382
			if ( $order->has_status( array( 'pending', 'failed' ) ) ) {
383
				$this->send_failed_order_email( $order_id );
384
			}
385
386
			return array(
387
				'result'   => 'fail',
388
				'redirect' => '',
389
			);
390
		}
391
	}
392
}
393