Extractor.php 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. <?php
  2. /**
  3. * Refer to LICENSE.txt distributed with the Temando Shipping module for notice of license
  4. */
  5. namespace Temando\Shipping\Model\Checkout\RateRequest;
  6. use Magento\Framework\Exception\LocalizedException;
  7. use Magento\Quote\Model\Quote\Address\RateRequest;
  8. /**
  9. * Temando Rate Request Utility.
  10. *
  11. * @package Temando\Shipping\Model
  12. * @author Christoph Aßmann <christoph.assmann@netresearch.de>
  13. * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
  14. * @link http://www.temando.com/
  15. */
  16. class Extractor
  17. {
  18. /**
  19. * Normalize rate request items. In rare cases they are not set at all.
  20. *
  21. * @param RateRequest $rateRequest
  22. * @return \Magento\Quote\Model\Quote\Item\AbstractItem[]
  23. */
  24. public function getItems(RateRequest $rateRequest)
  25. {
  26. if (!$rateRequest->getAllItems()) {
  27. return [];
  28. }
  29. return $rateRequest->getAllItems();
  30. }
  31. /**
  32. * Extract quote from rate request.
  33. *
  34. * @param RateRequest $rateRequest
  35. * @return \Magento\Quote\Api\Data\CartInterface|\Magento\Quote\Model\Quote
  36. * @throws LocalizedException
  37. */
  38. public function getQuote(RateRequest $rateRequest)
  39. {
  40. /** @var \Magento\Quote\Model\Quote\Item\AbstractItem[] $itemsToShip */
  41. $itemsToShip = $this->getItems($rateRequest);
  42. $currentItem = current($itemsToShip);
  43. if ($currentItem === false) {
  44. throw new LocalizedException(__('No items to ship found in rates request.'));
  45. }
  46. return $currentItem->getQuote();
  47. }
  48. /**
  49. * Extract shipping address from rate request.
  50. *
  51. * @param RateRequest $rateRequest
  52. * @return \Magento\Quote\Model\Quote\Address
  53. * @throws LocalizedException
  54. */
  55. public function getShippingAddress(RateRequest $rateRequest)
  56. {
  57. $itemsToShip = $this->getItems($rateRequest);
  58. $currentItem = current($itemsToShip);
  59. if ($currentItem === false) {
  60. throw new LocalizedException(__('No items to ship found in rates request.'));
  61. }
  62. return $currentItem->getAddress();
  63. }
  64. /**
  65. * Extract billing address from rate request.
  66. *
  67. * @param RateRequest $rateRequest
  68. * @return \Magento\Quote\Model\Quote\Address
  69. * @throws LocalizedException
  70. */
  71. public function getBillingAddress(RateRequest $rateRequest)
  72. {
  73. $quote = $this->getQuote($rateRequest);
  74. if (!$quote->getBillingAddress()->getCountryId()) {
  75. // billing address not selected yet, temporarily use shipping address.
  76. return $this->getShippingAddress($rateRequest);
  77. }
  78. return $quote->getBillingAddress();
  79. }
  80. }