Last active
March 19, 2019 19:01
-
-
Save andyg5000/869959f2ca70f7be466faf910ea3955a to your computer and use it in GitHub Desktop.
Commerce USPS Event Subcriber Example. Dimensional weights are automatically applied by the USPS Webtools API, but this file provides a solid example of how to manipluate the package array before a rate request is made. Make sure to register your event subscribers
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Be sure to register this in your MYMODULE.services.yml file. | |
* | |
* MYMODULE_dimensional_weigth.rate_subscriber: | |
* class: Drupal\MYMODULE\EventSubscriber\DimensionalWeightSubscriber | |
* tags: | |
* - { name: event_subscriber } | |
*/ | |
namespace Drupal\commerce_usps\EventSubscriber; | |
use Drupal\commerce_usps\Event\USPSEvents; | |
use Drupal\commerce_usps\Event\USPSRateRequestEvent; | |
use Symfony\Component\EventDispatcher\EventSubscriberInterface; | |
/** | |
* Class DimensionalWeightSubscriber. | |
* | |
* @package Drupal\commerce_usps\EventSubscriber | |
*/ | |
class DimensionalWeightSubscriber implements EventSubscriberInterface { | |
/** | |
* The minimum volume to trip dimensional weight. | |
*/ | |
const DIMENSIONAL_WEIGHT_MIN_VOLUME = 1725; | |
/** | |
* The dimensional weight divisor. | |
*/ | |
const DIMENSIONAL_WEIGHT_DIVISOR = 166; | |
/** | |
* {@inheritdoc} | |
*/ | |
public static function getSubscribedEvents() { | |
return [ | |
USPSEvents::BEFORE_RATE_REQUEST => ['dimensionalWeight'], | |
]; | |
} | |
/** | |
* Alter the rate for dimensional rate requests. | |
* | |
* @param \Drupal\commerce_usps\Event\USPSRateRequestEvent $event | |
* The rate event. | |
*/ | |
public function dimensionalWeight(USPSRateRequestEvent $event) { | |
/** @var \Drupal\commerce_usps\USPS\USPSRate $rate_request */ | |
$rate_request = $event->getRateRequest(); | |
foreach ($rate_request->getPackages() as $delta => $package) { | |
$volume = ($package['Length'] * $package['Width'] * $package['Height']); | |
if ($volume > self::DIMENSIONAL_WEIGHT_MIN_VOLUME) { | |
$dimensional_weight = ceil($volume / self::DIMENSIONAL_WEIGHT_DIVISOR); | |
$rate_request->setPackageValue($delta, 'Pounds', $dimensional_weight); | |
$rate_request->setPackageValue($delta, 'Ounces', 0); | |
} | |
} | |
$event->setRateRequest($rate_request); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment