wyyl/beike/Services/ShippingMethodService.php

72 lines
2.5 KiB
PHP

<?php
/**
* ShippingMethodService.php
*
* @copyright 2022 beikeshop.com - All Rights Reserved
* @link https://beikeshop.com
* @author Edward Yang <yangjin@guangda.work>
* @created 2022-12-01 10:54:46
* @modified 2022-12-01 10:54:46
*/
namespace Beike\Services;
use Beike\Admin\Http\Resources\PluginResource;
use Beike\Models\Logistics;
use Beike\Repositories\PluginRepo;
use Beike\Shop\Services\CheckoutService;
use Illuminate\Support\Str;
class ShippingMethodService
{
/**
* 获取配送方式, 二维数组, 一个配送插件对应多个配送方式
*
* @param CheckoutService $checkout
* @return array
* @throws \Exception
*/
public static function getShippingMethods(CheckoutService $checkout): array
{
$shippingPlugins = PluginRepo::getShippingMethods();
$shippingMethods = [];
foreach ($shippingPlugins as $shippingPlugin) {
$plugin = $shippingPlugin->plugin;
$pluginCode = $shippingPlugin->code;
$pluginName = Str::studly($pluginCode);
$className = "Plugin\\{$pluginName}\\Bootstrap";
if (! method_exists($className, 'getQuotes')) {
throw new \Exception("请在插件 {$className} 实现方法: public function getQuotes(\$currentCart)");
}
$quotes = (new $className)->getQuotes($checkout, $plugin);
if ($quotes) {
$pluginResource = (new PluginResource($plugin))->jsonSerialize();
$shippingMethods[] = [
'is_logistics' => 0,
'code' => $pluginCode,
'name' => $pluginResource['name'],
'quotes' => $quotes,
];
}
}
// 获取根据收货地址 获取物流信息
$cart = $checkout->cart->toArray();
$address = $checkout->cart->guest_shipping_address ?? $checkout->cart->guest_payment_address ?? $cart['payment_address'] ?? $cart['shipping_address'];
if($address){
$logisticsList = Logistics::getAll($address['country_id']);
foreach($logisticsList as $logisticsItem){
$shippingMethods[] = [
'is_logistics' => 1,
'code' => $logisticsItem['id'],
'name' => $logisticsItem['name'],
'quotes' => $logisticsItem,
];
}
}
return $shippingMethods;
}
}