1
0
Fork 0
mirror of https://github.com/archtechx/tenancy.git synced 2026-02-05 17:14:03 +00:00
tenancy/src/Resolvers/Contracts/CachedTenantResolver.php
Abrar Ahmad 97ab483173
Completing PR #881 (#902)
* install PHP CS Fixer

* Fix styling

* remove StyleCI config

* use config from archtechx/template

* Fix styling

* added `php-cs-fixer`

* Update .php-cs-fixer.php

* added GitHub token

* Update ci.yml

* Update ci.yml

* Update ci.yml

* php-cs-fixer workflow same as template

Co-authored-by: Erik Gaal <me@erikgaal.nl>
Co-authored-by: erikgaal <erikgaal@users.noreply.github.com>
2022-07-20 15:28:45 +02:00

81 lines
1.9 KiB
PHP

<?php
declare(strict_types=1);
namespace Stancl\Tenancy\Resolvers\Contracts;
use Illuminate\Contracts\Cache\Factory;
use Illuminate\Contracts\Cache\Repository;
use Stancl\Tenancy\Contracts\Tenant;
use Stancl\Tenancy\Contracts\TenantResolver;
abstract class CachedTenantResolver implements TenantResolver
{
/** @var bool */
public static $shouldCache = false;
/** @var int */
public static $cacheTTL = 3600; // seconds
/** @var string|null */
public static $cacheStore = null; // default
/** @var Repository */
protected $cache;
public function __construct(Factory $cache)
{
$this->cache = $cache->store(static::$cacheStore);
}
public function resolve(...$args): Tenant
{
if (! static::$shouldCache) {
return $this->resolveWithoutCache(...$args);
}
$key = $this->getCacheKey(...$args);
if ($this->cache->has($key)) {
$tenant = $this->cache->get($key);
$this->resolved($tenant, ...$args);
return $tenant;
}
$tenant = $this->resolveWithoutCache(...$args);
$this->cache->put($key, $tenant, static::$cacheTTL);
return $tenant;
}
public function invalidateCache(Tenant $tenant): void
{
if (! static::$shouldCache) {
return;
}
foreach ($this->getArgsForTenant($tenant) as $args) {
$this->cache->forget($this->getCacheKey(...$args));
}
}
public function getCacheKey(...$args): string
{
return '_tenancy_resolver:' . static::class . ':' . json_encode($args);
}
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.
*
* @return array[]
*/
abstract public function getArgsForTenant(Tenant $tenant): array;
}