TaxSubscriber.php in Commerce Shipping 8.2
File
src/EventSubscriber/TaxSubscriber.php
View source
<?php
namespace Drupal\commerce_shipping\EventSubscriber;
use Drupal\commerce_shipping\ShippingOrderManagerInterface;
use Drupal\commerce_tax\Event\CustomerProfileEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class TaxSubscriber implements EventSubscriberInterface {
protected $shippingOrderManager;
public function __construct(ShippingOrderManagerInterface $shipping_order_manager) {
$this->shippingOrderManager = $shipping_order_manager;
}
public static function getSubscribedEvents() {
return [
'commerce_tax.customer_profile' => [
'onCustomerProfile',
],
];
}
public function onCustomerProfile(CustomerProfileEvent $event) {
$order_item = $event
->getOrderItem();
$order = $order_item
->getOrder();
if (!$this->shippingOrderManager
->hasShipments($order)) {
return;
}
$shipments = $order
->get('shipments')
->referencedEntities();
$shipping_profiles = [];
foreach ($shipments as $shipment) {
$shipping_profile = $shipment
->getShippingProfile();
if ($shipping_profile) {
$shipping_profiles[$shipping_profile
->id()] = $shipping_profile;
}
}
if (count($shipping_profiles) < 2) {
return;
}
$customer_profile = $event
->getCustomerProfile();
foreach ($shipments as $shipment) {
foreach ($shipment
->getItems() as $shipment_item) {
if ($shipment_item
->getOrderItemId() == $order_item
->id()) {
$address_field = $shipment
->getShippingProfile()
->get('address');
$customer_profile
->set('address', $address_field
->getValue());
return;
}
}
}
}
}