Test Failed
Push — develop ( 64bec5...308757 )
by Remco
03:59
created

Gateway::copy_customer_id_to_wp_user()   B

Complexity

Conditions 7
Paths 9

Size

Total Lines 38
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 56

Importance

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

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

622
			$customer_id = $this->get_customer_id_for_subscription( /** @scrutinizer ignore-type */ $payment->get_subscription() );
Loading history...
623
624
			if ( null !== $customer_id ) {
625
				$customer_ids[] = $customer_id;
626
			}
627
		}
628
629
		// Customer ID from WordPress user.
630
		$customer = $payment->get_customer();
631
632
		if ( null !== $customer ) {
633
			$user_id = $customer->get_user_id();
634
635
			if ( ! empty( $user_id ) ) {
636
				$user_customer_ids = $this->get_customer_ids_for_user( $user_id );
637
638
				$customer_ids = \array_merge( $customer_ids, $user_customer_ids );
639
			}
640
		}
641
642
		return $customer_ids;
643
	}
644
645
	/**
646
	 * Get Mollie customers for the specified WordPress user ID.
647
	 *
648
	 * @param int $user_id WordPress user ID.
649
	 * @return array<string>
650
	 */
651
	private function get_customer_ids_for_user( $user_id ) {
652
		$customer_query = new CustomerQuery(
653
			array(
654
				'user_id' => $user_id,
655
			)
656
		);
657
658
		$customers = $customer_query->get_customers();
659
660
		$customer_ids = wp_list_pluck( $customers, 'mollie_id' );
661
662
		return $customer_ids;
663
	}
664
665
	/**
666
	 * Get customer ID for subscription.
667
	 *
668
	 * @param Subscription $subscription Subscription.
669
	 * @return string|null
670
	 */
671
	private function get_customer_id_for_subscription( Subscription $subscription ) {
672
		$customer_id = $subscription->get_meta( 'mollie_customer_id' );
673
674
		if ( empty( $customer_id ) ) {
675
			// Try to get (legacy) customer ID from first payment.
676
			$first_payment = $subscription->get_first_payment();
677
678
			if ( null !== $first_payment ) {
679
				$customer_id = $first_payment->get_meta( 'mollie_customer_id' );
680
			}
681
		}
682
683
		if ( empty( $customer_id ) ) {
684
			return null;
685
		}
686
687
		return $customer_id;
688
	}
689
690
	/**
691
	 * Get first existing customer from customers list.
692
	 *
693
	 * @param array $customer_ids Customers.
694
	 * @return string|null
695
	 */
696
	private function get_first_existing_customer_id( $customer_ids ) {
697
		$customer_ids = \array_filter( $customer_ids );
698
699
		$customer_ids = \array_unique( $customer_ids );
700
701
		foreach ( $customer_ids as $customer_id ) {
702
			$customer = $this->client->get_customer( $customer_id );
703
704
			if ( null !== $customer ) {
705
				return $customer_id;
706
			}
707
		}
708
709
		return null;
710
	}
711
712
	/**
713
	 * Create customer for payment.
714
	 *
715
	 * @param Payment $payment Payment.
716
	 * @return string|null
717
	 * @throws Error Throws Error when Mollie error occurs.
718
	 */
719
	private function create_customer_for_payment( Payment $payment ) {
720
		$mollie_customer = new Customer();
721
		$mollie_customer->set_mode( $this->config->is_test_mode() ? 'test' : 'live' );
722
		$mollie_customer->set_email( $payment->get_email() );
723
724
		$pronamic_customer = $payment->get_customer();
725
726
		if ( null !== $pronamic_customer ) {
727
			// Name.
728
			$name = \strval( $pronamic_customer->get_name() );
729
730
			if ( '' !== $name ) {
731
				$mollie_customer->set_name( $name );
732
			}
733
734
			// Locale.
735
			$locale = $pronamic_customer->get_locale();
736
737
			if ( null !== $locale ) {
738
				$mollie_customer->set_locale( LocaleHelper::transform( $locale ) );
739
			}
740
		}
741
742
		// Try to get name from consumer bank details.
743
		$consumer_bank_details = $payment->get_consumer_bank_details();
744
745
		if ( null === $mollie_customer->get_name() && null !== $consumer_bank_details ) {
746
			$name = $consumer_bank_details->get_name();
747
748
			if ( null !== $name ) {
749
				$mollie_customer->set_name( $name );
750
			}
751
		}
752
753
		// Create customer.
754
		$mollie_customer = $this->client->create_customer( $mollie_customer );
755
756
		$customer_id = $this->customer_data_store->insert_customer( $mollie_customer );
0 ignored issues
show
Unused Code introduced by
The assignment to $customer_id is dead and can be removed.
Loading history...
757
758
		// Connect to user.
759
		$user = \get_user_by( 'id', $pronamic_customer->get_user_id() );
760
761
		if ( false !== $user ) {
762
			$this->customer_data_store->connect_mollie_customer_to_wp_user( $mollie_customer, $user );
763
		}
764
765
		// Store customer ID in subscription meta.
766
		$subscription = $payment->get_subscription();
767
768
		if ( null !== $subscription ) {
769
			$subscription->set_meta( 'mollie_customer_id', $mollie_customer->get_id() );
770
		}
771
772
		return $mollie_customer->get_id();
773
	}
774
775
	/**
776
	 * Copy Mollie customer ID from subscription meta to WordPress user meta.
777
	 *
778
	 * @param Payment $payment Payment.
779
	 * @return void
780
	 */
781
	public function copy_customer_id_to_wp_user( Payment $payment ) {
782
		if ( $this->config->id !== $payment->config_id ) {
783
			return;
784
		}
785
786
		// Customer.
787
		$customer = $payment->get_customer();
788
789
		if ( null === $customer ) {
790
			return;
791
		}
792
793
		// WordPress user.
794
		$user = \get_user_by( 'id', $customer->get_user_id() );
795
796
		if ( false !== $user ) {
797
			return;
798
		}
799
800
		/**
801
		 * Payment.
802
		 */
803
		$customer_id = $payment->get_meta( 'mollie_customer_id' );
804
805
		if ( ! empty( $customer_id ) ) {
806
			$this->customer_data_store->connect_mollie_customer_to_wp_user( new Customer( $customer_id ), $user );
0 ignored issues
show
Bug introduced by
$user of type false is incompatible with the type WP_User expected by parameter $user of Pronamic\WordPress\Pay\G...e_customer_to_wp_user(). ( Ignorable by Annotation )

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

806
			$this->customer_data_store->connect_mollie_customer_to_wp_user( new Customer( $customer_id ), /** @scrutinizer ignore-type */ $user );
Loading history...
807
		}
808
809
		/**
810
		 * Subscription.
811
		 */
812
		$subscription = $payment->get_subscription();
813
814
		if ( null !== $subscription ) {
815
			$customer_id = $subscription->get_meta( 'mollie_customer_id' );
816
817
			if ( ! empty( $customer_id ) ) {
818
				$this->customer_data_store->connect_mollie_customer_to_wp_user( new Customer( $customer_id ), $user );
819
			}
820
		}
821
	}
822
}
823