-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathShipping.php
executable file
·142 lines (117 loc) · 3.08 KB
/
Shipping.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
<?php
namespace Webkul\Shipping;
use Illuminate\Support\Facades\Config;
use Webkul\Checkout\Facades\Cart;
/**
* Class Shipping.
*
*/
class Shipping
{
/**
* Rates
*
* @var array
*/
protected $rates = [];
/**
* Collects rate from available shipping methods
*
* @return array
*/
public function collectRates()
{
if (! $cart = Cart::getCart()) {
return false;
}
$this->removeAllShippingRates();
foreach (Config::get('carriers') as $shippingMethod) {
$object = new $shippingMethod['class'];
if ($rates = $object->calculate()) {
if (is_array($rates)) {
$this->rates = array_merge($this->rates, $rates);
} else {
$this->rates[] = $rates;
}
}
}
$this->saveAllShippingRates();
return [
'jump_to_section' => 'shipping',
'shippingMethods' => $this->getGroupedAllShippingRates(),
'html' => view('shop::checkout.onepage.shipping', ['shippingRateGroups' => $this->getGroupedAllShippingRates()])->render(),
];
}
/**
* Persist shipping rate to database
*
* @return void
*/
public function removeAllShippingRates()
{
if (! $cart = Cart::getCart()) {
return;
}
foreach ($cart->shipping_rates()->get() as $rate) {
$rate->delete();
}
}
/**
* Persist shipping rate to database
*
* @return void
*/
public function saveAllShippingRates()
{
if (! $cart = Cart::getCart()) {
return;
}
$shippingAddress = $cart->shipping_address;
if ($shippingAddress) {
foreach ($this->rates as $rate) {
$rate->cart_address_id = $shippingAddress->id;
$rate->save();
}
}
}
/**
* Returns shipping rates, grouped by shipping method
*
* @return void
*/
public function getGroupedAllShippingRates()
{
$rates = [];
foreach ($this->rates as $rate) {
if (! isset($rates[$rate->carrier])) {
$rates[$rate->carrier] = [
'carrier_title' => $rate->carrier_title,
'rates' => []
];
}
$rates[$rate->carrier]['rates'][] = $rate;
}
return $rates;
}
/**
* Returns active shipping methods
*
* @return array
*/
public function getShippingMethods()
{
$methods = [];
foreach (Config::get('carriers') as $shippingMethod) {
$object = new $shippingMethod['class'];
if (! $object->isAvailable()) {
continue;
}
$methods[] = [
'method' => $object->getCode(),
'method_title' => $object->getTitle(),
'description' => $object->getDescription()
];
}
return $methods;
}
}