Passed
Push — develop ( b2e038...bdb56e )
by Remco
04:06
created

Gateway   F

Complexity

Total Complexity 95

Size/Duplication

Total Lines 571
Duplicated Lines 0 %

Test Coverage

Coverage 45.33%

Importance

Changes 40
Bugs 0 Features 0
Metric Value
eloc 237
dl 0
loc 571
ccs 97
cts 214
cp 0.4533
rs 2
c 40
b 0
f 0
wmc 95

11 Methods

Rating   Name   Duplication   Size   Complexity  
B get_available_payment_methods() 0 66 11
A __construct() 0 27 2
A get_issuers() 0 25 3
A update_wp_user_customer_id() 0 10 6
C get_customer_id_for_payment() 0 49 14
A copy_customer_id_to_wp_user() 0 31 6
A get_supported_payment_methods() 0 16 1
F start() 0 140 25
A get_customer_id_by_wp_user_id() 0 6 2
A get_webhook_url() 0 27 6
F update_status() 0 69 19

How to fix   Complexity   

Complex Class

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

1
<?php
2
/**
3
 * Mollie gateway.
4
 *
5
 * @author    Pronamic <[email protected]>
6
 * @copyright 2005-2020 Pronamic
7
 * @license   GPL-3.0-or-later
8
 * @package   Pronamic\WordPress\Pay
9
 */
10
11
namespace Pronamic\WordPress\Pay\Gateways\Mollie;
12
13
use DateInterval;
14
use Pronamic\WordPress\DateTime\DateTime;
15
use Pronamic\WordPress\Pay\Banks\BankAccountDetails;
16
use Pronamic\WordPress\Pay\Banks\BankTransferDetails;
17
use Pronamic\WordPress\Pay\Core\Gateway as Core_Gateway;
18
use Pronamic\WordPress\Pay\Core\PaymentMethods;
19
use Pronamic\WordPress\Pay\Core\Recurring as Core_Recurring;
20
use Pronamic\WordPress\Pay\Payments\PaymentStatus;
21
use Pronamic\WordPress\Pay\Payments\Payment;
22
23
/**
24
 * Title: Mollie
25
 * Description:
26
 * Copyright: 2005-2020 Pronamic
27
 * Company: Pronamic
28
 *
29
 * @author  Remco Tolsma
30
 * @version 2.0.9
31
 * @since   1.1.0
32
 */
33
class Gateway extends Core_Gateway {
34
	/**
35
	 * Client.
36
	 *
37
	 * @var Client
38
	 */
39
	protected $client;
40
41
	/**
42
	 * Meta key for customer ID.
43
	 *
44
	 * @var string
45
	 */
46
	private $meta_key_customer_id = '_pronamic_pay_mollie_customer_id';
47
48
	/**
49
	 * Constructs and initializes an Mollie gateway
50
	 *
51
	 * @param Config $config Config.
52
	 */
53 39
	public function __construct( Config $config ) {
54 39
		parent::__construct( $config );
55
56 39
		$this->set_method( self::METHOD_HTTP_REDIRECT );
57
58
		// Supported features.
59 39
		$this->supports = array(
60
			'payment_status_request',
61
			'recurring_direct_debit',
62
			'recurring_credit_card',
63
			'recurring',
64
			'webhook',
65
			'webhook_log',
66
			'webhook_no_config',
67
		);
68
69
		// Client.
70 39
		$this->client = new Client( \strval( $config->api_key ) );
71 39
		$this->client->set_mode( $config->mode );
72
73
		// Mollie customer ID meta key.
74 39
		if ( self::MODE_TEST === $config->mode ) {
75 38
			$this->meta_key_customer_id = '_pronamic_pay_mollie_customer_id_test';
76
		}
77
78
		// Actions.
79 39
		add_action( 'pronamic_payment_status_update', array( $this, 'copy_customer_id_to_wp_user' ), 99, 1 );
80 39
	}
81
82
	/**
83
	 * Get issuers
84
	 *
85
	 * @see Core_Gateway::get_issuers()
86
	 */
87 3
	public function get_issuers() {
88 3
		$groups = array();
89
90
		try {
91 3
			$result = $this->client->get_issuers();
92
93
			$groups[] = array(
94
				'options' => $result,
95
			);
96 3
		} catch ( Error $e ) {
97
			// Catch Mollie error.
98 3
			$error = new \WP_Error(
99 3
				'mollie_error',
100 3
				sprintf( '%1$s (%2$s) - %3$s', $e->get_title(), $e->getCode(), $e->get_detail() )
101
			);
102
103 3
			$this->set_error( $error );
104
		} catch ( \Exception $e ) {
105
			// Catch exceptions.
106
			$error = new \WP_Error( 'mollie_error', $e->getMessage() );
107
108
			$this->set_error( $error );
109
		}
110
111 3
		return $groups;
112
	}
113
114
	/**
115
	 * Get available payment methods.
116
	 *
117
	 * @see Core_Gateway::get_available_payment_methods()
118
	 */
119 2
	public function get_available_payment_methods() {
120 2
		$payment_methods = array();
121
122
		// Set sequence types to get payment methods for.
123 2
		$sequence_types = array( Sequence::ONE_OFF, Sequence::RECURRING, Sequence::FIRST );
124
125 2
		$results = array();
126
127 2
		foreach ( $sequence_types as $sequence_type ) {
128
			// Get active payment methods for Mollie account.
129
			try {
130 2
				$result = $this->client->get_payment_methods( $sequence_type );
131 2
			} catch ( Error $e ) {
132
				// Catch Mollie error.
133
				$error = new \WP_Error(
134
					'mollie_error',
135
					sprintf( '%1$s (%2$s) - %3$s', $e->get_title(), $e->getCode(), $e->get_detail() )
136
				);
137
138
				$this->set_error( $error );
139
140
				break;
141 2
			} catch ( \Exception $e ) {
142
				// Catch exceptions.
143 2
				$error = new \WP_Error( 'mollie_error', $e->getMessage() );
144
145 2
				$this->set_error( $error );
146
147 2
				break;
148
			}
149
150 2
			if ( Sequence::FIRST === $sequence_type ) {
151
				foreach ( $result as $method => $title ) {
152
					unset( $result[ $method ] );
153
154
					// Get WordPress payment method for direct debit method.
155
					$method         = Methods::transform_gateway_method( $method );
156
					$payment_method = array_search( $method, PaymentMethods::get_recurring_methods(), true );
157
158
					if ( $payment_method ) {
159
						$results[ $payment_method ] = $title;
160
					}
161
				}
162
			}
163
164 2
			if ( is_array( $result ) ) {
165 2
				$results = array_merge( $results, $result );
166
			}
167
		}
168
169
		// Transform to WordPress payment methods.
170 2
		foreach ( $results as $method => $title ) {
171 2
			if ( PaymentMethods::is_recurring_method( $method ) ) {
172
				$payment_method = $method;
173
			} else {
174 2
				$payment_method = Methods::transform_gateway_method( $method );
175
			}
176
177 2
			if ( $payment_method ) {
178 2
				$payment_methods[] = $payment_method;
179
			}
180
		}
181
182 2
		$payment_methods = array_unique( $payment_methods );
183
184 2
		return $payment_methods;
185
	}
186
187
	/**
188
	 * Get supported payment methods
189
	 *
190
	 * @see Pronamic_WP_Pay_Gateway::get_supported_payment_methods()
191
	 * @return array<string>
192
	 */
193 2
	public function get_supported_payment_methods() {
194
		return array(
195 2
			PaymentMethods::BANCONTACT,
196
			PaymentMethods::BANK_TRANSFER,
197
			PaymentMethods::BELFIUS,
198
			PaymentMethods::CREDIT_CARD,
199
			PaymentMethods::DIRECT_DEBIT,
200
			PaymentMethods::DIRECT_DEBIT_BANCONTACT,
201
			PaymentMethods::DIRECT_DEBIT_IDEAL,
202
			PaymentMethods::DIRECT_DEBIT_SOFORT,
203
			PaymentMethods::EPS,
204
			PaymentMethods::GIROPAY,
205
			PaymentMethods::IDEAL,
206
			PaymentMethods::KBC,
207
			PaymentMethods::PAYPAL,
208
			PaymentMethods::SOFORT,
209
		);
210
	}
211
212
	/**
213
	 * Get webhook URL for Mollie.
214
	 *
215
	 * @return string|null
216
	 */
217 4
	public function get_webhook_url() {
218 4
		$url = home_url( '/' );
219
220 4
		$host = wp_parse_url( $url, PHP_URL_HOST );
221
222 4
		if ( is_array( $host ) ) {
223
			// Parsing failure.
224
			$host = '';
225
		}
226
227 4
		if ( 'localhost' === $host ) {
228
			// Mollie doesn't allow localhost.
229 1
			return null;
230 3
		} elseif ( '.dev' === substr( $host, -4 ) ) {
231
			// Mollie doesn't allow the .dev TLD.
232 1
			return null;
233 2
		} elseif ( '.local' === substr( $host, -6 ) ) {
234
			// Mollie doesn't allow the .local TLD.
235 1
			return null;
236 1
		} elseif ( '.test' === substr( $host, -5 ) ) {
237
			// Mollie doesn't allow the .test TLD.
238
			return null;
239
		}
240
241 1
		$url = add_query_arg( 'mollie_webhook', '', $url );
242
243 1
		return $url;
244
	}
245
246
	/**
247
	 * Start
248
	 *
249
	 * @see Pronamic_WP_Pay_Gateway::start()
250
	 * @param Payment $payment Payment.
251
	 * @return void
252
	 */
253
	public function start( Payment $payment ) {
254
		$request = new PaymentRequest(
255
			AmountTransformer::transform( $payment->get_total_amount() ),
256
			\strval( $payment->get_description() )
257
		);
258
259
		$request->redirect_url = $payment->get_return_url();
260
		$request->webhook_url  = $this->get_webhook_url();
261
262
		// Locale.
263
		$customer = $payment->get_customer();
264
265
		if ( null !== $customer ) {
266
			$request->locale = LocaleHelper::transform( $customer->get_locale() );
267
		}
268
269
		// Customer ID.
270
		$customer_id = $this->get_customer_id_for_payment( $payment );
271
272
		if ( is_string( $customer_id ) && ! empty( $customer_id ) ) {
273
			$request->customer_id = $customer_id;
274
		}
275
276
		// Payment method.
277
		$payment_method = $payment->get_method();
278
279
		// Recurring payment method.
280
		$is_recurring_method = ( $payment->get_subscription() && PaymentMethods::is_recurring_method( $payment_method ) );
281
282
		if ( false === $is_recurring_method ) {
283
			// Always use 'direct debit mandate via iDEAL/Bancontact/Sofort' payment methods as recurring method.
284
			$is_recurring_method = PaymentMethods::is_direct_debit_method( $payment_method );
285
		}
286
287
		if ( $is_recurring_method ) {
288
			$request->sequence_type = $payment->get_recurring() ? Sequence::RECURRING : Sequence::FIRST;
289
290
			if ( Sequence::FIRST === $request->sequence_type ) {
291
				$payment_method = PaymentMethods::get_first_payment_method( $payment_method );
292
			}
293
294
			if ( Sequence::RECURRING === $request->sequence_type ) {
295
				$payment->set_action_url( $payment->get_return_url() );
296
			}
297
		}
298
299
		// Leap of faith if the WordPress payment method could not transform to a Mollie method?
300
		$request->method = Methods::transform( $payment_method, $payment_method );
301
302
		// Issuer.
303
		if ( Methods::IDEAL === $request->method ) {
304
			$request->issuer = $payment->get_issuer();
305
		}
306
307
		// Due date.
308
		try {
309
			$due_date = new DateTime( sprintf( '+%s days', $this->config->due_date_days ) );
310
		} catch ( \Exception $e ) {
311
			$due_date = null;
312
		}
313
314
		$request->set_due_date( $due_date );
315
316
		// Create payment.
317
		$result = $this->client->create_payment( $request );
318
319
		// Set transaction ID.
320
		if ( isset( $result->id ) ) {
321
			$payment->set_transaction_id( $result->id );
322
		}
323
324
		// Set expiry date.
325
		/* phpcs:disable WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase */
326
		if ( isset( $result->expiresAt ) ) {
327
			try {
328
				$expires_at = new DateTime( $result->expiresAt );
329
			} catch ( \Exception $e ) {
330
				$expires_at = null;
331
			}
332
333
			$payment->set_expiry_date( $expires_at );
334
		}
335
		/* phpcs:enable WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase */
336
337
		// Set status.
338
		if ( isset( $result->status ) ) {
339
			$payment->set_status( Statuses::transform( $result->status ) );
340
		}
341
342
		// Set bank transfer recipient details.
343
		if ( isset( $result->details ) ) {
344
			$bank_transfer_recipient_details = $payment->get_bank_transfer_recipient_details();
345
346
			if ( null === $bank_transfer_recipient_details ) {
347
				$bank_transfer_recipient_details = new BankTransferDetails();
348
349
				$payment->set_bank_transfer_recipient_details( $bank_transfer_recipient_details );
350
			}
351
352
			$bank_details = $bank_transfer_recipient_details->get_bank_account();
353
354
			if ( null === $bank_details ) {
355
				$bank_details = new BankAccountDetails();
356
357
				$bank_transfer_recipient_details->set_bank_account( $bank_details );
358
			}
359
360
			$details = $result->details;
361
362
			/*
363
			 * @codingStandardsIgnoreStart
364
			 *
365
			 * Ignore coding standards because of sniff WordPress.NamingConventions.ValidVariableName.NotSnakeCaseMemberVar
366
			 */
367
			if ( isset( $details->bankName ) ) {
368
				/**
369
				 * Set `bankName` as bank details name, as result "Stichting Mollie Payments"
370
				 * is not the name of a bank, but the account holder name.
371
				 */
372
				$bank_details->set_name( $details->bankName );
373
			}
374
375
			if ( isset( $details->bankAccount ) ) {
376
				$bank_details->set_iban( $details->bankAccount );
377
			}
378
379
			if ( isset( $details->bankBic ) ) {
380
				$bank_details->set_bic( $details->bankBic );
381
			}
382
383
			if ( isset( $details->transferReference ) ) {
384
				$bank_transfer_recipient_details->set_reference( $details->transferReference );
385
			}
386
			// @codingStandardsIgnoreEnd
387
		}
388
389
		// Set action URL.
390
		if ( isset( $result->_links ) ) {
391
			if ( isset( $result->_links->checkout->href ) ) {
392
				$payment->set_action_url( $result->_links->checkout->href );
393
			}
394
		}
395
	}
396
397
	/**
398
	 * Update status of the specified payment
399
	 *
400
	 * @param Payment $payment Payment.
401
	 * @return void
402
	 */
403
	public function update_status( Payment $payment ) {
404
		$transaction_id = $payment->get_transaction_id();
405
406
		if ( null === $transaction_id ) {
407
			return;
408
		}
409
410
		$mollie_payment = $this->client->get_payment( $transaction_id );
411
412
		if ( isset( $mollie_payment->status ) ) {
413
			$payment->set_status( Statuses::transform( $mollie_payment->status ) );
414
		}
415
416
		if ( isset( $mollie_payment->details ) ) {
417
			$consumer_bank_details = $payment->get_consumer_bank_details();
418
419
			if ( null === $consumer_bank_details ) {
420
				$consumer_bank_details = new BankAccountDetails();
421
422
				$payment->set_consumer_bank_details( $consumer_bank_details );
423
			}
424
425
			$details = $mollie_payment->details;
426
427
			/*
428
			 * @codingStandardsIgnoreStart
429
			 *
430
			 * Ignore coding standards because of sniff WordPress.NamingConventions.ValidVariableName.NotSnakeCaseMemberVar
431
			 */
432
			if ( isset( $details->consumerName ) ) {
433
				$consumer_bank_details->set_name( $details->consumerName );
434
			}
435
436
			if ( isset( $details->cardHolder ) ) {
437
				$consumer_bank_details->set_name( $details->cardHolder );
438
			}
439
440
			if ( isset( $details->cardNumber ) ) {
441
				// The last four digits of the card number.
442
				$consumer_bank_details->set_account_number( $details->cardNumber );
443
			}
444
445
			if ( isset( $details->cardCountryCode ) ) {
446
				// The ISO 3166-1 alpha-2 country code of the country the card was issued in.
447
				$consumer_bank_details->set_country( $details->cardCountryCode );
448
			}
449
450
			if ( isset( $details->consumerAccount ) ) {
451
				switch ( $mollie_payment->method ) {
452
					case Methods::BELFIUS:
453
					case Methods::DIRECT_DEBIT:
454
					case Methods::IDEAL:
455
					case Methods::KBC:
456
					case Methods::SOFORT:
457
						$consumer_bank_details->set_iban( $details->consumerAccount );
458
459
						break;
460
					case Methods::BANCONTACT:
461
					case Methods::BANKTRANSFER:
462
					case Methods::PAYPAL:
463
					default:
464
						$consumer_bank_details->set_account_number( $details->consumerAccount );
465
466
						break;
467
				}
468
			}
469
470
			if ( isset( $details->consumerBic ) ) {
471
				$consumer_bank_details->set_bic( $details->consumerBic );
472
			}
473
			// @codingStandardsIgnoreEnd
474
		}
475
	}
476
477
	/**
478
	 * Get Mollie customer ID for payment.
479
	 *
480
	 * @param Payment $payment Payment.
481
	 * @return bool|string
482
	 */
483 10
	public function get_customer_id_for_payment( Payment $payment ) {
484 10
		$customer = $payment->get_customer();
485
486
		// Get WordPress user ID from payment customer.
487 10
		$user_id = ( null === $customer ? null : $customer->get_user_id() );
488
489
		// Get Mollie customer ID from user meta.
490 10
		$customer_id = $this->get_customer_id_by_wp_user_id( $user_id );
491
492 10
		$subscription = $payment->get_subscription();
493
494
		// Get customer ID from subscription meta.
495 10
		if ( $subscription ) {
496 10
			$subscription_customer_id = $subscription->get_meta( 'mollie_customer_id' );
497
498
			// Try to get (legacy) customer ID from first payment.
499 10
			if ( empty( $subscription_customer_id ) && $subscription->get_first_payment() ) {
500 7
				$first_payment = $subscription->get_first_payment();
501
502 7
				$subscription_customer_id = $first_payment->get_meta( 'mollie_customer_id' );
503
			}
504
505 10
			if ( ! empty( $subscription_customer_id ) ) {
506 4
				$customer_id = $subscription_customer_id;
507
			}
508
		}
509
510
		// Create new customer if the customer does not exist at Mollie.
511 10
		if ( ( empty( $customer_id ) || null === $this->client->get_customer( $customer_id ) ) && Core_Recurring::RECURRING !== $payment->recurring_type ) {
512
			$customer_name = null;
513
514
			if ( null !== $customer && null !== $customer->get_name() ) {
515
				$customer_name = strval( $customer->get_name() );
516
			}
517
518
			$customer_id = $this->client->create_customer( $payment->get_email(), $customer_name );
519
520
			$this->update_wp_user_customer_id( $user_id, $customer_id );
521
		}
522
523
		// Store customer ID in subscription meta.
524 10
		if ( $subscription && empty( $subscription_customer_id ) && ! empty( $customer_id ) ) {
525
			$subscription->set_meta( 'mollie_customer_id', $customer_id );
526
		}
527
528
		// Copy customer ID from subscription to user meta.
529 10
		$this->copy_customer_id_to_wp_user( $payment );
530
531 10
		return $customer_id;
532
	}
533
534
	/**
535
	 * Get Mollie customer ID by the specified WordPress user ID.
536
	 *
537
	 * @param int $user_id WordPress user ID.
538
	 * @return string|bool
539
	 */
540 27
	public function get_customer_id_by_wp_user_id( $user_id ) {
541 27
		if ( empty( $user_id ) ) {
542 11
			return false;
543
		}
544
545 16
		return get_user_meta( $user_id, $this->meta_key_customer_id, true );
546
	}
547
548
	/**
549
	 * Update Mollie customer ID meta for WordPress user.
550
	 *
551
	 * @param int    $user_id     WordPress user ID.
552
	 * @param string $customer_id Mollie Customer ID.
553
	 * @return bool
554
	 */
555 15
	private function update_wp_user_customer_id( $user_id, $customer_id ) {
556 15
		if ( empty( $user_id ) || is_bool( $user_id ) ) {
557 3
			return false;
558
		}
559
560 12
		if ( ! is_string( $customer_id ) || empty( $customer_id ) || 1 === strlen( $customer_id ) ) {
0 ignored issues
show
introduced by
The condition is_string($customer_id) is always true.
Loading history...
561 11
			return false;
562
		}
563
564 4
		update_user_meta( $user_id, $this->meta_key_customer_id, $customer_id );
565 4
	}
566
567
	/**
568
	 * Copy Mollie customer ID from subscription meta to WordPress user meta.
569
	 *
570
	 * @param Payment $payment Payment.
571
	 * @return void
572
	 */
573 27
	public function copy_customer_id_to_wp_user( Payment $payment ) {
574 27
		if ( $this->config->id !== $payment->config_id ) {
575 1
			return;
576
		}
577
578 26
		$subscription = $payment->get_subscription();
579
580 26
		if ( ! $subscription ) {
581
			return;
582
		}
583
584 26
		$customer = $subscription->get_customer();
585
586 26
		if ( null === $customer ) {
587 1
			return;
588
		}
589
590 25
		$user_id = $customer->get_user_id();
591
592 25
		if ( empty( $user_id ) ) {
593 10
			return;
594
		}
595
596
		// Get customer ID from subscription meta.
597 15
		$customer_id = $subscription->get_meta( 'mollie_customer_id' );
598
599 15
		$user_customer_id = $this->get_customer_id_by_wp_user_id( $user_id );
600
601 15
		if ( empty( $user_customer_id ) ) {
602
			// Set customer ID as user meta.
603 15
			$this->update_wp_user_customer_id( $user_id, (string) $customer_id );
604
		}
605 15
	}
606
}
607