Skip to content

Commit

Permalink
refactor: Remove untestable and unnecessary code from belongs to many…
Browse files Browse the repository at this point in the history
… tenants observer
  • Loading branch information
ollieread committed Sep 24, 2024
1 parent c279530 commit 129daf5
Showing 1 changed file with 7 additions and 15 deletions.
22 changes: 7 additions & 15 deletions src/Database/Eloquent/Observers/BelongsToManyTenantsObserver.php
Original file line number Diff line number Diff line change
Expand Up @@ -34,19 +34,11 @@ private function doesModelAlreadyHaveATenant(Model $model, BelongsToMany $relati
$model->load($relation->getRelationName());
}

if ($model->relationLoaded($relation->getRelationName())) {
/** @var \Illuminate\Database\Eloquent\Collection<int, TenantModel>|null $relatedModels */
$relatedModels = $model->getRelation($relation->getRelationName());

if ($relatedModels === null) {
return false;
}

// If it's not empty, there are already tenants
return $relatedModels->isNotEmpty();
}
/** @var \Illuminate\Database\Eloquent\Collection<int, TenantModel> $relatedModels */
$relatedModels = $model->getRelation($relation->getRelationName());

return false;
// If it's not empty, there are already tenants
return $relatedModels->isNotEmpty();
}

/**
Expand Down Expand Up @@ -84,7 +76,7 @@ private function isTenantMismatched(Model $model, Tenant&Model $tenant, BelongsT
* @throws \Sprout\Exceptions\TenantMismatch
* @throws \Sprout\Exceptions\TenantMissing
*/
private function passesInitialChecks(Model $model, Tenancy $tenancy, BelongsToMany $relation): bool
private function passesInitialChecks(Model $model, Tenancy $tenancy, BelongsToMany $relation, bool $succeedOnMatch = false): bool
{
// If we don't have a current tenant, we may need to do something
if (! $tenancy->check()) {
Expand Down Expand Up @@ -126,7 +118,7 @@ private function passesInitialChecks(Model $model, Tenancy $tenancy, BelongsToMa
// tenant, so, we can assume that either the relation is already
// set in the model, or it doesn't need to be.
// Either way, we're finished here
return false;
return $succeedOnMatch;
}

return true;
Expand Down Expand Up @@ -200,7 +192,7 @@ public function retrieved(Model $model): void
$tenancy = $model->getTenancy();

// If the initial checks do not pass
if (! $this->passesInitialChecks($model, $tenancy, $relation)) {
if (! $this->passesInitialChecks($model, $tenancy, $relation, true)) {
// Just exit, an exception will have be thrown
return;
}
Expand Down

0 comments on commit 129daf5

Please sign in to comment.