Skip to content

Commit

Permalink
[3.x] Small code refactoring (SpartnerNL#3982)
Browse files Browse the repository at this point in the history
* 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 <[email protected]>

---------

Co-authored-by: Anton Mykhailovskyi <[email protected]>
Co-authored-by: Adrien Foulon <[email protected]>
  • Loading branch information
3 people authored Oct 26, 2023
1 parent 577bb26 commit 3bed775
Showing 1 changed file with 20 additions and 21 deletions.
41 changes: 20 additions & 21 deletions src/Imports/ModelManager.php
Original file line number Diff line number Diff line change
Expand Up @@ -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));
}

/**
Expand All @@ -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);
}
});
}
Expand All @@ -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);
}
});
});
Expand Down Expand Up @@ -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);
}
}

0 comments on commit 3bed775

Please sign in to comment.