php - 使用集合重构状态?
问题描述
有没有办法重构calculateState()
方法看起来更干净并可能使用 Laravel 集合?
它计算发货数量的结果状态,无库存退款数量和退货退款数量。
$this->dispatchedQty
如果是 Return ( "Code": "Return"
)它应该减少
输入Json:
$json = '{
"HistoryState": [
{
"Name": "Dispatched",
"Num": 3
},
{
"Name": "Refunding",
"Num": 1,
"Code": "NotInStock"
},
{
"Name": "Refunding",
"Num": 1,
"Code": "Return"
}
]
}';
$statusItem = new App\Services\State($json);
预期输出:
2 派遣
1 退款无库存
1 已退回
class State
{
protected $state;
protected $dispatchedQty = 0;
protected $refundNotInStockQty = 0;
protected $refundReturnQty = 0;
public function __construct($json)
{
$object = json_decode($json);
$this->state = $object->HistoryState;
$this->calculateState();
}
protected function calculateState()
{
foreach($this->state as $state) {
if ($state->Name == "Dispatched") {
$this->dispatchedQty+= $state->Num;
}
if ($state->Name == "Refunding") {
if ($state->Code == "NotInStock") {
$this->refundNotInStockQty += $state->Num;
} else {
$this->refundReturnQty += $state->Num;
$this->dispatchedQty -= $state->Num;
}
}
}
dd($this->dispatchedQty, $this->refundNotInStockQty, $this->refundReturnQty );
}
}
解决方案
首先,您可以使用非常强大且非常有用的 Laravel 集合。
您可以从 json 类型对象转换集合。
让我们一步一步开始。 第 1 步:让我们先处理构造函数。
public function __construct($json)
{
$object = json_decode($json);
//Convert it to collection
$this->state = collect($object->HistoryState);
$this->calculateState();
}
第 2 步:接下来重构您的 calculateState 方法。
protected function calculateState()
{
$stateGroupByName = $this->state->groupBy(["Name", "Code"]);
dd(
$stateGroupByName["Dispatched"]->first()->sum('Num'), //Total DispatchedQty
$stateGroupByName["Refunding"]["Return"]->sum('Num'), //Total ReturnedQty
$stateGroupByName["Refunding"]["NotInStock"]->sum('Num'), //Total Not instock
);
}
就是这样。根据您的要求调整您的代码。
推荐阅读
- python - Python:类内的函数范围
- apache - 使用 .htaccess 重定向 404 而不重定向尾部斜杠
- android - Android Volley JsonObjectRequest 超时,但显式 IP:端口请求有效
- react-native - 如何按月份和年份对数组进行分组 React Native
- nested - Protobuf-c:在消息中嵌套消息会创建一个结构指针
- reactjs - 对 api 进行异步调用不能通过 redux 操作进行
- node.js - 如果firebase中不存在,创建自定义令牌的方法将创建uid
- python - 如何获取两个列表之间普遍存在的键值?
- python - 并行迭代列表..帮助
- facebook - FB注销流程:如何撤销用户权限?