Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
FreeShipping.php
Go to the documentation of this file.
1 <?php
6 declare(strict_types=1);
7 
9 
11 use Magento\OfflineShipping\Model\SalesRule\ExtendedCalculator;
15 
17 {
21  protected $calculator;
22 
26  protected $storeManager;
27 
32  public function __construct(
35  ) {
36  $this->storeManager = $storeManager;
37  $this->calculator = $calculator;
38  }
39 
43  public function isFreeShipping(\Magento\Quote\Model\Quote $quote, $items)
44  {
46  if (!count($items)) {
47  return false;
48  }
49 
50  $result = false;
51  $addressFreeShipping = true;
52  $store = $this->storeManager->getStore($quote->getStoreId());
53  $this->calculator->init(
54  $store->getWebsiteId(),
55  $quote->getCustomerGroupId(),
56  $quote->getCouponCode()
57  );
58  $shippingAddress = $quote->getShippingAddress();
59  $shippingAddress->setFreeShipping(0);
61  foreach ($items as $item) {
62  if ($item->getNoDiscount()) {
63  $addressFreeShipping = false;
64  $item->setFreeShipping(false);
65  continue;
66  }
67 
69  if ($item->getParentItemId()) {
70  continue;
71  }
72 
73  $this->calculator->processFreeShipping($item);
74  // at least one item matches to the rule and the rule mode is not a strict
75  if ((bool)$item->getAddress()->getFreeShipping()) {
76  $result = true;
77  break;
78  }
79 
80  $itemFreeShipping = (bool)$item->getFreeShipping();
81  $addressFreeShipping = $addressFreeShipping && $itemFreeShipping;
82  $result = $addressFreeShipping;
83  }
84 
85  $shippingAddress->setFreeShipping((int)$result);
86  $this->applyToItems($items, $result);
87  return $result;
88  }
89 
95  protected function applyToChildren(\Magento\Quote\Model\Quote\Item\AbstractItem $item, $isFreeShipping)
96  {
97  if ($item->getHasChildren() && $item->isChildrenCalculated()) {
98  foreach ($item->getChildren() as $child) {
99  $this->calculator->processFreeShipping($child);
100  if ($isFreeShipping) {
101  $child->setFreeShipping($isFreeShipping);
102  }
103  }
104  }
105  }
106 
113  private function applyToItems(array $items, bool $freeShipping)
114  {
116  foreach ($items as $item) {
117  $item->getAddress()
118  ->setFreeShipping((int)$freeShipping);
119  $this->applyToChildren($item, $freeShipping);
120  }
121  }
122 }
$quote
$shippingAddress
Definition: order.php:40
applyToChildren(\Magento\Quote\Model\Quote\Item\AbstractItem $item, $isFreeShipping)
__construct(StoreManagerInterface $storeManager, Calculator $calculator)
isFreeShipping(\Magento\Quote\Model\Quote $quote, $items)
$items