使用Collection重构状态?

时间:2018-09-18 21:30:33

标签: php laravel

是否有一种方法可以重构calculateState()方法,使其看起来更整洁并可能使用Laravel集合?

它计算派送数量的结局状态,没有存货时退还数量,退货时返还数量。

如果已返回($this->dispatchedQty),则应减少"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 );
    }
}

1 个答案:

答案 0 :(得分:0)

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

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