0

I'm writing a project with Laravel.i have a loop with a lot of condition like this:

  foreach ($transactionsGroupBys as $transactionsGroupBy) {

        if ($this->checkExistSettlement($transactionsGroupBy, Carbon::today())) {
            $this->setErrorLog('This settlement has already been created', $transactionsGroupBy);
            continue;
        }

        try {

            if ($this->doChunk()) {

                $transactions = $this->getTransactions($transactionsGroupBy);
                $maxAmountSettle = $this->configRepository->find('transaction_chunk:PUBLIC')->value;
                $transactionChunk = app(ChunkTransaction::class)->chunk($transactions, $maxAmountSettle);

                foreach ($transactionChunk as $chunk) {
                    $transactionsIds = collect($chunk->transactions)->pluck('id')->toArray();
                    $settlements[] = $this->insertSettlement($chunk->transactions_group_by, $transactionsIds)->toArray();
                    $this->setInfoLog("Created $counter/$countSettlements settlement", $chunk->transactions_group_by);
                }

            } else {

                $transactions = $this->getTransactions($transactionsGroupBy, ['id']);
                $transactionsIds = $transactions ? collect($transactions)->pluck('id')->toArray() : [];

                $settlements[] = $this->insertSettlement($transactionsGroupBy, $transactionsIds)->toArray();
                $this->setInfoLog("Created $counter/$countSettlements settlement", $transactionsGroupBy);
            }

            $counter += 1;

        } catch (\Exception $exception) {
            $this->setErrorLog($exception->getMessage());
            continue;
        }

    }

i am checking $this->doChunk() and if true, run other loop. i feel this code is very Complicated and i have duplicated code. i need new pattern for Solve this problem.

1 Answers1

0

No, it's ok.

One point that can be corrected is - remove try {} catch {} block and rewrite it using Laravel ExceptionHandler.

Other way is split this method and put every branch in big if statement into separate methods, then rewrite if to thernary operator.

Also you can rewrite foreach with array_reduce to reduce the complexity of the code, in relation to "counter"