首页 > 解决方案 > 使用集合重构状态?

问题描述

有没有办法重构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 );
    }
}

标签: phplaravel

解决方案


首先,您可以使用非常强大且非常有用的 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
    );
}

就是这样。根据您的要求调整您的代码。


推荐阅读