ShippingOrderManager.php in Commerce Shipping 8.2
File
src/ShippingOrderManager.php
View source
<?php
namespace Drupal\commerce_shipping;
use Drupal\commerce_order\Entity\OrderInterface;
use Drupal\Core\Entity\EntityTypeBundleInfoInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\profile\Entity\ProfileInterface;
class ShippingOrderManager implements ShippingOrderManagerInterface {
protected $entityTypeManager;
protected $entityTypeBundleInfo;
protected $packerManager;
public function __construct(EntityTypeManagerInterface $entity_type_manager, EntityTypeBundleInfoInterface $entity_type_bundle_info, PackerManagerInterface $packer_manager) {
$this->entityTypeManager = $entity_type_manager;
$this->entityTypeBundleInfo = $entity_type_bundle_info;
$this->packerManager = $packer_manager;
}
public function createProfile(OrderInterface $order, array $values = []) {
$values += [
'type' => 'customer',
'uid' => 0,
];
$order_type_id = $order
->bundle();
$order_bundle_info = $this->entityTypeBundleInfo
->getBundleInfo('commerce_order');
if (!empty($order_bundle_info[$order_type_id]['shipping_profile_type'])) {
$values['type'] = $order_bundle_info[$order_type_id]['shipping_profile_type'];
}
$profile_storage = $this->entityTypeManager
->getStorage('profile');
return $profile_storage
->create($values);
}
public function getProfile(OrderInterface $order) {
$profiles = $order
->collectProfiles();
return isset($profiles['shipping']) ? $profiles['shipping'] : NULL;
}
public function hasShipments(OrderInterface $order) {
return $order
->hasField('shipments') && !$order
->get('shipments')
->isEmpty();
}
public function isShippable(OrderInterface $order) {
if (!$order
->hasField('shipments')) {
return FALSE;
}
foreach ($order
->getItems() as $order_item) {
$purchased_entity = $order_item
->getPurchasedEntity();
if ($purchased_entity && $purchased_entity
->hasField('weight')) {
return TRUE;
}
}
return FALSE;
}
public function pack(OrderInterface $order, ProfileInterface $profile = NULL) {
if (!$profile) {
$profile = $this
->getProfile($order) ?: $this
->createProfile($order);
}
$shipments = $order
->get('shipments')
->referencedEntities();
list($shipments, $removed_shipments) = $this->packerManager
->packToShipments($order, $profile, $shipments);
if (!empty($removed_shipments)) {
$shipment_storage = $this->entityTypeManager
->getStorage('commerce_shipment');
$shipment_storage
->delete($removed_shipments);
}
return $shipments;
}
}