mirror of
https://github.com/archtechx/tenancy.git
synced 2025-12-14 00:14:04 +00:00
Merge branch 'master' into storage-url-conflict-resolution
This commit is contained in:
commit
9206dafd28
109 changed files with 1147 additions and 754 deletions
|
|
@ -6,7 +6,7 @@ namespace Stancl\Tenancy\Bootstrappers;
|
|||
|
||||
use Stancl\Tenancy\Contracts\TenancyBootstrapper;
|
||||
use Stancl\Tenancy\Contracts\Tenant;
|
||||
use Stancl\Tenancy\Contracts\TenantWithDatabase;
|
||||
use Stancl\Tenancy\Database\Contracts\TenantWithDatabase;
|
||||
use Stancl\Tenancy\Database\DatabaseManager;
|
||||
use Stancl\Tenancy\Exceptions\TenantDatabaseDoesNotExistException;
|
||||
|
||||
|
|
|
|||
42
src/Bootstrappers/Integrations/ScoutTenancyBootstrapper.php
Normal file
42
src/Bootstrappers/Integrations/ScoutTenancyBootstrapper.php
Normal file
|
|
@ -0,0 +1,42 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Stancl\Tenancy\Bootstrappers\Integrations;
|
||||
|
||||
use Illuminate\Contracts\Config\Repository;
|
||||
use Stancl\Tenancy\Contracts\TenancyBootstrapper;
|
||||
use Stancl\Tenancy\Contracts\Tenant;
|
||||
|
||||
class ScoutTenancyBootstrapper implements TenancyBootstrapper
|
||||
{
|
||||
/** @var Repository */
|
||||
protected $config;
|
||||
|
||||
/** @var string */
|
||||
protected $originalScoutPrefix;
|
||||
|
||||
public function __construct(Repository $config)
|
||||
{
|
||||
$this->config = $config;
|
||||
}
|
||||
|
||||
public function bootstrap(Tenant $tenant)
|
||||
{
|
||||
if (! isset($this->originalScoutPrefix)) {
|
||||
$this->originalScoutPrefix = $this->config->get('scout.prefix');
|
||||
}
|
||||
|
||||
$this->config->set('scout.prefix', $this->getTenantPrefix($tenant));
|
||||
}
|
||||
|
||||
public function revert()
|
||||
{
|
||||
$this->config->set('scout.prefix', $this->originalScoutPrefix);
|
||||
}
|
||||
|
||||
protected function getTenantPrefix(Tenant $tenant): string
|
||||
{
|
||||
return (string) $tenant->getTenantKey();
|
||||
}
|
||||
}
|
||||
|
|
@ -6,6 +6,8 @@ namespace Stancl\Tenancy;
|
|||
|
||||
use Illuminate\Cache\CacheManager as BaseCacheManager;
|
||||
|
||||
// todo move to Cache namespace?
|
||||
|
||||
class CacheManager extends BaseCacheManager
|
||||
{
|
||||
/**
|
||||
|
|
@ -26,7 +28,7 @@ class CacheManager extends BaseCacheManager
|
|||
}
|
||||
|
||||
$names = $parameters[0];
|
||||
$names = (array) $names; // cache()->tags('foo') https://laravel.com/docs/5.7/cache#removing-tagged-cache-items
|
||||
$names = (array) $names; // cache()->tags('foo') https://laravel.com/docs/9.x/cache#removing-tagged-cache-items
|
||||
|
||||
return $this->store()->tags(array_merge($tags, $names));
|
||||
}
|
||||
|
|
|
|||
|
|
@ -5,6 +5,9 @@ declare(strict_types=1);
|
|||
namespace Stancl\Tenancy\Commands;
|
||||
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Contracts\Console\Kernel;
|
||||
use Symfony\Component\Console\Input\ArgvInput;
|
||||
use Symfony\Component\Console\Output\ConsoleOutput;
|
||||
|
||||
class Run extends Command
|
||||
{
|
||||
|
|
@ -20,36 +23,35 @@ class Run extends Command
|
|||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $signature = "tenants:run {commandname : The command's name.}
|
||||
{--tenants=* : The tenant(s) to run the command for. Default: all}
|
||||
{--argument=* : The arguments to pass to the command. Default: none}
|
||||
{--option=* : The options to pass to the command. Default: none}";
|
||||
protected $signature = 'tenants:run {commandname : The artisan command.}
|
||||
{--tenants=* : The tenant(s) to run the command for. Default: all}';
|
||||
|
||||
/**
|
||||
* Execute the console command.
|
||||
*/
|
||||
public function handle()
|
||||
{
|
||||
tenancy()->runForMultiple($this->option('tenants'), function ($tenant) {
|
||||
$argvInput = $this->ArgvInput();
|
||||
tenancy()->runForMultiple($this->option('tenants'), function ($tenant) use ($argvInput) {
|
||||
$this->line("Tenant: {$tenant->getTenantKey()}");
|
||||
|
||||
$callback = function ($prefix = '') {
|
||||
return function ($arguments, $argument) use ($prefix) {
|
||||
[$key, $value] = explode('=', $argument, 2);
|
||||
$arguments[$prefix . $key] = $value;
|
||||
|
||||
return $arguments;
|
||||
};
|
||||
};
|
||||
|
||||
// Turns ['foo=bar', 'abc=xyz=zzz'] into ['foo' => 'bar', 'abc' => 'xyz=zzz']
|
||||
$arguments = array_reduce($this->option('argument'), $callback(), []);
|
||||
|
||||
// Turns ['foo=bar', 'abc=xyz=zzz'] into ['--foo' => 'bar', '--abc' => 'xyz=zzz']
|
||||
$options = array_reduce($this->option('option'), $callback('--'), []);
|
||||
|
||||
// Run command
|
||||
$this->call($this->argument('commandname'), array_merge($arguments, $options));
|
||||
$this->getLaravel()
|
||||
->make(Kernel::class)
|
||||
->handle($argvInput, new ConsoleOutput);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Get command as ArgvInput instance.
|
||||
*/
|
||||
protected function ArgvInput(): ArgvInput
|
||||
{
|
||||
// Convert string command to array
|
||||
$subCommand = explode(' ', $this->argument('commandname'));
|
||||
|
||||
// Add "artisan" as first parameter because ArgvInput expects "artisan" as first parameter and later removes it
|
||||
array_unshift($subCommand, 'artisan');
|
||||
|
||||
return new ArgvInput($subCommand);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
72
src/Concerns/Debuggable.php
Normal file
72
src/Concerns/Debuggable.php
Normal file
|
|
@ -0,0 +1,72 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Stancl\Tenancy\Concerns;
|
||||
|
||||
use Closure;
|
||||
use Stancl\Tenancy\Enums\LogMode;
|
||||
use Stancl\Tenancy\Events\Contracts\TenancyEvent;
|
||||
use Stancl\Tenancy\Tenancy;
|
||||
|
||||
// todo finish this feature
|
||||
|
||||
/**
|
||||
* @mixin Tenancy
|
||||
*/
|
||||
trait Debuggable
|
||||
{
|
||||
protected LogMode $logMode = LogMode::NONE;
|
||||
protected array $eventLog = [];
|
||||
|
||||
public function log(LogMode $mode = LogMode::SILENT): static
|
||||
{
|
||||
$this->eventLog = [];
|
||||
$this->logMode = $mode;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function logMode(): LogMode
|
||||
{
|
||||
return $this->logMode;
|
||||
}
|
||||
|
||||
public function getLog(): array
|
||||
{
|
||||
return $this->eventLog;
|
||||
}
|
||||
|
||||
public function logEvent(TenancyEvent $event): static
|
||||
{
|
||||
$this->eventLog[] = ['time' => now(), 'event' => $event::class, 'tenant' => $this->tenant];
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function dump(Closure $dump = null): static
|
||||
{
|
||||
$dump ??= dd(...);
|
||||
|
||||
// Dump the log if we were already logging in silent mode
|
||||
// Otherwise start logging in instant mode
|
||||
match ($this->logMode) {
|
||||
LogMode::NONE => $this->log(LogMode::INSTANT),
|
||||
LogMode::SILENT => $dump($this->eventLog),
|
||||
LogMode::INSTANT => null,
|
||||
};
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function dd(Closure $dump = null): void
|
||||
{
|
||||
$dump ??= dd(...);
|
||||
|
||||
if ($this->logMode === LogMode::SILENT) {
|
||||
$dump($this->eventLog);
|
||||
} else {
|
||||
$dump($this);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -7,6 +7,8 @@ namespace Stancl\Tenancy\Contracts;
|
|||
use Illuminate\Database\Eloquent\Collection;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
|
||||
|
||||
// todo move all resource syncing-related things to a separate namespace?
|
||||
|
||||
/**
|
||||
* @property-read Tenant[]|Collection $tenants
|
||||
*/
|
||||
|
|
|
|||
|
|
@ -8,11 +8,11 @@ interface Syncable
|
|||
{
|
||||
public function getGlobalIdentifierKeyName(): string;
|
||||
|
||||
public function getGlobalIdentifierKey();
|
||||
public function getGlobalIdentifierKey(): string|int;
|
||||
|
||||
public function getCentralModelName(): string;
|
||||
|
||||
public function getSyncedAttributeNames(): array;
|
||||
|
||||
public function triggerSyncEvent();
|
||||
public function triggerSyncEvent(): void;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -4,11 +4,11 @@ declare(strict_types=1);
|
|||
|
||||
namespace Stancl\Tenancy\Contracts;
|
||||
|
||||
use Closure;
|
||||
|
||||
/**
|
||||
* @see \Stancl\Tenancy\Database\Models\Tenant
|
||||
*
|
||||
* @method __call(string $method, array $parameters) IDE support. This will be a model.
|
||||
* @method static __callStatic(string $method, array $parameters) IDE support. This will be a model.
|
||||
* @mixin \Illuminate\Database\Eloquent\Model
|
||||
*/
|
||||
interface Tenant
|
||||
|
|
@ -17,14 +17,14 @@ interface Tenant
|
|||
public function getTenantKeyName(): string;
|
||||
|
||||
/** Get the value of the key used for identifying the tenant. */
|
||||
public function getTenantKey();
|
||||
public function getTenantKey(): int|string;
|
||||
|
||||
/** Get the value of an internal key. */
|
||||
public function getInternal(string $key);
|
||||
public function getInternal(string $key): mixed;
|
||||
|
||||
/** Set the value of an internal key. */
|
||||
public function setInternal(string $key, $value);
|
||||
public function setInternal(string $key, mixed $value): static;
|
||||
|
||||
/** Run a callback in this tenant's environment. */
|
||||
public function run(callable $callback);
|
||||
public function run(Closure $callback): mixed;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -5,7 +5,49 @@ declare(strict_types=1);
|
|||
namespace Stancl\Tenancy\Contracts;
|
||||
|
||||
use Exception;
|
||||
use Spatie\Ignition\Contracts\BaseSolution;
|
||||
use Spatie\Ignition\Contracts\ProvidesSolution;
|
||||
|
||||
abstract class TenantCouldNotBeIdentifiedException extends Exception
|
||||
abstract class TenantCouldNotBeIdentifiedException extends Exception implements ProvidesSolution
|
||||
{
|
||||
/** Default solution title. */
|
||||
protected string $solutionTitle = 'Tenant could not be identified';
|
||||
|
||||
/** Default solution description. */
|
||||
protected string $solutionDescription = 'Are you sure this tenant exists?';
|
||||
|
||||
/** Set the message. */
|
||||
protected function tenantCouldNotBeIdentified(string $how): static
|
||||
{
|
||||
$this->message = 'Tenant could not be identified ' . $how;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/** Set the solution title. */
|
||||
protected function title(string $solutionTitle): static
|
||||
{
|
||||
$this->solutionTitle = $solutionTitle;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/** Set the solution description. */
|
||||
protected function description(string $solutionDescription): static
|
||||
{
|
||||
$this->solutionDescription = $solutionDescription;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/** Get the Ignition description. */
|
||||
public function getSolution(): BaseSolution
|
||||
{
|
||||
return BaseSolution::create($this->solutionTitle)
|
||||
->setSolutionDescription($this->solutionDescription)
|
||||
->setDocumentationLinks([
|
||||
'Tenants' => 'https://tenancyforlaravel.com/docs/v3/tenants',
|
||||
'Tenant Identification' => 'https://tenancyforlaravel.com/docs/v3/tenant-identification',
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -11,5 +11,5 @@ interface TenantResolver
|
|||
*
|
||||
* @throws TenantCouldNotBeIdentifiedException
|
||||
*/
|
||||
public function resolve(...$args): Tenant;
|
||||
public function resolve(mixed ...$args): Tenant;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,15 +0,0 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Stancl\Tenancy\Contracts;
|
||||
|
||||
use Stancl\Tenancy\DatabaseConfig;
|
||||
|
||||
interface TenantWithDatabase extends Tenant
|
||||
{
|
||||
public function database(): DatabaseConfig;
|
||||
|
||||
/** Get an internal key. */
|
||||
public function getInternal(string $key);
|
||||
}
|
||||
|
|
@ -4,22 +4,26 @@ declare(strict_types=1);
|
|||
|
||||
namespace Stancl\Tenancy\Controllers;
|
||||
|
||||
use Closure;
|
||||
use Illuminate\Routing\Controller;
|
||||
use Throwable;
|
||||
|
||||
class TenantAssetsController extends Controller
|
||||
{
|
||||
public static $tenancyMiddleware = 'Stancl\Tenancy\Middleware\InitializeTenancyByDomain';
|
||||
public static string|array|Closure $tenancyMiddleware = Stancl\Tenancy\Middleware\InitializeTenancyByDomain::class;
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
$this->middleware(static::$tenancyMiddleware);
|
||||
}
|
||||
|
||||
public function asset($path)
|
||||
public function asset(string $path = null)
|
||||
{
|
||||
abort_if($path === null, 404);
|
||||
|
||||
try {
|
||||
return response()->file(storage_path("app/public/$path"));
|
||||
} catch (\Throwable $th) {
|
||||
} catch (Throwable) {
|
||||
abort(404);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -10,7 +10,7 @@ trait BelongsToPrimaryModel
|
|||
{
|
||||
abstract public function getRelationshipToPrimaryModel(): string;
|
||||
|
||||
public static function bootBelongsToPrimaryModel()
|
||||
public static function bootBelongsToPrimaryModel(): void
|
||||
{
|
||||
static::addGlobalScope(new ParentModelScope);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -19,7 +19,7 @@ trait BelongsToTenant
|
|||
return $this->belongsTo(config('tenancy.tenant_model'), BelongsToTenant::$tenantIdColumn);
|
||||
}
|
||||
|
||||
public static function bootBelongsToTenant()
|
||||
public static function bootBelongsToTenant(): void
|
||||
{
|
||||
static::addGlobalScope(new TenantScope);
|
||||
|
||||
|
|
|
|||
|
|
@ -6,7 +6,7 @@ namespace Stancl\Tenancy\Database\Concerns;
|
|||
|
||||
trait ConvertsDomainsToLowercase
|
||||
{
|
||||
public static function bootConvertsDomainsToLowercase()
|
||||
public static function bootConvertsDomainsToLowercase(): void
|
||||
{
|
||||
static::saving(function ($model) {
|
||||
$model->domain = strtolower($model->domain);
|
||||
|
|
|
|||
|
|
@ -2,9 +2,9 @@
|
|||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Stancl\Tenancy\Concerns;
|
||||
namespace Stancl\Tenancy\Database\Concerns;
|
||||
|
||||
use Stancl\Tenancy\Contracts\TenantWithDatabase;
|
||||
use Stancl\Tenancy\Database\Contracts\TenantWithDatabase;
|
||||
|
||||
trait CreatesDatabaseUsers
|
||||
{
|
||||
|
|
@ -8,7 +8,7 @@ use Stancl\Tenancy\Exceptions\DomainOccupiedByOtherTenantException;
|
|||
|
||||
trait EnsuresDomainIsNotOccupied
|
||||
{
|
||||
public static function bootEnsuresDomainIsNotOccupied()
|
||||
public static function bootEnsuresDomainIsNotOccupied(): void
|
||||
{
|
||||
static::saving(function ($self) {
|
||||
if ($domain = $self->newQuery()->where('domain', $self->domain)->first()) {
|
||||
|
|
|
|||
|
|
@ -8,7 +8,7 @@ use Stancl\Tenancy\Contracts\UniqueIdentifierGenerator;
|
|||
|
||||
trait GeneratesIds
|
||||
{
|
||||
public static function bootGeneratesIds()
|
||||
public static function bootGeneratesIds(): void
|
||||
{
|
||||
static::creating(function (self $model) {
|
||||
if (! $model->getKey() && $model->shouldGenerateId()) {
|
||||
|
|
|
|||
|
|
@ -4,8 +4,8 @@ declare(strict_types=1);
|
|||
|
||||
namespace Stancl\Tenancy\Database\Concerns;
|
||||
|
||||
use Stancl\Tenancy\Contracts\TenantWithDatabase;
|
||||
use Stancl\Tenancy\DatabaseConfig;
|
||||
use Stancl\Tenancy\Database\Contracts\TenantWithDatabase;
|
||||
use Stancl\Tenancy\Database\DatabaseConfig;
|
||||
|
||||
trait HasDatabase
|
||||
{
|
||||
|
|
|
|||
|
|
@ -2,6 +2,8 @@
|
|||
|
||||
declare(strict_types=1);
|
||||
|
||||
// todo not sure if this should be in Database\
|
||||
|
||||
namespace Stancl\Tenancy\Database\Concerns;
|
||||
|
||||
use Stancl\Tenancy\Contracts\Domain;
|
||||
|
|
|
|||
|
|
@ -6,26 +6,20 @@ namespace Stancl\Tenancy\Database\Concerns;
|
|||
|
||||
trait HasInternalKeys
|
||||
{
|
||||
/**
|
||||
* Get the internal prefix.
|
||||
*/
|
||||
/** Get the internal prefix. */
|
||||
public static function internalPrefix(): string
|
||||
{
|
||||
return 'tenancy_';
|
||||
}
|
||||
|
||||
/**
|
||||
* Get an internal key.
|
||||
*/
|
||||
public function getInternal(string $key)
|
||||
/** Get an internal key. */
|
||||
public function getInternal(string $key): mixed
|
||||
{
|
||||
return $this->getAttribute(static::internalPrefix() . $key);
|
||||
}
|
||||
|
||||
/**
|
||||
* Set internal key.
|
||||
*/
|
||||
public function setInternal(string $key, $value)
|
||||
/** Set internal key. */
|
||||
public function setInternal(string $key, mixed $value): static
|
||||
{
|
||||
$this->setAttribute(static::internalPrefix() . $key, $value);
|
||||
|
||||
|
|
|
|||
|
|
@ -16,7 +16,7 @@ trait InvalidatesResolverCache
|
|||
Resolvers\RequestDataTenantResolver::class,
|
||||
];
|
||||
|
||||
public static function bootInvalidatesResolverCache()
|
||||
public static function bootInvalidatesResolverCache(): void
|
||||
{
|
||||
static::saved(function (Tenant $tenant) {
|
||||
foreach (static::$resolvers as $resolver) {
|
||||
|
|
|
|||
|
|
@ -19,7 +19,7 @@ trait InvalidatesTenantsResolverCache
|
|||
Resolvers\RequestDataTenantResolver::class,
|
||||
];
|
||||
|
||||
public static function bootInvalidatesTenantsResolverCache()
|
||||
public static function bootInvalidatesTenantsResolverCache(): void
|
||||
{
|
||||
static::saved(function (Model $model) {
|
||||
foreach (static::$resolvers as $resolver) {
|
||||
|
|
|
|||
|
|
@ -10,7 +10,7 @@ use Stancl\Tenancy\Events\SyncedResourceSaved;
|
|||
|
||||
trait ResourceSyncing
|
||||
{
|
||||
public static function bootResourceSyncing()
|
||||
public static function bootResourceSyncing(): void
|
||||
{
|
||||
static::saved(function (Syncable $model) {
|
||||
/** @var ResourceSyncing $model */
|
||||
|
|
@ -27,7 +27,7 @@ trait ResourceSyncing
|
|||
});
|
||||
}
|
||||
|
||||
public function triggerSyncEvent()
|
||||
public function triggerSyncEvent(): void
|
||||
{
|
||||
/** @var Syncable $this */
|
||||
event(new SyncedResourceSaved($this, tenant()));
|
||||
|
|
|
|||
|
|
@ -4,15 +4,17 @@ declare(strict_types=1);
|
|||
|
||||
namespace Stancl\Tenancy\Database\Concerns;
|
||||
|
||||
use Closure;
|
||||
use Stancl\Tenancy\Contracts\Tenant;
|
||||
|
||||
trait TenantRun
|
||||
{
|
||||
/**
|
||||
* Run a callback in this tenant's context.
|
||||
* Atomic, safely reverts to previous context.
|
||||
*
|
||||
* This method is atomic and safely reverts to the previous context.
|
||||
*/
|
||||
public function run(callable $callback)
|
||||
public function run(Closure $callback): mixed
|
||||
{
|
||||
/** @var Tenant $this */
|
||||
$originalTenant = tenant();
|
||||
|
|
|
|||
|
|
@ -2,15 +2,18 @@
|
|||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Stancl\Tenancy\Contracts;
|
||||
namespace Stancl\Tenancy\Database\Contracts;
|
||||
|
||||
use Stancl\Tenancy\DatabaseConfig;
|
||||
use Stancl\Tenancy\Database\DatabaseConfig;
|
||||
|
||||
interface ManagesDatabaseUsers extends TenantDatabaseManager
|
||||
{
|
||||
/** Create a database user. */
|
||||
public function createUser(DatabaseConfig $databaseConfig): bool;
|
||||
|
||||
/** Delete a database user. */
|
||||
public function deleteUser(DatabaseConfig $databaseConfig): bool;
|
||||
|
||||
/** Does a database user exist? */
|
||||
public function userExists(string $username): bool;
|
||||
}
|
||||
|
|
@ -2,30 +2,22 @@
|
|||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Stancl\Tenancy\Contracts;
|
||||
namespace Stancl\Tenancy\Database\Contracts;
|
||||
|
||||
use Stancl\Tenancy\Exceptions\NoConnectionSetException;
|
||||
use Stancl\Tenancy\Database\Exceptions\NoConnectionSetException;
|
||||
|
||||
interface TenantDatabaseManager
|
||||
{
|
||||
/**
|
||||
* Create a database.
|
||||
*/
|
||||
/** Create a database. */
|
||||
public function createDatabase(TenantWithDatabase $tenant): bool;
|
||||
|
||||
/**
|
||||
* Delete a database.
|
||||
*/
|
||||
/** Delete a database. */
|
||||
public function deleteDatabase(TenantWithDatabase $tenant): bool;
|
||||
|
||||
/**
|
||||
* Does a database exist.
|
||||
*/
|
||||
/** Does a database exist? */
|
||||
public function databaseExists(string $name): bool;
|
||||
|
||||
/**
|
||||
* Make a DB connection config array.
|
||||
*/
|
||||
/** Construct a DB connection config array. */
|
||||
public function makeConnectionConfig(array $baseConfig, string $databaseName): array;
|
||||
|
||||
/**
|
||||
13
src/Database/Contracts/TenantWithDatabase.php
Normal file
13
src/Database/Contracts/TenantWithDatabase.php
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Stancl\Tenancy\Database\Contracts;
|
||||
|
||||
use Stancl\Tenancy\Contracts\Tenant;
|
||||
use Stancl\Tenancy\Database\DatabaseConfig;
|
||||
|
||||
interface TenantWithDatabase extends Tenant
|
||||
{
|
||||
public function database(): DatabaseConfig;
|
||||
}
|
||||
|
|
@ -2,29 +2,27 @@
|
|||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Stancl\Tenancy;
|
||||
namespace Stancl\Tenancy\Database;
|
||||
|
||||
use Closure;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Support\Facades\Hash;
|
||||
use Illuminate\Support\Str;
|
||||
use Stancl\Tenancy\Contracts\ManagesDatabaseUsers;
|
||||
use Stancl\Tenancy\Contracts\TenantDatabaseManager;
|
||||
use Stancl\Tenancy\Contracts\TenantWithDatabase as Tenant;
|
||||
use Stancl\Tenancy\Exceptions\DatabaseManagerNotRegisteredException;
|
||||
use Stancl\Tenancy\Database\Contracts\TenantWithDatabase as Tenant;
|
||||
|
||||
class DatabaseConfig
|
||||
{
|
||||
/** @var Tenant|Model */
|
||||
public $tenant;
|
||||
/** The tenant whose database we're dealing with. */
|
||||
public Tenant&Model $tenant;
|
||||
|
||||
/** @var callable */
|
||||
public static $usernameGenerator;
|
||||
/** Database username generator (can be set by the developer.) */
|
||||
public static Closure|null $usernameGenerator = null;
|
||||
|
||||
/** @var callable */
|
||||
public static $passwordGenerator;
|
||||
/** Database password generator (can be set by the developer.) */
|
||||
public static Closure|null $passwordGenerator = null;
|
||||
|
||||
/** @var callable */
|
||||
public static $databaseNameGenerator;
|
||||
/** Database name generator (can be set by the developer.) */
|
||||
public static Closure|null $databaseNameGenerator = null;
|
||||
|
||||
public static function __constructStatic(): void
|
||||
{
|
||||
|
|
@ -48,17 +46,17 @@ class DatabaseConfig
|
|||
$this->tenant = $tenant;
|
||||
}
|
||||
|
||||
public static function generateDatabaseNamesUsing(callable $databaseNameGenerator): void
|
||||
public static function generateDatabaseNamesUsing(Closure $databaseNameGenerator): void
|
||||
{
|
||||
static::$databaseNameGenerator = $databaseNameGenerator;
|
||||
}
|
||||
|
||||
public static function generateUsernamesUsing(callable $usernameGenerator): void
|
||||
public static function generateUsernamesUsing(Closure $usernameGenerator): void
|
||||
{
|
||||
static::$usernameGenerator = $usernameGenerator;
|
||||
}
|
||||
|
||||
public static function generatePasswordsUsing(callable $passwordGenerator): void
|
||||
public static function generatePasswordsUsing(Closure $passwordGenerator): void
|
||||
{
|
||||
static::$passwordGenerator = $passwordGenerator;
|
||||
}
|
||||
|
|
@ -85,7 +83,7 @@ class DatabaseConfig
|
|||
{
|
||||
$this->tenant->setInternal('db_name', $this->getName() ?? (static::$databaseNameGenerator)($this->tenant));
|
||||
|
||||
if ($this->manager() instanceof ManagesDatabaseUsers) {
|
||||
if ($this->manager() instanceof Contracts\ManagesDatabaseUsers) {
|
||||
$this->tenant->setInternal('db_username', $this->getUsername() ?? (static::$usernameGenerator)($this->tenant));
|
||||
$this->tenant->setInternal('db_password', $this->getPassword() ?? (static::$passwordGenerator)($this->tenant));
|
||||
}
|
||||
|
|
@ -142,20 +140,18 @@ class DatabaseConfig
|
|||
}, []);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the TenantDatabaseManager for this tenant's connection.
|
||||
*/
|
||||
public function manager(): TenantDatabaseManager
|
||||
/** Get the TenantDatabaseManager for this tenant's connection. */
|
||||
public function manager(): Contracts\TenantDatabaseManager
|
||||
{
|
||||
$driver = config("database.connections.{$this->getTemplateConnectionName()}.driver");
|
||||
|
||||
$databaseManagers = config('tenancy.database.managers');
|
||||
|
||||
if (! array_key_exists($driver, $databaseManagers)) {
|
||||
throw new DatabaseManagerNotRegisteredException($driver);
|
||||
throw new Exceptions\DatabaseManagerNotRegisteredException($driver);
|
||||
}
|
||||
|
||||
/** @var TenantDatabaseManager $databaseManager */
|
||||
/** @var Contracts\TenantDatabaseManager $databaseManager */
|
||||
$databaseManager = app($databaseManagers[$driver]);
|
||||
|
||||
$databaseManager->setConnection($this->getTemplateConnectionName());
|
||||
|
|
@ -7,12 +7,8 @@ namespace Stancl\Tenancy\Database;
|
|||
use Illuminate\Config\Repository;
|
||||
use Illuminate\Contracts\Foundation\Application;
|
||||
use Illuminate\Database\DatabaseManager as BaseDatabaseManager;
|
||||
use Stancl\Tenancy\Contracts\ManagesDatabaseUsers;
|
||||
use Stancl\Tenancy\Contracts\TenantCannotBeCreatedException;
|
||||
use Stancl\Tenancy\Contracts\TenantWithDatabase;
|
||||
use Stancl\Tenancy\Exceptions\DatabaseManagerNotRegisteredException;
|
||||
use Stancl\Tenancy\Exceptions\TenantDatabaseAlreadyExistsException;
|
||||
use Stancl\Tenancy\Exceptions\TenantDatabaseUserAlreadyExistsException;
|
||||
use Stancl\Tenancy\Database\Contracts\TenantWithDatabase;
|
||||
|
||||
/**
|
||||
* @internal Class is subject to breaking changes in minor and patch versions.
|
||||
|
|
@ -38,7 +34,7 @@ class DatabaseManager
|
|||
/**
|
||||
* Connect to a tenant's database.
|
||||
*/
|
||||
public function connectToTenant(TenantWithDatabase $tenant)
|
||||
public function connectToTenant(TenantWithDatabase $tenant): void
|
||||
{
|
||||
$this->purgeTenantConnection();
|
||||
$this->createTenantConnection($tenant);
|
||||
|
|
@ -48,7 +44,7 @@ class DatabaseManager
|
|||
/**
|
||||
* Reconnect to the default non-tenant connection.
|
||||
*/
|
||||
public function reconnectToCentral()
|
||||
public function reconnectToCentral(): void
|
||||
{
|
||||
$this->purgeTenantConnection();
|
||||
$this->setDefaultConnection($this->config->get('tenancy.database.central_connection'));
|
||||
|
|
@ -57,7 +53,7 @@ class DatabaseManager
|
|||
/**
|
||||
* Change the default database connection config.
|
||||
*/
|
||||
public function setDefaultConnection(string $connection)
|
||||
public function setDefaultConnection(string $connection): void
|
||||
{
|
||||
$this->config['database.default'] = $connection;
|
||||
$this->database->setDefaultConnection($connection);
|
||||
|
|
@ -66,7 +62,7 @@ class DatabaseManager
|
|||
/**
|
||||
* Create the tenant database connection.
|
||||
*/
|
||||
public function createTenantConnection(TenantWithDatabase $tenant)
|
||||
public function createTenantConnection(TenantWithDatabase $tenant): void
|
||||
{
|
||||
$this->config['database.connections.tenant'] = $tenant->database()->connection();
|
||||
}
|
||||
|
|
@ -74,7 +70,7 @@ class DatabaseManager
|
|||
/**
|
||||
* Purge the tenant database connection.
|
||||
*/
|
||||
public function purgeTenantConnection()
|
||||
public function purgeTenantConnection(): void
|
||||
{
|
||||
if (array_key_exists('tenant', $this->database->getConnections())) {
|
||||
$this->database->purge('tenant');
|
||||
|
|
@ -95,11 +91,11 @@ class DatabaseManager
|
|||
$manager = $tenant->database()->manager();
|
||||
|
||||
if ($manager->databaseExists($database = $tenant->database()->getName())) {
|
||||
throw new TenantDatabaseAlreadyExistsException($database);
|
||||
throw new Exceptions\TenantDatabaseAlreadyExistsException($database);
|
||||
}
|
||||
|
||||
if ($manager instanceof ManagesDatabaseUsers && $manager->userExists($username = $tenant->database()->getUsername())) {
|
||||
throw new TenantDatabaseUserAlreadyExistsException($username);
|
||||
if ($manager instanceof Contracts\ManagesDatabaseUsers && $manager->userExists($username = $tenant->database()->getUsername())) {
|
||||
throw new Exceptions\TenantDatabaseUserAlreadyExistsException($username);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,15 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Stancl\Tenancy\Database\Exceptions;
|
||||
|
||||
use Exception;
|
||||
|
||||
class DatabaseManagerNotRegisteredException extends Exception
|
||||
{
|
||||
public function __construct(string $driver)
|
||||
{
|
||||
parent::__construct("Database manager for driver $driver is not registered.");
|
||||
}
|
||||
}
|
||||
|
|
@ -2,13 +2,13 @@
|
|||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Stancl\Tenancy\Exceptions;
|
||||
namespace Stancl\Tenancy\Database\Exceptions;
|
||||
|
||||
use Exception;
|
||||
|
||||
class NoConnectionSetException extends Exception
|
||||
{
|
||||
public function __construct($manager)
|
||||
public function __construct(string $manager)
|
||||
{
|
||||
parent::__construct("No connection was set on this $manager instance.");
|
||||
}
|
||||
|
|
@ -2,24 +2,20 @@
|
|||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Stancl\Tenancy\Exceptions;
|
||||
namespace Stancl\Tenancy\Database\Exceptions;
|
||||
|
||||
use Stancl\Tenancy\Contracts\TenantCannotBeCreatedException;
|
||||
|
||||
class TenantDatabaseAlreadyExistsException extends TenantCannotBeCreatedException
|
||||
{
|
||||
/** @var string */
|
||||
protected $database;
|
||||
public function __construct(
|
||||
protected string $database,
|
||||
) {
|
||||
parent::__construct();
|
||||
}
|
||||
|
||||
public function reason(): string
|
||||
{
|
||||
return "Database {$this->database} already exists.";
|
||||
}
|
||||
|
||||
public function __construct(string $database)
|
||||
{
|
||||
$this->database = $database;
|
||||
|
||||
parent::__construct();
|
||||
}
|
||||
}
|
||||
|
|
@ -2,13 +2,13 @@
|
|||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Stancl\Tenancy\Exceptions;
|
||||
namespace Stancl\Tenancy\Database\Exceptions;
|
||||
|
||||
use Exception;
|
||||
|
||||
class TenantDatabaseDoesNotExistException extends Exception
|
||||
{
|
||||
public function __construct($database)
|
||||
public function __construct(string $database)
|
||||
{
|
||||
parent::__construct("Database $database does not exist.");
|
||||
}
|
||||
|
|
@ -2,24 +2,20 @@
|
|||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Stancl\Tenancy\Exceptions;
|
||||
namespace Stancl\Tenancy\Database\Exceptions;
|
||||
|
||||
use Stancl\Tenancy\Contracts\TenantCannotBeCreatedException;
|
||||
|
||||
class TenantDatabaseUserAlreadyExistsException extends TenantCannotBeCreatedException
|
||||
{
|
||||
/** @var string */
|
||||
protected $user;
|
||||
public function __construct(
|
||||
protected string $user,
|
||||
) {
|
||||
parent::__construct();
|
||||
}
|
||||
|
||||
public function reason(): string
|
||||
{
|
||||
return "Database user {$this->user} already exists.";
|
||||
}
|
||||
|
||||
public function __construct(string $user)
|
||||
{
|
||||
parent::__construct();
|
||||
|
||||
$this->user = $user;
|
||||
}
|
||||
}
|
||||
|
|
@ -5,6 +5,7 @@ declare(strict_types=1);
|
|||
namespace Stancl\Tenancy\Database\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use Stancl\Tenancy\Contracts;
|
||||
use Stancl\Tenancy\Contracts\Tenant;
|
||||
use Stancl\Tenancy\Database\Concerns;
|
||||
|
|
@ -25,7 +26,7 @@ class Domain extends Model implements Contracts\Domain
|
|||
|
||||
protected $guarded = [];
|
||||
|
||||
public function tenant()
|
||||
public function tenant(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(config('tenancy.tenant_model'));
|
||||
}
|
||||
|
|
|
|||
|
|
@ -5,17 +5,20 @@ declare(strict_types=1);
|
|||
namespace Stancl\Tenancy\Database\Models;
|
||||
|
||||
use Carbon\Carbon;
|
||||
use Illuminate\Contracts\Auth\StatefulGuard;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Illuminate\Support\Str;
|
||||
use Stancl\Tenancy\Database\Concerns\CentralConnection;
|
||||
use Stancl\Tenancy\Exceptions\StatefulGuardRequiredException;
|
||||
|
||||
/**
|
||||
* @param string $token
|
||||
* @param string $tenant_id
|
||||
* @param string $user_id
|
||||
* @param string $auth_guard
|
||||
* @param string $redirect_url
|
||||
* @param Carbon $created_at
|
||||
* @property string $token
|
||||
* @property string $tenant_id
|
||||
* @property string $user_id
|
||||
* @property string $auth_guard
|
||||
* @property string $redirect_url
|
||||
* @property Carbon $created_at
|
||||
*/
|
||||
class ImpersonationToken extends Model
|
||||
{
|
||||
|
|
@ -35,14 +38,18 @@ class ImpersonationToken extends Model
|
|||
'created_at',
|
||||
];
|
||||
|
||||
public static function boot()
|
||||
public static function booted(): void
|
||||
{
|
||||
parent::boot();
|
||||
|
||||
static::creating(function ($model) {
|
||||
$authGuard = $model->auth_guard ?? config('auth.defaults.guard');
|
||||
|
||||
if (! Auth::guard($authGuard) instanceof StatefulGuard) {
|
||||
throw new StatefulGuardRequiredException($authGuard);
|
||||
}
|
||||
|
||||
$model->created_at = $model->created_at ?? $model->freshTimestamp();
|
||||
$model->token = $model->token ?? Str::random(128);
|
||||
$model->auth_guard = $model->auth_guard ?? config('auth.defaults.guard');
|
||||
$model->auth_guard = $authGuard;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -39,7 +39,7 @@ class Tenant extends Model implements Contracts\Tenant
|
|||
return 'id';
|
||||
}
|
||||
|
||||
public function getTenantKey()
|
||||
public function getTenantKey(): int|string
|
||||
{
|
||||
return $this->getAttribute($this->getTenantKeyName());
|
||||
}
|
||||
|
|
|
|||
|
|
@ -9,10 +9,8 @@ use Stancl\Tenancy\Contracts\Syncable;
|
|||
|
||||
class TenantPivot extends Pivot
|
||||
{
|
||||
public static function boot()
|
||||
public static function booted(): void
|
||||
{
|
||||
parent::boot();
|
||||
|
||||
static::saved(function (self $pivot) {
|
||||
$parent = $pivot->pivotParent;
|
||||
|
||||
|
|
|
|||
|
|
@ -10,7 +10,7 @@ use Illuminate\Database\Eloquent\Scope;
|
|||
|
||||
class ParentModelScope implements Scope
|
||||
{
|
||||
public function apply(Builder $builder, Model $model)
|
||||
public function apply(Builder $builder, Model $model): void
|
||||
{
|
||||
if (! tenancy()->initialized) {
|
||||
return;
|
||||
|
|
|
|||
|
|
@ -4,6 +4,7 @@ declare(strict_types=1);
|
|||
|
||||
namespace Stancl\Tenancy\Database;
|
||||
|
||||
use Closure;
|
||||
use Illuminate\Database\Eloquent\Collection;
|
||||
use Stancl\Tenancy\Contracts\Tenant;
|
||||
|
||||
|
|
@ -16,7 +17,7 @@ use Stancl\Tenancy\Contracts\Tenant;
|
|||
*/
|
||||
class TenantCollection extends Collection
|
||||
{
|
||||
public function runForEach(callable $callable): self
|
||||
public function runForEach(Closure $callable): self
|
||||
{
|
||||
tenancy()->runForMultiple($this->items, $callable);
|
||||
|
||||
|
|
|
|||
|
|
@ -0,0 +1,29 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Stancl\Tenancy\Database\TenantDatabaseManagers;
|
||||
|
||||
use Stancl\Tenancy\Database\Contracts\TenantWithDatabase;
|
||||
|
||||
class MicrosoftSQLDatabaseManager extends TenantDatabaseManager
|
||||
{
|
||||
public function createDatabase(TenantWithDatabase $tenant): bool
|
||||
{
|
||||
$database = $tenant->database()->getName();
|
||||
$charset = $this->database()->getConfig('charset');
|
||||
$collation = $this->database()->getConfig('collation'); // todo check why these are not used
|
||||
|
||||
return $this->database()->statement("CREATE DATABASE [{$database}]");
|
||||
}
|
||||
|
||||
public function deleteDatabase(TenantWithDatabase $tenant): bool
|
||||
{
|
||||
return $this->database()->statement("DROP DATABASE [{$tenant->database()->getName()}]");
|
||||
}
|
||||
|
||||
public function databaseExists(string $name): bool
|
||||
{
|
||||
return (bool) $this->database()->select("SELECT name FROM master.sys.databases WHERE name = '$name'");
|
||||
}
|
||||
}
|
||||
29
src/Database/TenantDatabaseManagers/MySQLDatabaseManager.php
Normal file
29
src/Database/TenantDatabaseManagers/MySQLDatabaseManager.php
Normal file
|
|
@ -0,0 +1,29 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Stancl\Tenancy\Database\TenantDatabaseManagers;
|
||||
|
||||
use Stancl\Tenancy\Database\Contracts\TenantWithDatabase;
|
||||
|
||||
class MySQLDatabaseManager extends TenantDatabaseManager
|
||||
{
|
||||
public function createDatabase(TenantWithDatabase $tenant): bool
|
||||
{
|
||||
$database = $tenant->database()->getName();
|
||||
$charset = $this->database()->getConfig('charset');
|
||||
$collation = $this->database()->getConfig('collation');
|
||||
|
||||
return $this->database()->statement("CREATE DATABASE `{$database}` CHARACTER SET `$charset` COLLATE `$collation`");
|
||||
}
|
||||
|
||||
public function deleteDatabase(TenantWithDatabase $tenant): bool
|
||||
{
|
||||
return $this->database()->statement("DROP DATABASE `{$tenant->database()->getName()}`");
|
||||
}
|
||||
|
||||
public function databaseExists(string $name): bool
|
||||
{
|
||||
return (bool) $this->database()->select("SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = '$name'");
|
||||
}
|
||||
}
|
||||
|
|
@ -2,11 +2,11 @@
|
|||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Stancl\Tenancy\TenantDatabaseManagers;
|
||||
namespace Stancl\Tenancy\Database\TenantDatabaseManagers;
|
||||
|
||||
use Stancl\Tenancy\Concerns\CreatesDatabaseUsers;
|
||||
use Stancl\Tenancy\Contracts\ManagesDatabaseUsers;
|
||||
use Stancl\Tenancy\DatabaseConfig;
|
||||
use Stancl\Tenancy\Database\Concerns\CreatesDatabaseUsers;
|
||||
use Stancl\Tenancy\Database\Contracts\ManagesDatabaseUsers;
|
||||
use Stancl\Tenancy\Database\DatabaseConfig;
|
||||
|
||||
class PermissionControlledMySQLDatabaseManager extends MySQLDatabaseManager implements ManagesDatabaseUsers
|
||||
{
|
||||
|
|
@ -54,11 +54,4 @@ class PermissionControlledMySQLDatabaseManager extends MySQLDatabaseManager impl
|
|||
{
|
||||
return (bool) $this->database()->select("SELECT count(*) FROM mysql.user WHERE user = '$username'")[0]->{'count(*)'};
|
||||
}
|
||||
|
||||
public function makeConnectionConfig(array $baseConfig, string $databaseName): array
|
||||
{
|
||||
$baseConfig['database'] = $databaseName;
|
||||
|
||||
return $baseConfig;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,25 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Stancl\Tenancy\Database\TenantDatabaseManagers;
|
||||
|
||||
use Stancl\Tenancy\Database\Contracts\TenantWithDatabase;
|
||||
|
||||
class PostgreSQLDatabaseManager extends TenantDatabaseManager
|
||||
{
|
||||
public function createDatabase(TenantWithDatabase $tenant): bool
|
||||
{
|
||||
return $this->database()->statement("CREATE DATABASE \"{$tenant->database()->getName()}\" WITH TEMPLATE=template0");
|
||||
}
|
||||
|
||||
public function deleteDatabase(TenantWithDatabase $tenant): bool
|
||||
{
|
||||
return $this->database()->statement("DROP DATABASE \"{$tenant->database()->getName()}\"");
|
||||
}
|
||||
|
||||
public function databaseExists(string $name): bool
|
||||
{
|
||||
return (bool) $this->database()->select("SELECT datname FROM pg_database WHERE datname = '$name'");
|
||||
}
|
||||
}
|
||||
|
|
@ -2,33 +2,12 @@
|
|||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Stancl\Tenancy\TenantDatabaseManagers;
|
||||
namespace Stancl\Tenancy\Database\TenantDatabaseManagers;
|
||||
|
||||
use Illuminate\Database\Connection;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Stancl\Tenancy\Contracts\TenantDatabaseManager;
|
||||
use Stancl\Tenancy\Contracts\TenantWithDatabase;
|
||||
use Stancl\Tenancy\Exceptions\NoConnectionSetException;
|
||||
use Stancl\Tenancy\Database\Contracts\TenantWithDatabase;
|
||||
|
||||
class PostgreSQLSchemaManager implements TenantDatabaseManager
|
||||
class PostgreSQLSchemaManager extends TenantDatabaseManager
|
||||
{
|
||||
/** @var string */
|
||||
protected $connection;
|
||||
|
||||
protected function database(): Connection
|
||||
{
|
||||
if ($this->connection === null) {
|
||||
throw new NoConnectionSetException(static::class);
|
||||
}
|
||||
|
||||
return DB::connection($this->connection);
|
||||
}
|
||||
|
||||
public function setConnection(string $connection): void
|
||||
{
|
||||
$this->connection = $connection;
|
||||
}
|
||||
|
||||
public function createDatabase(TenantWithDatabase $tenant): bool
|
||||
{
|
||||
return $this->database()->statement("CREATE SCHEMA \"{$tenant->database()->getName()}\"");
|
||||
|
|
@ -2,10 +2,11 @@
|
|||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Stancl\Tenancy\TenantDatabaseManagers;
|
||||
namespace Stancl\Tenancy\Database\TenantDatabaseManagers;
|
||||
|
||||
use Stancl\Tenancy\Contracts\TenantDatabaseManager;
|
||||
use Stancl\Tenancy\Contracts\TenantWithDatabase;
|
||||
use Stancl\Tenancy\Database\Contracts\TenantDatabaseManager;
|
||||
use Stancl\Tenancy\Database\Contracts\TenantWithDatabase;
|
||||
use Throwable;
|
||||
|
||||
class SQLiteDatabaseManager implements TenantDatabaseManager
|
||||
{
|
||||
|
|
@ -13,7 +14,7 @@ class SQLiteDatabaseManager implements TenantDatabaseManager
|
|||
{
|
||||
try {
|
||||
return file_put_contents(database_path($tenant->database()->getName()), '');
|
||||
} catch (\Throwable $th) {
|
||||
} catch (Throwable) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
|
@ -22,7 +23,7 @@ class SQLiteDatabaseManager implements TenantDatabaseManager
|
|||
{
|
||||
try {
|
||||
return unlink(database_path($tenant->database()->getName()));
|
||||
} catch (\Throwable $th) {
|
||||
} catch (Throwable) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,37 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Stancl\Tenancy\Database\TenantDatabaseManagers;
|
||||
|
||||
use Illuminate\Database\Connection;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Stancl\Tenancy\Database\Contracts\TenantDatabaseManager as Contract;
|
||||
use Stancl\Tenancy\Database\Exceptions\NoConnectionSetException;
|
||||
|
||||
abstract class TenantDatabaseManager implements Contract // todo better naming?
|
||||
{
|
||||
/** The database connection to the server. */
|
||||
protected string $connection;
|
||||
|
||||
protected function database(): Connection
|
||||
{
|
||||
if (! isset($this->connection)) {
|
||||
throw new NoConnectionSetException(static::class);
|
||||
}
|
||||
|
||||
return DB::connection($this->connection);
|
||||
}
|
||||
|
||||
public function setConnection(string $connection): void
|
||||
{
|
||||
$this->connection = $connection;
|
||||
}
|
||||
|
||||
public function makeConnectionConfig(array $baseConfig, string $databaseName): array
|
||||
{
|
||||
$baseConfig['database'] = $databaseName;
|
||||
|
||||
return $baseConfig;
|
||||
}
|
||||
}
|
||||
12
src/Enums/LogMode.php
Normal file
12
src/Enums/LogMode.php
Normal file
|
|
@ -0,0 +1,12 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Stancl\Tenancy\Enums;
|
||||
|
||||
enum LogMode
|
||||
{
|
||||
case NONE;
|
||||
case SILENT;
|
||||
case INSTANT;
|
||||
}
|
||||
|
|
@ -5,7 +5,7 @@ declare(strict_types=1);
|
|||
namespace Stancl\Tenancy\Events;
|
||||
|
||||
use Stancl\Tenancy\Contracts\Syncable;
|
||||
use Stancl\Tenancy\Contracts\TenantWithDatabase;
|
||||
use Stancl\Tenancy\Database\Contracts\TenantWithDatabase;
|
||||
|
||||
class SyncedResourceChangedInForeignDatabase
|
||||
{
|
||||
|
|
|
|||
|
|
@ -6,17 +6,16 @@ namespace Stancl\Tenancy\Events;
|
|||
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Stancl\Tenancy\Contracts\Syncable;
|
||||
use Stancl\Tenancy\Contracts\TenantWithDatabase;
|
||||
use Stancl\Tenancy\Database\Contracts\TenantWithDatabase;
|
||||
|
||||
class SyncedResourceSaved
|
||||
{
|
||||
/** @var Syncable|Model */
|
||||
public $model;
|
||||
public Syncable&Model $model;
|
||||
|
||||
/** @var TenantWithDatabase|Model|null */
|
||||
public $tenant;
|
||||
/** @var (TenantWithDatabase&Model)|null */
|
||||
public TenantWithDatabase|null $tenant;
|
||||
|
||||
public function __construct(Syncable $model, ?TenantWithDatabase $tenant)
|
||||
public function __construct(Syncable $model, TenantWithDatabase|null $tenant)
|
||||
{
|
||||
$this->model = $model;
|
||||
$this->tenant = $tenant;
|
||||
|
|
|
|||
|
|
@ -1,13 +0,0 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Stancl\Tenancy\Exceptions;
|
||||
|
||||
class DatabaseManagerNotRegisteredException extends \Exception
|
||||
{
|
||||
public function __construct($driver)
|
||||
{
|
||||
parent::__construct("Database manager for driver $driver is not registered.");
|
||||
}
|
||||
}
|
||||
15
src/Exceptions/StatefulGuardRequiredException.php
Normal file
15
src/Exceptions/StatefulGuardRequiredException.php
Normal file
|
|
@ -0,0 +1,15 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Stancl\Tenancy\Exceptions;
|
||||
|
||||
use Exception;
|
||||
|
||||
class StatefulGuardRequiredException extends Exception
|
||||
{
|
||||
public function __construct(string $guardName)
|
||||
{
|
||||
parent::__construct("Cannot use a non-stateful guard ('$guardName'). A guard implementing the Illuminate\\Contracts\\Auth\\StatefulGuard interface is required.");
|
||||
}
|
||||
}
|
||||
|
|
@ -1,28 +0,0 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Stancl\Tenancy\Exceptions;
|
||||
|
||||
use Facade\IgnitionContracts\BaseSolution;
|
||||
use Facade\IgnitionContracts\ProvidesSolution;
|
||||
use Facade\IgnitionContracts\Solution;
|
||||
use Stancl\Tenancy\Contracts\TenantCouldNotBeIdentifiedException;
|
||||
|
||||
// todo: in v4 this should be suffixed with Exception
|
||||
class TenantCouldNotBeIdentifiedById extends TenantCouldNotBeIdentifiedException implements ProvidesSolution
|
||||
{
|
||||
public function __construct($tenant_id)
|
||||
{
|
||||
parent::__construct("Tenant could not be identified with tenant_id: $tenant_id");
|
||||
}
|
||||
|
||||
public function getSolution(): Solution
|
||||
{
|
||||
return BaseSolution::create('Tenant could not be identified with that ID')
|
||||
->setSolutionDescription('Are you sure the ID is correct and the tenant exists?')
|
||||
->setDocumentationLinks([
|
||||
'Initializing Tenants' => 'https://tenancyforlaravel.com/docs/v3/tenants',
|
||||
]);
|
||||
}
|
||||
}
|
||||
20
src/Exceptions/TenantCouldNotBeIdentifiedByIdException.php
Normal file
20
src/Exceptions/TenantCouldNotBeIdentifiedByIdException.php
Normal file
|
|
@ -0,0 +1,20 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
// todo perhaps create Identification namespace
|
||||
|
||||
namespace Stancl\Tenancy\Exceptions;
|
||||
|
||||
use Stancl\Tenancy\Contracts\TenantCouldNotBeIdentifiedException;
|
||||
|
||||
class TenantCouldNotBeIdentifiedByIdException extends TenantCouldNotBeIdentifiedException
|
||||
{
|
||||
public function __construct(int|string $tenant_id)
|
||||
{
|
||||
$this
|
||||
->tenantCouldNotBeIdentified("by tenant id: $tenant_id")
|
||||
->title('Tenant could not be identified with that ID')
|
||||
->description('Are you sure the ID is correct and the tenant exists?');
|
||||
}
|
||||
}
|
||||
|
|
@ -4,24 +4,15 @@ declare(strict_types=1);
|
|||
|
||||
namespace Stancl\Tenancy\Exceptions;
|
||||
|
||||
use Facade\IgnitionContracts\BaseSolution;
|
||||
use Facade\IgnitionContracts\ProvidesSolution;
|
||||
use Facade\IgnitionContracts\Solution;
|
||||
use Stancl\Tenancy\Contracts\TenantCouldNotBeIdentifiedException;
|
||||
|
||||
class TenantCouldNotBeIdentifiedByPathException extends TenantCouldNotBeIdentifiedException implements ProvidesSolution
|
||||
class TenantCouldNotBeIdentifiedByPathException extends TenantCouldNotBeIdentifiedException
|
||||
{
|
||||
public function __construct($tenant_id)
|
||||
public function __construct(int|string $tenant_id)
|
||||
{
|
||||
parent::__construct("Tenant could not be identified on path with tenant_id: $tenant_id");
|
||||
}
|
||||
|
||||
public function getSolution(): Solution
|
||||
{
|
||||
return BaseSolution::create('Tenant could not be identified on this path')
|
||||
->setSolutionDescription('Did you forget to create a tenant for this path?')
|
||||
->setDocumentationLinks([
|
||||
'Creating Tenants' => 'https://tenancyforlaravel.com/docs/v3/tenants/',
|
||||
]);
|
||||
$this
|
||||
->tenantCouldNotBeIdentified("on path with tenant id: $tenant_id")
|
||||
->title('Tenant could not be identified on this path')
|
||||
->description('Did you forget to create a tenant for this path?');
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -4,24 +4,15 @@ declare(strict_types=1);
|
|||
|
||||
namespace Stancl\Tenancy\Exceptions;
|
||||
|
||||
use Facade\IgnitionContracts\BaseSolution;
|
||||
use Facade\IgnitionContracts\ProvidesSolution;
|
||||
use Facade\IgnitionContracts\Solution;
|
||||
use Stancl\Tenancy\Contracts\TenantCouldNotBeIdentifiedException;
|
||||
|
||||
class TenantCouldNotBeIdentifiedByRequestDataException extends TenantCouldNotBeIdentifiedException implements ProvidesSolution
|
||||
class TenantCouldNotBeIdentifiedByRequestDataException extends TenantCouldNotBeIdentifiedException
|
||||
{
|
||||
public function __construct($tenant_id)
|
||||
public function __construct(mixed $payload)
|
||||
{
|
||||
parent::__construct("Tenant could not be identified by request data with payload: $tenant_id");
|
||||
}
|
||||
|
||||
public function getSolution(): Solution
|
||||
{
|
||||
return BaseSolution::create('Tenant could not be identified with this request data')
|
||||
->setSolutionDescription('Did you forget to create a tenant with this id?')
|
||||
->setDocumentationLinks([
|
||||
'Creating Tenants' => 'https://tenancyforlaravel.com/docs/v3/tenants/',
|
||||
]);
|
||||
$this
|
||||
->tenantCouldNotBeIdentified("by request data with payload: $payload")
|
||||
->title('Tenant could not be identified using this request data')
|
||||
->description('Did you forget to create a tenant with this id?');
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -4,24 +4,15 @@ declare(strict_types=1);
|
|||
|
||||
namespace Stancl\Tenancy\Exceptions;
|
||||
|
||||
use Facade\IgnitionContracts\BaseSolution;
|
||||
use Facade\IgnitionContracts\ProvidesSolution;
|
||||
use Facade\IgnitionContracts\Solution;
|
||||
use Stancl\Tenancy\Contracts\TenantCouldNotBeIdentifiedException;
|
||||
|
||||
class TenantCouldNotBeIdentifiedOnDomainException extends TenantCouldNotBeIdentifiedException implements ProvidesSolution
|
||||
class TenantCouldNotBeIdentifiedOnDomainException extends TenantCouldNotBeIdentifiedException
|
||||
{
|
||||
public function __construct($domain)
|
||||
public function __construct(string $domain)
|
||||
{
|
||||
parent::__construct("Tenant could not be identified on domain $domain");
|
||||
}
|
||||
|
||||
public function getSolution(): Solution
|
||||
{
|
||||
return BaseSolution::create('Tenant could not be identified on this domain')
|
||||
->setSolutionDescription('Did you forget to create a tenant for this domain?')
|
||||
->setDocumentationLinks([
|
||||
'Creating Tenants' => 'https://tenancyforlaravel.com/docs/v3/tenants/',
|
||||
]);
|
||||
$this
|
||||
->tenantCouldNotBeIdentified("on domain $domain")
|
||||
->title('Tenant could not be identified on this domain')
|
||||
->description('Did you forget to create a tenant for this domain?');
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -14,12 +14,16 @@ class CrossDomainRedirect implements Feature
|
|||
{
|
||||
RedirectResponse::macro('domain', function (string $domain) {
|
||||
/** @var RedirectResponse $this */
|
||||
|
||||
// replace first occurance of hostname fragment with $domain
|
||||
$url = $this->getTargetUrl();
|
||||
|
||||
/**
|
||||
* The original hostname in the redirect response.
|
||||
*
|
||||
* @var string $hostname
|
||||
*/
|
||||
$hostname = parse_url($url, PHP_URL_HOST);
|
||||
$position = strpos($url, $hostname);
|
||||
$this->setTargetUrl(substr_replace($url, $domain, $position, strlen($hostname)));
|
||||
|
||||
$this->setTargetUrl((string) str($url)->replace($hostname, $domain));
|
||||
|
||||
return $this;
|
||||
});
|
||||
|
|
|
|||
|
|
@ -6,6 +6,7 @@ namespace Stancl\Tenancy\Features;
|
|||
|
||||
use Illuminate\Contracts\Config\Repository;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Support\Arr;
|
||||
use Illuminate\Support\Facades\Event;
|
||||
use Stancl\Tenancy\Contracts\Feature;
|
||||
use Stancl\Tenancy\Contracts\Tenant;
|
||||
|
|
@ -18,8 +19,7 @@ class TenantConfig implements Feature
|
|||
/** @var Repository */
|
||||
protected $config;
|
||||
|
||||
/** @var array */
|
||||
public $originalConfig = [];
|
||||
public array $originalConfig = [];
|
||||
|
||||
public static $storageToConfigMap = [
|
||||
// 'paypal_api_key' => 'services.paypal.api_key',
|
||||
|
|
@ -45,19 +45,19 @@ class TenantConfig implements Feature
|
|||
{
|
||||
/** @var Tenant|Model $tenant */
|
||||
foreach (static::$storageToConfigMap as $storageKey => $configKey) {
|
||||
$override = $tenant->getAttribute($storageKey);
|
||||
$override = Arr::get($tenant, $storageKey);
|
||||
|
||||
if (! is_null($override)) {
|
||||
if (is_array($configKey)) {
|
||||
foreach ($configKey as $key) {
|
||||
$this->originalConfig[$key] = $this->originalConfig[$key] ?? $this->config[$key];
|
||||
$this->originalConfig[$key] = $this->originalConfig[$key] ?? $this->config->get($key);
|
||||
|
||||
$this->config[$key] = $override;
|
||||
$this->config->set($key, $override);
|
||||
}
|
||||
} else {
|
||||
$this->originalConfig[$configKey] = $this->originalConfig[$configKey] ?? $this->config[$configKey];
|
||||
$this->originalConfig[$configKey] = $this->originalConfig[$configKey] ?? $this->config->get($configKey);
|
||||
|
||||
$this->config[$configKey] = $override;
|
||||
$this->config->set($configKey, $override);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -66,7 +66,7 @@ class TenantConfig implements Feature
|
|||
public function unsetTenantConfig(): void
|
||||
{
|
||||
foreach ($this->originalConfig as $key => $value) {
|
||||
$this->config[$key] = $value;
|
||||
$this->config->set($key, $value);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -13,9 +13,10 @@ use Stancl\Tenancy\Tenancy;
|
|||
|
||||
class UniversalRoutes implements Feature
|
||||
{
|
||||
public static $middlewareGroup = 'universal';
|
||||
public static string $middlewareGroup = 'universal';
|
||||
|
||||
public static $identificationMiddlewares = [
|
||||
// todo docblock
|
||||
public static array $identificationMiddlewares = [
|
||||
Middleware\InitializeTenancyByDomain::class,
|
||||
Middleware\InitializeTenancyBySubdomain::class,
|
||||
];
|
||||
|
|
@ -39,7 +40,7 @@ class UniversalRoutes implements Feature
|
|||
}
|
||||
}
|
||||
|
||||
public static function routeHasMiddleware(Route $route, $middleware): bool
|
||||
public static function routeHasMiddleware(Route $route, string $middleware): bool
|
||||
{
|
||||
if (in_array($middleware, $route->middleware(), true)) {
|
||||
return true;
|
||||
|
|
|
|||
|
|
@ -4,7 +4,6 @@ declare(strict_types=1);
|
|||
|
||||
namespace Stancl\Tenancy\Features;
|
||||
|
||||
use Carbon\Carbon;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Stancl\Tenancy\Contracts\Feature;
|
||||
|
|
@ -14,7 +13,8 @@ use Stancl\Tenancy\Tenancy;
|
|||
|
||||
class UserImpersonation implements Feature
|
||||
{
|
||||
public static $ttl = 60; // seconds
|
||||
/** The lifespan of impersonation tokens (in seconds). */
|
||||
public static int $ttl = 60;
|
||||
|
||||
public function bootstrap(Tenancy $tenancy): void
|
||||
{
|
||||
|
|
@ -28,25 +28,21 @@ class UserImpersonation implements Feature
|
|||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Impersonate a user and get an HTTP redirect response.
|
||||
*
|
||||
* @param string|ImpersonationToken $token
|
||||
* @param int $ttl
|
||||
*/
|
||||
public static function makeResponse($token, int $ttl = null): RedirectResponse
|
||||
/** Impersonate a user and get an HTTP redirect response. */
|
||||
public static function makeResponse(string|ImpersonationToken $token, int $ttl = null): RedirectResponse
|
||||
{
|
||||
/** @var ImpersonationToken $token */
|
||||
$token = $token instanceof ImpersonationToken ? $token : ImpersonationToken::findOrFail($token);
|
||||
$ttl ??= static::$ttl;
|
||||
|
||||
if (((string) $token->tenant_id) !== ((string) tenant()->getTenantKey())) {
|
||||
abort(403);
|
||||
}
|
||||
$tokenExpired = $token->created_at->diffInSeconds(now()) > $ttl;
|
||||
|
||||
$ttl = $ttl ?? static::$ttl;
|
||||
abort_if($tokenExpired, 403);
|
||||
|
||||
if ($token->created_at->diffInSeconds(Carbon::now()) > $ttl) {
|
||||
abort(403);
|
||||
}
|
||||
$tokenTenantId = (string) $token->tenant_id;
|
||||
$currentTenantId = (string) tenant()->getTenantKey();
|
||||
|
||||
abort_unless($tokenTenantId === $currentTenantId, 403);
|
||||
|
||||
Auth::guard($token->auth_guard)->loginUsingId($token->user_id);
|
||||
|
||||
|
|
|
|||
|
|
@ -10,7 +10,7 @@ use Illuminate\Database\Eloquent\Model;
|
|||
use Illuminate\Foundation\Bus\Dispatchable;
|
||||
use Illuminate\Queue\InteractsWithQueue;
|
||||
use Illuminate\Queue\SerializesModels;
|
||||
use Stancl\Tenancy\Contracts\TenantWithDatabase;
|
||||
use Stancl\Tenancy\Database\Contracts\TenantWithDatabase;
|
||||
use Stancl\Tenancy\Database\DatabaseManager;
|
||||
use Stancl\Tenancy\Events\CreatingDatabase;
|
||||
use Stancl\Tenancy\Events\DatabaseCreated;
|
||||
|
|
@ -19,12 +19,9 @@ class CreateDatabase implements ShouldQueue
|
|||
{
|
||||
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
|
||||
|
||||
/** @var TenantWithDatabase|Model */
|
||||
protected $tenant;
|
||||
|
||||
public function __construct(TenantWithDatabase $tenant)
|
||||
{
|
||||
$this->tenant = $tenant;
|
||||
public function __construct(
|
||||
protected TenantWithDatabase&Model $tenant,
|
||||
) {
|
||||
}
|
||||
|
||||
public function handle(DatabaseManager $databaseManager)
|
||||
|
|
|
|||
|
|
@ -6,10 +6,11 @@ namespace Stancl\Tenancy\Jobs;
|
|||
|
||||
use Illuminate\Bus\Queueable;
|
||||
use Illuminate\Contracts\Queue\ShouldQueue;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Foundation\Bus\Dispatchable;
|
||||
use Illuminate\Queue\InteractsWithQueue;
|
||||
use Illuminate\Queue\SerializesModels;
|
||||
use Stancl\Tenancy\Contracts\TenantWithDatabase;
|
||||
use Stancl\Tenancy\Database\Contracts\TenantWithDatabase;
|
||||
use Stancl\Tenancy\Events\DatabaseDeleted;
|
||||
use Stancl\Tenancy\Events\DeletingDatabase;
|
||||
|
||||
|
|
@ -17,15 +18,12 @@ class DeleteDatabase implements ShouldQueue
|
|||
{
|
||||
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
|
||||
|
||||
/** @var TenantWithDatabase */
|
||||
protected $tenant;
|
||||
|
||||
public function __construct(TenantWithDatabase $tenant)
|
||||
{
|
||||
$this->tenant = $tenant;
|
||||
public function __construct(
|
||||
protected TenantWithDatabase&Model $tenant,
|
||||
) {
|
||||
}
|
||||
|
||||
public function handle()
|
||||
public function handle(): void
|
||||
{
|
||||
event(new DeletingDatabase($this->tenant));
|
||||
|
||||
|
|
|
|||
|
|
@ -5,24 +5,26 @@ declare(strict_types=1);
|
|||
namespace Stancl\Tenancy\Jobs;
|
||||
|
||||
use Illuminate\Bus\Queueable;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Foundation\Bus\Dispatchable;
|
||||
use Illuminate\Queue\InteractsWithQueue;
|
||||
use Illuminate\Queue\SerializesModels;
|
||||
use Stancl\Tenancy\Contracts\TenantWithDatabase;
|
||||
use Stancl\Tenancy\Database\Concerns\HasDomains;
|
||||
use Stancl\Tenancy\Database\Contracts\TenantWithDatabase;
|
||||
|
||||
class DeleteDomains
|
||||
{
|
||||
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
|
||||
|
||||
/** @var TenantWithDatabase */
|
||||
protected $tenant;
|
||||
/** @var TenantWithDatabase&Model&HasDomains */ // todo unresolvable type for phpstan
|
||||
protected TenantWithDatabase&Model $tenant;
|
||||
|
||||
public function __construct(TenantWithDatabase $tenant)
|
||||
public function __construct(TenantWithDatabase&Model $tenant)
|
||||
{
|
||||
$this->tenant = $tenant;
|
||||
}
|
||||
|
||||
public function handle()
|
||||
public function handle(): void
|
||||
{
|
||||
$this->tenant->domains->each->delete();
|
||||
}
|
||||
|
|
|
|||
|
|
@ -6,30 +6,23 @@ namespace Stancl\Tenancy\Jobs;
|
|||
|
||||
use Illuminate\Bus\Queueable;
|
||||
use Illuminate\Contracts\Queue\ShouldQueue;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Foundation\Bus\Dispatchable;
|
||||
use Illuminate\Queue\InteractsWithQueue;
|
||||
use Illuminate\Queue\SerializesModels;
|
||||
use Illuminate\Support\Facades\Artisan;
|
||||
use Stancl\Tenancy\Contracts\TenantWithDatabase;
|
||||
use Stancl\Tenancy\Database\Contracts\TenantWithDatabase;
|
||||
|
||||
class MigrateDatabase implements ShouldQueue
|
||||
{
|
||||
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
|
||||
|
||||
/** @var TenantWithDatabase */
|
||||
protected $tenant;
|
||||
|
||||
public function __construct(TenantWithDatabase $tenant)
|
||||
{
|
||||
$this->tenant = $tenant;
|
||||
public function __construct(
|
||||
protected TenantWithDatabase&Model $tenant,
|
||||
) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute the job.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function handle()
|
||||
public function handle(): void
|
||||
{
|
||||
Artisan::call('tenants:migrate', [
|
||||
'--tenants' => [$this->tenant->getTenantKey()],
|
||||
|
|
|
|||
|
|
@ -6,30 +6,23 @@ namespace Stancl\Tenancy\Jobs;
|
|||
|
||||
use Illuminate\Bus\Queueable;
|
||||
use Illuminate\Contracts\Queue\ShouldQueue;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Foundation\Bus\Dispatchable;
|
||||
use Illuminate\Queue\InteractsWithQueue;
|
||||
use Illuminate\Queue\SerializesModels;
|
||||
use Illuminate\Support\Facades\Artisan;
|
||||
use Stancl\Tenancy\Contracts\TenantWithDatabase;
|
||||
use Stancl\Tenancy\Database\Contracts\TenantWithDatabase;
|
||||
|
||||
class SeedDatabase implements ShouldQueue
|
||||
{
|
||||
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
|
||||
|
||||
/** @var TenantWithDatabase */
|
||||
protected $tenant;
|
||||
|
||||
public function __construct(TenantWithDatabase $tenant)
|
||||
{
|
||||
$this->tenant = $tenant;
|
||||
public function __construct(
|
||||
protected TenantWithDatabase&Model $tenant,
|
||||
) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute the job.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function handle()
|
||||
public function handle(): void
|
||||
{
|
||||
Artisan::call('tenants:seed', [
|
||||
'--tenants' => [$this->tenant->getTenantKey()],
|
||||
|
|
|
|||
|
|
@ -10,7 +10,7 @@ use Stancl\Tenancy\Events\TenancyInitialized;
|
|||
|
||||
class BootstrapTenancy
|
||||
{
|
||||
public function handle(TenancyInitialized $event)
|
||||
public function handle(TenancyInitialized $event): void
|
||||
{
|
||||
event(new BootstrappingTenancy($event->tenancy));
|
||||
|
||||
|
|
|
|||
|
|
@ -17,7 +17,7 @@ class CreateTenantConnection
|
|||
$this->database = $database;
|
||||
}
|
||||
|
||||
public function handle(TenantEvent $event)
|
||||
public function handle(TenantEvent $event): void
|
||||
{
|
||||
$this->database->createTenantConnection($event->tenant);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -11,9 +11,9 @@ use Illuminate\Contracts\Queue\ShouldQueue;
|
|||
*/
|
||||
abstract class QueueableListener implements ShouldQueue
|
||||
{
|
||||
public static $shouldQueue = false;
|
||||
public static bool $shouldQueue = false;
|
||||
|
||||
public function shouldQueue($event)
|
||||
public function shouldQueue($event): bool
|
||||
{
|
||||
if (static::$shouldQueue) {
|
||||
return true;
|
||||
|
|
|
|||
|
|
@ -10,11 +10,11 @@ use Stancl\Tenancy\Events\TenancyEnded;
|
|||
|
||||
class RevertToCentralContext
|
||||
{
|
||||
public function handle(TenancyEnded $event)
|
||||
public function handle(TenancyEnded $event): void
|
||||
{
|
||||
event(new RevertingToCentralContext($event->tenancy));
|
||||
|
||||
foreach ($event->tenancy->getBootstrappers() as $bootstrapper) {
|
||||
foreach (array_reverse($event->tenancy->getBootstrappers()) as $bootstrapper) {
|
||||
$bootstrapper->revert();
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -4,6 +4,7 @@ declare(strict_types=1);
|
|||
|
||||
namespace Stancl\Tenancy\Listeners;
|
||||
|
||||
use Illuminate\Database\Eloquent\Collection as EloquentCollection;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\Pivot;
|
||||
use Stancl\Tenancy\Contracts\SyncMaster;
|
||||
|
|
@ -13,9 +14,9 @@ use Stancl\Tenancy\Exceptions\ModelNotSyncMasterException;
|
|||
|
||||
class UpdateSyncedResource extends QueueableListener
|
||||
{
|
||||
public static $shouldQueue = false;
|
||||
public static bool $shouldQueue = false;
|
||||
|
||||
public function handle(SyncedResourceSaved $event)
|
||||
public function handle(SyncedResourceSaved $event): void
|
||||
{
|
||||
$syncedAttributes = $event->model->only($event->model->getSyncedAttributeNames());
|
||||
|
||||
|
|
@ -29,7 +30,7 @@ class UpdateSyncedResource extends QueueableListener
|
|||
$this->updateResourceInTenantDatabases($tenants, $event, $syncedAttributes);
|
||||
}
|
||||
|
||||
protected function getTenantsForCentralModel($centralModel)
|
||||
protected function getTenantsForCentralModel($centralModel): EloquentCollection
|
||||
{
|
||||
if (! $centralModel instanceof SyncMaster) {
|
||||
// If we're trying to use a tenant User model instead of the central User model, for example.
|
||||
|
|
@ -45,7 +46,7 @@ class UpdateSyncedResource extends QueueableListener
|
|||
return $centralModel->tenants;
|
||||
}
|
||||
|
||||
protected function updateResourceInCentralDatabaseAndGetTenants($event, $syncedAttributes)
|
||||
protected function updateResourceInCentralDatabaseAndGetTenants($event, $syncedAttributes): EloquentCollection
|
||||
{
|
||||
/** @var Model|SyncMaster $centralModel */
|
||||
$centralModel = $event->model->getCentralModelName()::where($event->model->getGlobalIdentifierKeyName(), $event->model->getGlobalIdentifierKey())
|
||||
|
|
@ -85,7 +86,7 @@ class UpdateSyncedResource extends QueueableListener
|
|||
});
|
||||
}
|
||||
|
||||
protected function updateResourceInTenantDatabases($tenants, $event, $syncedAttributes)
|
||||
protected function updateResourceInTenantDatabases($tenants, $event, $syncedAttributes): void
|
||||
{
|
||||
tenancy()->runForMultiple($tenants, function ($tenant) use ($event, $syncedAttributes) {
|
||||
// Forget instance state and find the model,
|
||||
|
|
|
|||
|
|
@ -7,6 +7,9 @@ namespace Stancl\Tenancy\Middleware;
|
|||
use Closure;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Routing\Route;
|
||||
use Illuminate\Support\Facades\Event;
|
||||
use Illuminate\Support\Facades\URL;
|
||||
use Stancl\Tenancy\Events\InitializingTenancy;
|
||||
use Stancl\Tenancy\Exceptions\RouteIsMissingTenantParameterException;
|
||||
use Stancl\Tenancy\Resolvers\PathTenantResolver;
|
||||
use Stancl\Tenancy\Tenancy;
|
||||
|
|
@ -37,6 +40,11 @@ class InitializeTenancyByPath extends IdentificationMiddleware
|
|||
// We don't want to initialize tenancy if the tenant is
|
||||
// simply injected into some route controller action.
|
||||
if ($route->parameterNames()[0] === PathTenantResolver::$tenantParameterName) {
|
||||
// Set tenant as a default parameter for the URLs in the current request
|
||||
Event::listen(InitializingTenancy::class, function (InitializingTenancy $event) {
|
||||
URL::defaults([PathTenantResolver::$tenantParameterName => $event->tenancy->tenant->getTenantKey()]);
|
||||
});
|
||||
|
||||
return $this->initializeTenancy(
|
||||
$request,
|
||||
$next,
|
||||
|
|
|
|||
|
|
@ -11,14 +11,11 @@ use Stancl\Tenancy\Contracts\TenantResolver;
|
|||
|
||||
abstract class CachedTenantResolver implements TenantResolver
|
||||
{
|
||||
/** @var bool */
|
||||
public static $shouldCache = false;
|
||||
public static bool $shouldCache = false; // todo docblocks for these
|
||||
|
||||
/** @var int */
|
||||
public static $cacheTTL = 3600; // seconds
|
||||
public static int $cacheTTL = 3600; // seconds
|
||||
|
||||
/** @var string|null */
|
||||
public static $cacheStore = null; // default
|
||||
public static string|null $cacheStore = null; // default
|
||||
|
||||
/** @var Repository */
|
||||
protected $cache;
|
||||
|
|
@ -28,7 +25,7 @@ abstract class CachedTenantResolver implements TenantResolver
|
|||
$this->cache = $cache->store(static::$cacheStore);
|
||||
}
|
||||
|
||||
public function resolve(...$args): Tenant
|
||||
public function resolve(mixed ...$args): Tenant
|
||||
{
|
||||
if (! static::$shouldCache) {
|
||||
return $this->resolveWithoutCache(...$args);
|
||||
|
|
@ -61,12 +58,12 @@ abstract class CachedTenantResolver implements TenantResolver
|
|||
}
|
||||
}
|
||||
|
||||
public function getCacheKey(...$args): string
|
||||
public function getCacheKey(mixed ...$args): string
|
||||
{
|
||||
return '_tenancy_resolver:' . static::class . ':' . json_encode($args);
|
||||
}
|
||||
|
||||
abstract public function resolveWithoutCache(...$args): Tenant;
|
||||
abstract public function resolveWithoutCache(mixed ...$args): Tenant;
|
||||
|
||||
public function resolved(Tenant $tenant, ...$args): void
|
||||
{
|
||||
|
|
|
|||
|
|
@ -11,31 +11,22 @@ use Stancl\Tenancy\Exceptions\TenantCouldNotBeIdentifiedOnDomainException;
|
|||
|
||||
class DomainTenantResolver extends Contracts\CachedTenantResolver
|
||||
{
|
||||
/**
|
||||
* The model representing the domain that the tenant was identified on.
|
||||
*
|
||||
* @var Domain
|
||||
*/
|
||||
public static $currentDomain;
|
||||
/** The model representing the domain that the tenant was identified on. */
|
||||
public static Domain $currentDomain; // todo |null?
|
||||
|
||||
/** @var bool */
|
||||
public static $shouldCache = false;
|
||||
public static bool $shouldCache = false;
|
||||
|
||||
/** @var int */
|
||||
public static $cacheTTL = 3600; // seconds
|
||||
public static int $cacheTTL = 3600; // seconds
|
||||
|
||||
/** @var string|null */
|
||||
public static $cacheStore = null; // default
|
||||
public static string|null $cacheStore = null; // default
|
||||
|
||||
public function resolveWithoutCache(...$args): Tenant
|
||||
public function resolveWithoutCache(mixed ...$args): Tenant
|
||||
{
|
||||
$domain = $args[0];
|
||||
|
||||
/** @var Tenant|null $tenant */
|
||||
$tenant = config('tenancy.tenant_model')::query()
|
||||
->whereHas('domains', function (Builder $query) use ($domain) {
|
||||
$query->where('domain', $domain);
|
||||
})
|
||||
->whereHas('domains', fn (Builder $query) => $query->where('domain', $domain))
|
||||
->with('domains')
|
||||
->first();
|
||||
|
||||
|
|
|
|||
|
|
@ -10,18 +10,15 @@ use Stancl\Tenancy\Exceptions\TenantCouldNotBeIdentifiedByPathException;
|
|||
|
||||
class PathTenantResolver extends Contracts\CachedTenantResolver
|
||||
{
|
||||
public static $tenantParameterName = 'tenant';
|
||||
public static string $tenantParameterName = 'tenant';
|
||||
|
||||
/** @var bool */
|
||||
public static $shouldCache = false;
|
||||
public static bool $shouldCache = false;
|
||||
|
||||
/** @var int */
|
||||
public static $cacheTTL = 3600; // seconds
|
||||
public static int $cacheTTL = 3600; // seconds
|
||||
|
||||
/** @var string|null */
|
||||
public static $cacheStore = null; // default
|
||||
public static string|null $cacheStore = null; // default
|
||||
|
||||
public function resolveWithoutCache(...$args): Tenant
|
||||
public function resolveWithoutCache(mixed ...$args): Tenant
|
||||
{
|
||||
/** @var Route $route */
|
||||
$route = $args[0];
|
||||
|
|
|
|||
|
|
@ -9,16 +9,13 @@ use Stancl\Tenancy\Exceptions\TenantCouldNotBeIdentifiedByRequestDataException;
|
|||
|
||||
class RequestDataTenantResolver extends Contracts\CachedTenantResolver
|
||||
{
|
||||
/** @var bool */
|
||||
public static $shouldCache = false;
|
||||
public static bool $shouldCache = false;
|
||||
|
||||
/** @var int */
|
||||
public static $cacheTTL = 3600; // seconds
|
||||
public static int $cacheTTL = 3600; // seconds
|
||||
|
||||
/** @var string|null */
|
||||
public static $cacheStore = null; // default
|
||||
public static string|null $cacheStore = null; // default
|
||||
|
||||
public function resolveWithoutCache(...$args): Tenant
|
||||
public function resolveWithoutCache(mixed ...$args): Tenant
|
||||
{
|
||||
$payload = $args[0];
|
||||
|
||||
|
|
|
|||
|
|
@ -4,41 +4,45 @@ declare(strict_types=1);
|
|||
|
||||
namespace Stancl\Tenancy;
|
||||
|
||||
use Closure;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Support\Traits\Macroable;
|
||||
use Stancl\Tenancy\Concerns\Debuggable;
|
||||
use Stancl\Tenancy\Contracts\TenancyBootstrapper;
|
||||
use Stancl\Tenancy\Contracts\Tenant;
|
||||
use Stancl\Tenancy\Exceptions\TenantCouldNotBeIdentifiedById;
|
||||
use Stancl\Tenancy\Exceptions\TenantCouldNotBeIdentifiedByIdException;
|
||||
|
||||
class Tenancy
|
||||
{
|
||||
use Macroable;
|
||||
|
||||
/** @var Tenant|Model|null */
|
||||
public $tenant;
|
||||
|
||||
/** @var callable|null */
|
||||
public $getBootstrappersUsing = null;
|
||||
|
||||
/** @var bool */
|
||||
public $initialized = false;
|
||||
use Macroable, Debuggable;
|
||||
|
||||
/**
|
||||
* Initializes the tenant.
|
||||
* @param Tenant|int|string $tenant
|
||||
* The current tenant.
|
||||
*
|
||||
* @var (Tenant&Model)|null
|
||||
*/
|
||||
public function initialize($tenant): void
|
||||
public ?Tenant $tenant = null;
|
||||
|
||||
// todo docblock
|
||||
public ?Closure $getBootstrappersUsing = null;
|
||||
|
||||
/** Is tenancy fully initialized? */
|
||||
public bool $initialized = false; // todo document the difference between $tenant being set and $initialized being true (e.g. end of initialize() method)
|
||||
|
||||
/** Initialize tenancy for the passed tenant. */
|
||||
public function initialize(Tenant|int|string $tenant): void
|
||||
{
|
||||
if (! is_object($tenant)) {
|
||||
$tenantId = $tenant;
|
||||
$tenant = $this->find($tenantId);
|
||||
|
||||
if (! $tenant) {
|
||||
throw new TenantCouldNotBeIdentifiedById($tenantId);
|
||||
throw new TenantCouldNotBeIdentifiedByIdException($tenantId);
|
||||
}
|
||||
}
|
||||
|
||||
// todo0 for phpstan this should be $this->tenant?, but first I want to clean up the $initialized logic and explore removing the property
|
||||
if ($this->initialized && $this->tenant->getTenantKey() === $tenant->getTenantKey()) {
|
||||
return;
|
||||
}
|
||||
|
|
@ -59,17 +63,19 @@ class Tenancy
|
|||
|
||||
public function end(): void
|
||||
{
|
||||
event(new Events\EndingTenancy($this));
|
||||
|
||||
if (! $this->initialized) {
|
||||
return;
|
||||
}
|
||||
|
||||
event(new Events\EndingTenancy($this));
|
||||
|
||||
// todo find a way to refactor these two methods
|
||||
|
||||
event(new Events\TenancyEnded($this));
|
||||
|
||||
$this->initialized = false;
|
||||
|
||||
$this->tenant = null;
|
||||
|
||||
$this->initialized = false;
|
||||
}
|
||||
|
||||
/** @return TenancyBootstrapper[] */
|
||||
|
|
@ -84,29 +90,28 @@ class Tenancy
|
|||
return array_map('app', $resolve($this->tenant));
|
||||
}
|
||||
|
||||
public function query(): Builder
|
||||
public static function query(): Builder
|
||||
{
|
||||
return $this->model()->query();
|
||||
return static::model()->query();
|
||||
}
|
||||
|
||||
/** @return Tenant|Model */
|
||||
public function model()
|
||||
public static function model(): Tenant&Model
|
||||
{
|
||||
$class = config('tenancy.tenant_model');
|
||||
|
||||
return new $class;
|
||||
}
|
||||
|
||||
public function find($id): ?Tenant
|
||||
public static function find(int|string $id): Tenant|null
|
||||
{
|
||||
return $this->model()->where($this->model()->getTenantKeyName(), $id)->first();
|
||||
return static::model()->where(static::model()->getTenantKeyName(), $id)->first();
|
||||
}
|
||||
|
||||
/**
|
||||
* Run a callback in the central context.
|
||||
* Atomic, safely reverts to previous context.
|
||||
*/
|
||||
public function central(callable $callback)
|
||||
public function central(Closure $callback)
|
||||
{
|
||||
$previousTenant = $this->tenant;
|
||||
|
||||
|
|
@ -128,9 +133,8 @@ class Tenancy
|
|||
* More performant than running $tenant->run() one by one.
|
||||
*
|
||||
* @param Tenant[]|\Traversable|string[]|null $tenants
|
||||
* @return void
|
||||
*/
|
||||
public function runForMultiple($tenants, callable $callback)
|
||||
public function runForMultiple($tenants, Closure $callback): void
|
||||
{
|
||||
// Convert null to all tenants
|
||||
$tenants = is_null($tenants) ? $this->model()->cursor() : $tenants;
|
||||
|
|
@ -142,7 +146,7 @@ class Tenancy
|
|||
$tenants = is_string($tenants) ? [$tenants] : $tenants;
|
||||
|
||||
// Use all tenants if $tenants is falsey
|
||||
$tenants = $tenants ?: $this->model()->cursor();
|
||||
$tenants = $tenants ?: $this->model()->cursor(); // todo0 phpstan thinks this isn't needed, but tests fail without it
|
||||
|
||||
$originalTenant = $this->tenant;
|
||||
|
||||
|
|
|
|||
|
|
@ -5,17 +5,18 @@ declare(strict_types=1);
|
|||
namespace Stancl\Tenancy;
|
||||
|
||||
use Illuminate\Cache\CacheManager;
|
||||
use Illuminate\Support\Facades\Event;
|
||||
use Illuminate\Support\ServiceProvider;
|
||||
use Stancl\Tenancy\Bootstrappers\FilesystemTenancyBootstrapper;
|
||||
use Stancl\Tenancy\Contracts\Domain;
|
||||
use Stancl\Tenancy\Contracts\Tenant;
|
||||
use Stancl\Tenancy\Enums\LogMode;
|
||||
use Stancl\Tenancy\Events\Contracts\TenancyEvent;
|
||||
use Stancl\Tenancy\Resolvers\DomainTenantResolver;
|
||||
|
||||
class TenancyServiceProvider extends ServiceProvider
|
||||
{
|
||||
/**
|
||||
* Register services.
|
||||
*/
|
||||
/* Register services. */
|
||||
public function register(): void
|
||||
{
|
||||
$this->mergeConfigFrom(__DIR__ . '/../assets/config.php', 'tenancy');
|
||||
|
|
@ -72,9 +73,7 @@ class TenancyServiceProvider extends ServiceProvider
|
|||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Bootstrap services.
|
||||
*/
|
||||
/* Bootstrap services. */
|
||||
public function boot(): void
|
||||
{
|
||||
$this->commands([
|
||||
|
|
@ -113,6 +112,18 @@ class TenancyServiceProvider extends ServiceProvider
|
|||
$this->loadRoutesFrom(__DIR__ . '/../assets/routes.php');
|
||||
}
|
||||
|
||||
Event::listen('Stancl\\Tenancy\\Events\\*', function (string $name, array $data) {
|
||||
$event = $data[0];
|
||||
|
||||
if ($event instanceof TenancyEvent) {
|
||||
match (tenancy()->logMode()) {
|
||||
LogMode::SILENT => tenancy()->logEvent($event),
|
||||
LogMode::INSTANT => dump($event), // todo0 perhaps still log
|
||||
default => null,
|
||||
};
|
||||
}
|
||||
});
|
||||
|
||||
$this->app->singleton('globalUrl', function ($app) {
|
||||
if ($app->bound(FilesystemTenancyBootstrapper::class)) {
|
||||
$instance = clone $app['url'];
|
||||
|
|
|
|||
|
|
@ -1,57 +0,0 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Stancl\Tenancy\TenantDatabaseManagers;
|
||||
|
||||
use Illuminate\Database\Connection;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Stancl\Tenancy\Contracts\TenantDatabaseManager;
|
||||
use Stancl\Tenancy\Contracts\TenantWithDatabase;
|
||||
use Stancl\Tenancy\Exceptions\NoConnectionSetException;
|
||||
|
||||
class MicrosoftSQLDatabaseManager implements TenantDatabaseManager
|
||||
{
|
||||
/** @var string */
|
||||
protected $connection;
|
||||
|
||||
protected function database(): Connection
|
||||
{
|
||||
if ($this->connection === null) {
|
||||
throw new NoConnectionSetException(static::class);
|
||||
}
|
||||
|
||||
return DB::connection($this->connection);
|
||||
}
|
||||
|
||||
public function setConnection(string $connection): void
|
||||
{
|
||||
$this->connection = $connection;
|
||||
}
|
||||
|
||||
public function createDatabase(TenantWithDatabase $tenant): bool
|
||||
{
|
||||
$database = $tenant->database()->getName();
|
||||
$charset = $this->database()->getConfig('charset');
|
||||
$collation = $this->database()->getConfig('collation');
|
||||
|
||||
return $this->database()->statement("CREATE DATABASE [{$database}]");
|
||||
}
|
||||
|
||||
public function deleteDatabase(TenantWithDatabase $tenant): bool
|
||||
{
|
||||
return $this->database()->statement("DROP DATABASE [{$tenant->database()->getName()}]");
|
||||
}
|
||||
|
||||
public function databaseExists(string $name): bool
|
||||
{
|
||||
return (bool) $this->database()->select("SELECT name FROM master.sys.databases WHERE name = '$name'");
|
||||
}
|
||||
|
||||
public function makeConnectionConfig(array $baseConfig, string $databaseName): array
|
||||
{
|
||||
$baseConfig['database'] = $databaseName;
|
||||
|
||||
return $baseConfig;
|
||||
}
|
||||
}
|
||||
|
|
@ -1,57 +0,0 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Stancl\Tenancy\TenantDatabaseManagers;
|
||||
|
||||
use Illuminate\Database\Connection;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Stancl\Tenancy\Contracts\TenantDatabaseManager;
|
||||
use Stancl\Tenancy\Contracts\TenantWithDatabase;
|
||||
use Stancl\Tenancy\Exceptions\NoConnectionSetException;
|
||||
|
||||
class MySQLDatabaseManager implements TenantDatabaseManager
|
||||
{
|
||||
/** @var string */
|
||||
protected $connection;
|
||||
|
||||
protected function database(): Connection
|
||||
{
|
||||
if ($this->connection === null) {
|
||||
throw new NoConnectionSetException(static::class);
|
||||
}
|
||||
|
||||
return DB::connection($this->connection);
|
||||
}
|
||||
|
||||
public function setConnection(string $connection): void
|
||||
{
|
||||
$this->connection = $connection;
|
||||
}
|
||||
|
||||
public function createDatabase(TenantWithDatabase $tenant): bool
|
||||
{
|
||||
$database = $tenant->database()->getName();
|
||||
$charset = $this->database()->getConfig('charset');
|
||||
$collation = $this->database()->getConfig('collation');
|
||||
|
||||
return $this->database()->statement("CREATE DATABASE `{$database}` CHARACTER SET `$charset` COLLATE `$collation`");
|
||||
}
|
||||
|
||||
public function deleteDatabase(TenantWithDatabase $tenant): bool
|
||||
{
|
||||
return $this->database()->statement("DROP DATABASE `{$tenant->database()->getName()}`");
|
||||
}
|
||||
|
||||
public function databaseExists(string $name): bool
|
||||
{
|
||||
return (bool) $this->database()->select("SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = '$name'");
|
||||
}
|
||||
|
||||
public function makeConnectionConfig(array $baseConfig, string $databaseName): array
|
||||
{
|
||||
$baseConfig['database'] = $databaseName;
|
||||
|
||||
return $baseConfig;
|
||||
}
|
||||
}
|
||||
|
|
@ -1,53 +0,0 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Stancl\Tenancy\TenantDatabaseManagers;
|
||||
|
||||
use Illuminate\Database\Connection;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Stancl\Tenancy\Contracts\TenantDatabaseManager;
|
||||
use Stancl\Tenancy\Contracts\TenantWithDatabase;
|
||||
use Stancl\Tenancy\Exceptions\NoConnectionSetException;
|
||||
|
||||
class PostgreSQLDatabaseManager implements TenantDatabaseManager
|
||||
{
|
||||
/** @var string */
|
||||
protected $connection;
|
||||
|
||||
protected function database(): Connection
|
||||
{
|
||||
if ($this->connection === null) {
|
||||
throw new NoConnectionSetException(static::class);
|
||||
}
|
||||
|
||||
return DB::connection($this->connection);
|
||||
}
|
||||
|
||||
public function setConnection(string $connection): void
|
||||
{
|
||||
$this->connection = $connection;
|
||||
}
|
||||
|
||||
public function createDatabase(TenantWithDatabase $tenant): bool
|
||||
{
|
||||
return $this->database()->statement("CREATE DATABASE \"{$tenant->database()->getName()}\" WITH TEMPLATE=template0");
|
||||
}
|
||||
|
||||
public function deleteDatabase(TenantWithDatabase $tenant): bool
|
||||
{
|
||||
return $this->database()->statement("DROP DATABASE \"{$tenant->database()->getName()}\"");
|
||||
}
|
||||
|
||||
public function databaseExists(string $name): bool
|
||||
{
|
||||
return (bool) $this->database()->select("SELECT datname FROM pg_database WHERE datname = '$name'");
|
||||
}
|
||||
|
||||
public function makeConnectionConfig(array $baseConfig, string $databaseName): array
|
||||
{
|
||||
$baseConfig['database'] = $databaseName;
|
||||
|
||||
return $baseConfig;
|
||||
}
|
||||
}
|
||||
|
|
@ -7,6 +7,8 @@ namespace Stancl\Tenancy;
|
|||
use Ramsey\Uuid\Uuid;
|
||||
use Stancl\Tenancy\Contracts\UniqueIdentifierGenerator;
|
||||
|
||||
// todo move to separate namespace
|
||||
|
||||
class UUIDGenerator implements UniqueIdentifierGenerator
|
||||
{
|
||||
public static function generate($resource): string
|
||||
|
|
|
|||
|
|
@ -15,15 +15,14 @@ if (! function_exists('tenancy')) {
|
|||
|
||||
if (! function_exists('tenant')) {
|
||||
/**
|
||||
* Get a key from the current tenant's storage.
|
||||
* Get the current tenant or a key from the current tenant's properties.
|
||||
*
|
||||
* @param string|null $key
|
||||
* @return Tenant|null|mixed
|
||||
*/
|
||||
function tenant($key = null)
|
||||
function tenant(string $key = null): mixed
|
||||
{
|
||||
if (! app()->bound(Tenant::class)) {
|
||||
return;
|
||||
return null;
|
||||
}
|
||||
|
||||
if (is_null($key)) {
|
||||
|
|
@ -35,15 +34,15 @@ if (! function_exists('tenant')) {
|
|||
}
|
||||
|
||||
if (! function_exists('tenant_asset')) {
|
||||
/** @return string */
|
||||
function tenant_asset($asset)
|
||||
// todo docblock
|
||||
function tenant_asset(string|null $asset): string
|
||||
{
|
||||
return route('stancl.tenancy.asset', ['path' => $asset]);
|
||||
}
|
||||
}
|
||||
|
||||
if (! function_exists('global_asset')) {
|
||||
function global_asset($asset)
|
||||
function global_asset(string $asset) // todo types, also inside the globalUrl implementation
|
||||
{
|
||||
return app('globalUrl')->asset($asset);
|
||||
}
|
||||
|
|
@ -57,13 +56,17 @@ if (! function_exists('global_cache')) {
|
|||
}
|
||||
|
||||
if (! function_exists('tenant_route')) {
|
||||
function tenant_route(string $domain, $route, $parameters = [], $absolute = true)
|
||||
function tenant_route(string $domain, string $route, array $parameters = [], bool $absolute = true): string
|
||||
{
|
||||
// replace first occurance of hostname fragment with $domain
|
||||
$url = route($route, $parameters, $absolute);
|
||||
$hostname = parse_url($url, PHP_URL_HOST);
|
||||
$position = strpos($url, $hostname);
|
||||
|
||||
return substr_replace($url, $domain, $position, strlen($hostname));
|
||||
/**
|
||||
* The original hostname in the generated route.
|
||||
*
|
||||
* @var string $hostname
|
||||
*/
|
||||
$hostname = parse_url($url, PHP_URL_HOST);
|
||||
|
||||
return (string) str($url)->replace($hostname, $domain);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue