OrderAssignSubscriber.php in Commerce Core 8.2
File
modules/payment/src/EventSubscriber/OrderAssignSubscriber.php
View source
<?php
namespace Drupal\commerce_payment\EventSubscriber;
use Drupal\commerce_order\AddressBookInterface;
use Drupal\commerce_order\Event\OrderAssignEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class OrderAssignSubscriber implements EventSubscriberInterface {
protected $addressBook;
public function __construct(AddressBookInterface $address_book) {
$this->addressBook = $address_book;
}
public static function getSubscribedEvents() {
$events = [
'commerce_order.order.assign' => 'onAssign',
];
return $events;
}
public function onAssign(OrderAssignEvent $event) {
$order = $event
->getOrder();
if ($order
->get('payment_method')
->isEmpty()) {
return;
}
$customer = $event
->getCustomer();
$payment_method = $order
->get('payment_method')->entity;
if ($payment_method && empty($payment_method
->getOwnerId())) {
$payment_method_profile = $payment_method
->getBillingProfile();
if ($payment_method_profile && $this->addressBook
->needsCopy($payment_method_profile)) {
$this->addressBook
->copy($payment_method_profile, $customer);
$billing_profile = $order
->getBillingProfile();
if ($payment_method_profile
->equalToProfile($billing_profile)) {
$billing_profile
->populateFromProfile($payment_method_profile, [
'data',
]);
$billing_profile
->save();
}
}
$payment_method
->setOwner($customer);
$payment_method
->save();
}
}
}