From b77bf9f1793770a9aea72a14c94cbfb08443b69b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=B8rgen=20Solli?= Date: Tue, 4 Aug 2020 18:12:28 +0200 Subject: [PATCH] Allows tenants to be initalized with their IDs (#473) * Allows tenants to be initalized with their IDs * Code style, note Co-authored-by: Samuel Stancl --- .../TenantCountNotBeIdentifiedById.php | 27 +++++++++++++++++++ src/Tenancy.php | 21 +++++++++++++-- 2 files changed, 46 insertions(+), 2 deletions(-) create mode 100644 src/Exceptions/TenantCountNotBeIdentifiedById.php diff --git a/src/Exceptions/TenantCountNotBeIdentifiedById.php b/src/Exceptions/TenantCountNotBeIdentifiedById.php new file mode 100644 index 00000000..28bde14c --- /dev/null +++ b/src/Exceptions/TenantCountNotBeIdentifiedById.php @@ -0,0 +1,27 @@ +setSolutionDescription('Are you sure the ID is correct and the tenant exists?') + ->setDocumentationLinks([ + 'Initializing Tenants' => 'https://tenancyforlaravel.com/docs/v3/tenants', + ]); + } +} diff --git a/src/Tenancy.php b/src/Tenancy.php index 60c4f306..9026bd1b 100644 --- a/src/Tenancy.php +++ b/src/Tenancy.php @@ -8,7 +8,7 @@ use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Model; use Illuminate\Support\Traits\Macroable; use Stancl\Tenancy\Contracts\TenancyBootstrapper; -use Stancl\Tenancy\Contracts\Tenant; +use Stancl\Tenancy\Exceptions\TenantCountNotBeIdentifiedById; class Tenancy { @@ -23,17 +23,34 @@ class Tenancy /** @var bool */ public $initialized = false; + /** + * Initializes the tenant + * @param Tenant|int|string $tenant + * @return void + */ public function initialize(Tenant $tenant): void { if ($this->initialized && $this->tenant->getTenantKey() === $tenant->getTenantKey()) { return; } + // TODO: Remove this (so that runForMultiple() is still performant) and make the FS bootstrapper work either way if ($this->initialized) { $this->end(); } - $this->tenant = $tenant; + if (is_object($tenant)) { + $this->tenant = $tenant; + } else { + $tenantId = $tenant; + $tenant = $this->find($tenantId); + + if (! $tenant) { + throw new TenantCountNotBeIdentifiedById($tenantId); + } + + $this->tenant = $tenant; + } event(new Events\InitializingTenancy($this));