USPSShipmentBase.php in Commerce USPS 8
File
src/USPSShipmentBase.php
View source
<?php
namespace Drupal\commerce_usps;
use Drupal\commerce_shipping\Entity\ShipmentInterface;
use Drupal\commerce_usps\Event\USPSEvents;
use Drupal\commerce_usps\Event\USPSShipmentEvent;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use USPS\RatePackage;
class USPSShipmentBase implements USPSShipmentInterface {
protected $eventDispatcher;
protected $commerceShipment;
protected $uspsPackage;
protected $configuration;
public function __construct(EventDispatcherInterface $event_dispatcher) {
$this->eventDispatcher = $event_dispatcher;
}
public function setConfig(array $configuration) {
$this->configuration = $configuration;
}
public function getPackage(ShipmentInterface $commerce_shipment) {
$this->commerceShipment = $commerce_shipment;
$this
->buildPackage($commerce_shipment);
$this
->alterPackage();
return $this->uspsPackage;
}
public function alterPackage() {
$shipment_event = new USPSShipmentEvent($this->uspsPackage, $this->commerceShipment);
$this->eventDispatcher
->dispatch(USPSEvents::AFTER_BUILD_SHIPMENT, $shipment_event);
}
public function buildPackage() {
$this->uspsPackage = new RatePackage();
return $this->uspsPackage;
}
public function setDimensions() {
$package_type = $this
->getPackageType();
if (!empty($package_type)) {
$length = ceil($package_type
->getLength()
->convert('in')
->getNumber());
$width = ceil($package_type
->getWidth()
->convert('in')
->getNumber());
$height = ceil($package_type
->getHeight()
->convert('in')
->getNumber());
$size = $length > 12 || $width > 12 || $height > 12 ? 'LARGE' : 'REGULAR';
$this->uspsPackage
->setField('Size', $size);
$this->uspsPackage
->setField('Width', $width);
$this->uspsPackage
->setField('Length', $length);
$this->uspsPackage
->setField('Height', $height);
$this->uspsPackage
->setField('Girth', 0);
}
}
protected function setWeight() {
$weight = $this->commerceShipment
->getWeight();
if ($weight
->getNumber() > 0) {
$ounces = ceil($weight
->convert('oz')
->getNumber());
$this->uspsPackage
->setPounds(floor($ounces / 16));
$this->uspsPackage
->setOunces($ounces % 16);
}
}
protected function getPackageType() {
if (!empty($this->commerceShipment
->getPackageType())) {
return $this->commerceShipment
->getPackageType();
}
}
}