Skip to content

Commit

Permalink
Reinitialize tenancy for queued jobs if tenant id has changed (#276)
Browse files Browse the repository at this point in the history
* Reinitialize tenancy for queued jobs if tenant id has changed

* Refactor condition logic for better readability
  • Loading branch information
seanmtaylor authored Feb 22, 2020
1 parent 06ee1ff commit 5bb743f
Showing 1 changed file with 14 additions and 4 deletions.
18 changes: 14 additions & 4 deletions src/TenancyServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -109,11 +109,21 @@ public function boot(): void

// Queue tenancy
$this->app['events']->listen(\Illuminate\Queue\Events\JobProcessing::class, function ($event) {
if (array_key_exists('tenant_id', $event->job->payload())) {
if (! tenancy()->initialized) { // dispatchNow
tenancy()->initialize(tenancy()->find($event->job->payload()['tenant_id']));
}
$tenantId = $event->job->payload()['tenant_id'] ?? null;

// The job is not tenant-aware
if (! $tenantId) {
return;
}

// Tenancy is already initialized for the tenant (e.g. dispatchNow was used)
if (tenancy()->initialized && tenant('id') === $tenantId) {
return;
}

// Tenancy was either not initialized, or initialized for a different tenant.
// Therefore, we initialize it for the correct tenant.
tenancy()->initById($tenantId);
});
}
}

0 comments on commit 5bb743f

Please sign in to comment.