From 3bed775f259ee42aead5a4a84b99746fa9256aff Mon Sep 17 00:00:00 2001 From: Anton5360 <72033639+Anton5360@users.noreply.github.com> Date: Thu, 26 Oct 2023 09:18:14 +0200 Subject: [PATCH] [3.x] Small code refactoring (#3982) * Remove extra else statements * Move exception handling logic to private method * Replace raw php logic by Collection wrap method * Fix phpcs fail Co-authored-by: Adrien Foulon <6115458+Tofandel@users.noreply.github.com> --------- Co-authored-by: Anton Mykhailovskyi Co-authored-by: Adrien Foulon <6115458+Tofandel@users.noreply.github.com> --- src/Imports/ModelManager.php | 41 ++++++++++++++++++------------------ 1 file changed, 20 insertions(+), 21 deletions(-) diff --git a/src/Imports/ModelManager.php b/src/Imports/ModelManager.php index 5a89379cd..c18df82c1 100644 --- a/src/Imports/ModelManager.php +++ b/src/Imports/ModelManager.php @@ -88,13 +88,7 @@ public function toModels(ToModel $import, array $attributes, $rowNumber = null): $import->rememberRowNumber($rowNumber); } - $model = $import->model($attributes); - - if (null !== $model) { - return \is_array($model) ? new Collection($model) : new Collection([$model]); - } - - return new Collection([]); + return Collection::wrap($import->model($attributes)); } /** @@ -119,15 +113,13 @@ private function massFlush(ToModel $import) $import->uniqueBy(), $import instanceof WithUpsertColumns ? $import->upsertColumns() : null ); - } else { - $model::query()->insert($models->toArray()); + + return; } + + $model::query()->insert($models->toArray()); } catch (Throwable $e) { - if ($import instanceof SkipsOnError) { - $import->onError($e); - } else { - throw $e; - } + $this->handleException($import, $e); } }); } @@ -148,15 +140,13 @@ private function singleFlush(ToModel $import) $import->uniqueBy(), $import instanceof WithUpsertColumns ? $import->upsertColumns() : null ); - } else { - $model->saveOrFail(); + + return; } + + $model->saveOrFail(); } catch (Throwable $e) { - if ($import instanceof SkipsOnError) { - $import->onError($e); - } else { - throw $e; - } + $this->handleException($import, $e); } }); }); @@ -212,4 +202,13 @@ private function rows(): Collection { return new Collection($this->rows); } + + private function handleException(ToModel $import, Throwable $e): void + { + if (!$import instanceof SkipsOnError) { + throw $e; + } + + $import->onError($e); + } }