Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
AbstractCarrierOnline.php
Go to the documentation of this file.
1 <?php
8 
14 
22 abstract class AbstractCarrierOnline extends AbstractCarrier
23 {
24  const USA_COUNTRY_ID = 'US';
25 
26  const PUERTORICO_COUNTRY_ID = 'PR';
27 
28  const GUAM_COUNTRY_ID = 'GU';
29 
30  const GUAM_REGION_CODE = 'GU';
31 
37  protected static $_quotesCache = [];
38 
44  protected $_activeFlag = 'active';
45 
51  protected $_directoryData = null;
52 
56  protected $_xmlElFactory;
57 
61  protected $_rateFactory;
62 
67 
71  protected $_trackFactory;
72 
77 
82 
86  protected $_regionFactory;
87 
91  protected $_countryFactory;
92 
96  protected $_currencyFactory;
97 
101  protected $stockRegistry;
102 
108  protected $_rawRequest = null;
109 
115  protected $xmlSecurity;
116 
137  public function __construct(
138  \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig,
139  \Magento\Quote\Model\Quote\Address\RateResult\ErrorFactory $rateErrorFactory,
140  \Psr\Log\LoggerInterface $logger,
142  \Magento\Shipping\Model\Simplexml\ElementFactory $xmlElFactory,
143  \Magento\Shipping\Model\Rate\ResultFactory $rateFactory,
144  \Magento\Quote\Model\Quote\Address\RateResult\MethodFactory $rateMethodFactory,
145  \Magento\Shipping\Model\Tracking\ResultFactory $trackFactory,
146  \Magento\Shipping\Model\Tracking\Result\ErrorFactory $trackErrorFactory,
147  \Magento\Shipping\Model\Tracking\Result\StatusFactory $trackStatusFactory,
148  \Magento\Directory\Model\RegionFactory $regionFactory,
149  \Magento\Directory\Model\CountryFactory $countryFactory,
150  \Magento\Directory\Model\CurrencyFactory $currencyFactory,
151  \Magento\Directory\Helper\Data $directoryData,
152  \Magento\CatalogInventory\Api\StockRegistryInterface $stockRegistry,
153  array $data = []
154  ) {
155  $this->_xmlElFactory = $xmlElFactory;
156  $this->_rateFactory = $rateFactory;
157  $this->_rateMethodFactory = $rateMethodFactory;
158  $this->_trackFactory = $trackFactory;
159  $this->_trackErrorFactory = $trackErrorFactory;
160  $this->_trackStatusFactory = $trackStatusFactory;
161  $this->_regionFactory = $regionFactory;
162  $this->_countryFactory = $countryFactory;
163  $this->_currencyFactory = $currencyFactory;
164  $this->_directoryData = $directoryData;
165  $this->stockRegistry = $stockRegistry;
166  parent::__construct($scopeConfig, $rateErrorFactory, $logger, $data);
167  $this->xmlSecurity = $xmlSecurity;
168  }
169 
177  public function setActiveFlag($code = 'active')
178  {
179  $this->_activeFlag = $code;
180 
181  return $this;
182  }
183 
189  public function getCarrierCode()
190  {
191  return isset($this->_code) ? $this->_code : null;
192  }
193 
201  public function getTrackingInfo($tracking)
202  {
203  $result = $this->getTracking($tracking);
204 
205  if ($result instanceof \Magento\Shipping\Model\Tracking\Result) {
206  $trackings = $result->getAllTrackings();
207  if ($trackings) {
208  return $trackings[0];
209  }
210  } elseif (is_string($result) && !empty($result)) {
211  return $result;
212  }
213 
214  return false;
215  }
216 
223  public function isTrackingAvailable()
224  {
225  return true;
226  }
227 
233  public function isCityRequired()
234  {
235  return true;
236  }
237 
244  public function isZipCodeRequired($countryId = null)
245  {
246  if ($countryId != null) {
247  return !$this->_directoryData->isZipCodeOptional($countryId);
248  }
249 
250  return true;
251  }
252 
258  public function isShippingLabelsAvailable()
259  {
260  return true;
261  }
262 
274  {
275  $items = [];
276  if ($request->getAllItems()) {
277  foreach ($request->getAllItems() as $item) {
278  /* @var $item \Magento\Quote\Model\Quote\Item */
279  if ($item->getProduct()->isVirtual() || $item->getParentItem()) {
280  // Don't process children here - we will process (or already have processed) them below
281  continue;
282  }
283 
284  if ($item->getHasChildren() && $item->isShipSeparately()) {
285  foreach ($item->getChildren() as $child) {
286  if (!$child->getFreeShipping() && !$child->getProduct()->isVirtual()) {
287  $items[] = $child;
288  }
289  }
290  } else {
291  // Ship together - count compound item as one solid
292  $items[] = $item;
293  }
294  }
295  }
296 
297  return $items;
298  }
299 
310  {
311  return $this->processAdditionalValidation($request);
312  }
313 
323  public function processAdditionalValidation(\Magento\Framework\DataObject $request)
324  {
325  //Skip by item validation if there is no items in request
326  if (!count($this->getAllItems($request))) {
327  return $this;
328  }
329 
330  $maxAllowedWeight = (double)$this->getConfigData('max_package_weight');
331  $errorMsg = '';
332  $configErrorMsg = $this->getConfigData('specificerrmsg');
333  $defaultErrorMsg = __('The shipping module is not available.');
334  $showMethod = $this->getConfigData('showmethod');
335 
337  foreach ($this->getAllItems($request) as $item) {
338  $product = $item->getProduct();
339  if ($product && $product->getId()) {
340  $weight = $product->getWeight();
341  $stockItemData = $this->stockRegistry->getStockItem(
342  $product->getId(),
343  $item->getStore()->getWebsiteId()
344  );
345  $doValidation = true;
346 
347  if ($stockItemData->getIsQtyDecimal() && $stockItemData->getIsDecimalDivided()) {
348  if ($stockItemData->getEnableQtyIncrements() && $stockItemData->getQtyIncrements()
349  ) {
350  $weight = $weight * $stockItemData->getQtyIncrements();
351  } else {
352  $doValidation = false;
353  }
354  } elseif ($stockItemData->getIsQtyDecimal() && !$stockItemData->getIsDecimalDivided()) {
355  $weight = $weight * $item->getQty();
356  }
357 
358  if ($doValidation && $weight > $maxAllowedWeight) {
359  $errorMsg = $configErrorMsg ? $configErrorMsg : $defaultErrorMsg;
360  break;
361  }
362  }
363  }
364 
365  if (!$errorMsg && !$request->getDestPostcode() && $this->isZipCodeRequired($request->getDestCountryId())) {
366  $errorMsg = __('This shipping method is not available. Please specify the zip code.');
367  }
368 
369  if ($errorMsg && $showMethod) {
370  $error = $this->_rateErrorFactory->create();
371  $error->setCarrier($this->_code);
372  $error->setCarrierTitle($this->getConfigData('title'));
373  $error->setErrorMessage($errorMsg);
374 
375  return $error;
376  } elseif ($errorMsg) {
377  return false;
378  }
379 
380  return $this;
381  }
382 
389  protected function _getQuotesCacheKey($requestParams)
390  {
391  if (is_array($requestParams)) {
392  $requestParams = implode(
393  ',',
394  array_merge([$this->getCarrierCode()], array_keys($requestParams), $requestParams)
395  );
396  }
397 
398  return crc32($requestParams);
399  }
400 
410  protected function _getCachedQuotes($requestParams)
411  {
412  $key = $this->_getQuotesCacheKey($requestParams);
413 
414  return isset(self::$_quotesCache[$key]) ? self::$_quotesCache[$key] : null;
415  }
416 
424  protected function _setCachedQuotes($requestParams, $response)
425  {
426  $key = $this->_getQuotesCacheKey($requestParams);
427  self::$_quotesCache[$key] = $response;
428 
429  return $this;
430  }
431 
438  protected function _prepareServiceName($name)
439  {
440  $name = html_entity_decode((string)$name);
441  $name = strip_tags(preg_replace('#&\w+;#', '', $name));
442 
443  return trim($name);
444  }
445 
453  protected function _prepareShipmentRequest(\Magento\Framework\DataObject $request)
454  {
455  $phonePattern = '/[\s\_\-\(\)]+/';
456  $phoneNumber = $request->getShipperContactPhoneNumber();
457  $phoneNumber = preg_replace($phonePattern, '', $phoneNumber);
458  $request->setShipperContactPhoneNumber($phoneNumber);
459  $phoneNumber = $request->getRecipientContactPhoneNumber();
460  $phoneNumber = preg_replace($phonePattern, '', $phoneNumber);
461  $request->setRecipientContactPhoneNumber($phoneNumber);
462  }
463 
471  public function requestToShipment($request)
472  {
473  $packages = $request->getPackages();
474  if (!is_array($packages) || !$packages) {
475  throw new LocalizedException(__('No packages for request'));
476  }
477  if ($request->getStoreId() != null) {
478  $this->setStore($request->getStoreId());
479  }
480  $data = [];
481  foreach ($packages as $packageId => $package) {
482  $request->setPackageId($packageId);
483  $request->setPackagingType($package['params']['container']);
484  $request->setPackageWeight($package['params']['weight']);
485  $request->setPackageParams(new \Magento\Framework\DataObject($package['params']));
486  $request->setPackageItems($package['items']);
487  $result = $this->_doShipmentRequest($request);
488 
489  if ($result->hasErrors()) {
490  $this->rollBack($data);
491  break;
492  } else {
493  $data[] = [
494  'tracking_number' => $result->getTrackingNumber(),
495  'label_content' => $result->getShippingLabelContent(),
496  ];
497  }
498  if (!isset($isFirstRequest)) {
499  $request->setMasterTrackingId($result->getTrackingNumber());
500  $isFirstRequest = false;
501  }
502  }
503 
504  $response = new \Magento\Framework\DataObject(['info' => $data]);
505  if ($result->getErrors()) {
506  $response->setErrors($result->getErrors());
507  }
508 
509  return $response;
510  }
511 
519  public function returnOfShipment($request)
520  {
521  $request->setIsReturn(true);
522  $packages = $request->getPackages();
523  if (!is_array($packages) || !$packages) {
524  throw new LocalizedException(__('No packages for request'));
525  }
526  if ($request->getStoreId() != null) {
527  $this->setStore($request->getStoreId());
528  }
529  $data = [];
530  foreach ($packages as $packageId => $package) {
531  $request->setPackageId($packageId);
532  $request->setPackagingType($package['params']['container']);
533  $request->setPackageWeight($package['params']['weight']);
534  $request->setPackageParams(new \Magento\Framework\DataObject($package['params']));
535  $request->setPackageItems($package['items']);
536  $result = $this->_doShipmentRequest($request);
537 
538  if ($result->hasErrors()) {
539  $this->rollBack($data);
540  break;
541  } else {
542  $data[] = [
543  'tracking_number' => $result->getTrackingNumber(),
544  'label_content' => $result->getShippingLabelContent(),
545  ];
546  }
547  if (!isset($isFirstRequest)) {
548  $request->setMasterTrackingId($result->getTrackingNumber());
549  $isFirstRequest = false;
550  }
551  }
552 
553  $response = new \Magento\Framework\DataObject(['info' => $data]);
554  if ($result->getErrors()) {
555  $response->setErrors($result->getErrors());
556  }
557 
558  return $response;
559  }
560 
572  public function rollBack($data)
573  {
574  return true;
575  }
576 
583  abstract protected function _doShipmentRequest(\Magento\Framework\DataObject $request);
584 
591  protected function _isUSCountry($countyId)
592  {
593  switch ($countyId) {
594  case 'AS':
595  // Samoa American
596  case 'GU':
597  // Guam
598  case 'MP':
599  // Northern Mariana Islands
600  case 'PW':
601  // Palau
602  case 'PR':
603  // Puerto Rico
604  case 'VI':
605  // Virgin Islands US
606  case 'US':
607  // United States
608  return true;
609  }
610 
611  return false;
612  }
613 
623  public function isGirthAllowed($countyDest = null, $carrierMethodCode = null)
624  {
625  return false;
626  }
627 
633  public function setRawRequest($request)
634  {
635  $this->_rawRequest = $request;
636 
637  return $this;
638  }
639 
648  public function getMethodPrice($cost, $method = '')
649  {
650  return $method == $this->getConfigData(
651  $this->_freeMethod
652  ) && $this->getConfigFlag(
653  'free_shipping_enable'
654  ) && $this->getConfigData(
655  'free_shipping_subtotal'
656  ) <= $this->_rawRequest->getBaseSubtotalInclTax() ? '0.00' : $this->getFinalPriceWithHandlingFee(
657  $cost
658  );
659  }
660 
671  public function parseXml($xmlContent, $customSimplexml = 'SimpleXMLElement')
672  {
673  if (!$this->xmlSecurity->scan($xmlContent)) {
674  throw new LocalizedException(__('The security validation of the XML document has failed.'));
675  }
676 
677  $xmlElement = simplexml_load_string($xmlContent, $customSimplexml);
678 
679  return $xmlElement;
680  }
681 
686  public function canCollectRates()
687  {
688  return (bool)$this->getConfigFlag($this->_activeFlag);
689  }
690 
697  protected function debugErrors($errors)
698  {
699  if ($this->getConfigData('showmethod')) {
700  /* @var $error Error */
701  $this->_debug($errors);
702  }
703  }
704 
710  protected function getErrorMessage()
711  {
712  if ($this->getConfigData('showmethod')) {
713  /* @var $error Error */
714  $error = $this->_rateErrorFactory->create();
715  $error->setCarrier($this->getCarrierCode());
716  $error->setCarrierTitle($this->getConfigData('title'));
717  $error->setErrorMessage($this->getConfigData('specificerrmsg'));
718  return $error;
719  } else {
720  return false;
721  }
722  }
723 }
_prepareShipmentRequest(\Magento\Framework\DataObject $request)
$response
Definition: 404.php:11
elseif(isset( $params[ 'redirect_parent']))
Definition: iframe.phtml:17
__()
Definition: __.php:13
$logger
isGirthAllowed($countyDest=null, $carrierMethodCode=null)
parseXml($xmlContent, $customSimplexml='SimpleXMLElement')
$method
Definition: info.phtml:13
__construct(\Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig, \Magento\Quote\Model\Quote\Address\RateResult\ErrorFactory $rateErrorFactory, \Psr\Log\LoggerInterface $logger, Security $xmlSecurity, \Magento\Shipping\Model\Simplexml\ElementFactory $xmlElFactory, \Magento\Shipping\Model\Rate\ResultFactory $rateFactory, \Magento\Quote\Model\Quote\Address\RateResult\MethodFactory $rateMethodFactory, \Magento\Shipping\Model\Tracking\ResultFactory $trackFactory, \Magento\Shipping\Model\Tracking\Result\ErrorFactory $trackErrorFactory, \Magento\Shipping\Model\Tracking\Result\StatusFactory $trackStatusFactory, \Magento\Directory\Model\RegionFactory $regionFactory, \Magento\Directory\Model\CountryFactory $countryFactory, \Magento\Directory\Model\CurrencyFactory $currencyFactory, \Magento\Directory\Helper\Data $directoryData, \Magento\CatalogInventory\Api\StockRegistryInterface $stockRegistry, array $data=[])
processAdditionalValidation(\Magento\Framework\DataObject $request)
_doShipmentRequest(\Magento\Framework\DataObject $request)
proccessAdditionalValidation(\Magento\Framework\DataObject $request)
$errors
Definition: overview.phtml:9
$code
Definition: info.phtml:12
$items
if(!isset($_GET['name'])) $name
Definition: log.php:14