Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix issue 632: cached lookup #633

Merged
merged 8 commits into from
Apr 16, 2021
Merged
10 changes: 9 additions & 1 deletion src/Resolvers/Contracts/CachedTenantResolver.php
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,11 @@ public function resolve(...$args): Tenant
$key = $this->getCacheKey(...$args);

if ($this->cache->has($key)) {
return $this->cache->get($key);
$tenant = $this->cache->get($key);

$this->resolved($tenant, ...$args);

return $tenant;
}

$tenant = $this->resolveWithoutCache(...$args);
Expand All @@ -64,6 +68,10 @@ public function getCacheKey(...$args): string

abstract public function resolveWithoutCache(...$args): Tenant;

public function resolved(Tenant $tenant, ...$args): void
{
}

/**
* Get all the arg combinations for resolve() that can be used to find this tenant.
*
Expand Down
28 changes: 23 additions & 5 deletions src/Resolvers/DomainTenantResolver.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

namespace Stancl\Tenancy\Resolvers;

use Illuminate\Database\Eloquent\Builder;
use Stancl\Tenancy\Contracts\Domain;
use Stancl\Tenancy\Contracts\Tenant;
use Stancl\Tenancy\Exceptions\TenantCouldNotBeIdentifiedOnDomainException;
Expand All @@ -28,18 +29,35 @@ class DomainTenantResolver extends Contracts\CachedTenantResolver

public function resolveWithoutCache(...$args): Tenant
{
/** @var Domain $domain */
$domain = config('tenancy.domain_model')::where('domain', $args[0])->first();
$domain = $args[0];

if ($domain) {
static::$currentDomain = $domain;
/** @var Tenant|null $tenant */
$tenant = config('tenancy.tenant_model')::query()
->whereHas('domains', function (Builder $query) use ($domain) {
$query->where('domain', $domain);
})
->with('domains')
stancl marked this conversation as resolved.
Show resolved Hide resolved
->first();

return $domain->tenant;
if ($tenant) {
$this->setCurrentDomain($tenant, $domain);

return $tenant;
}

throw new TenantCouldNotBeIdentifiedOnDomainException($args[0]);
}

public function resolved(Tenant $tenant, ...$args): void
{
$this->setCurrentDomain($tenant, $args[0]);
}

protected function setCurrentDomain(Tenant $tenant, string $domain): void
{
static::$currentDomain = $tenant->domains->where('domain', $domain)->first();
}

public function getArgsForTenant(Tenant $tenant): array
{
$tenant->unsetRelation('domains');
Expand Down