1
0
Fork 0
mirror of https://github.com/archtechx/tenancy.git synced 2026-02-05 17:34:03 +00:00

Reduce nesting, rename methods

This commit is contained in:
lukinovec 2023-05-24 14:29:30 +02:00
parent 526002c7b2
commit ae568e1227

View file

@ -16,18 +16,24 @@ class CreateRLSPoliciesForTenantTables extends Command
public function handle(): int public function handle(): int
{ {
$tenantModels = $this->getTenantModels(); foreach (config('tenancy.models.rls') as $modelClass) {
$tenantKey = tenancy()->tenantKeyColumn(); $this->makeModelUseRls((new $modelClass));
}
foreach ($tenantModels as $model) { return Command::SUCCESS;
}
protected function makeModelUseRls(Model $model): void
{
$table = $model->getTable(); $table = $model->getTable();
$tenantKey = tenancy()->tenantKeyColumn();
DB::transaction(fn () => DB::statement("DROP POLICY IF EXISTS {$table}_rls_policy ON {$table}")); DB::transaction(fn () => DB::statement("DROP POLICY IF EXISTS {$table}_rls_policy ON {$table}"));
if (! Schema::hasColumn($table, $tenantKey)) { if (! Schema::hasColumn($table, $tenantKey)) {
// Table is not directly related to tenant // Table is not directly related to tenant
if (in_array(BelongsToPrimaryModel::class, class_uses_recursive($model::class))) { if (in_array(BelongsToPrimaryModel::class, class_uses_recursive($model::class))) {
$this->makeModelUseRls($model); $this->makeSecondaryModelUseRls($model);
} else { } else {
$modelName = $model::class; $modelName = $model::class;
@ -36,21 +42,13 @@ class CreateRLSPoliciesForTenantTables extends Command
} else { } else {
DB::transaction(fn () => DB::statement("CREATE POLICY {$table}_rls_policy ON {$table} USING ({$tenantKey}::TEXT = current_user);")); DB::transaction(fn () => DB::statement("CREATE POLICY {$table}_rls_policy ON {$table} USING ({$tenantKey}::TEXT = current_user);"));
$this->makeTableUseRls($table); $this->enableRls($table);
$this->components->info("Created RLS policy for table '$table'"); $this->components->info("Created RLS policy for table '$table'");
} }
} }
return Command::SUCCESS; protected function makeSecondaryModelUseRls(Model $model): void
}
public function getTenantModels(): array
{
return array_map(fn (string $modelName) => (new $modelName), config('tenancy.models.rls'));
}
protected function makeModelUseRls(Model $model): void
{ {
$table = $model->getTable(); $table = $model->getTable();
$tenantKey = tenancy()->tenantKeyColumn(); $tenantKey = tenancy()->tenantKeyColumn();
@ -72,10 +70,10 @@ class CreateRLSPoliciesForTenantTables extends Command
) )
)")); )"));
$this->makeTableUseRls($table); $this->enableRls($table);
} }
protected function makeTableUseRls(string $table): void protected function enableRls(string $table): void
{ {
DB::transaction(function () use ($table) { DB::transaction(function () use ($table) {
DB::statement("ALTER TABLE {$table} ENABLE ROW LEVEL SECURITY"); DB::statement("ALTER TABLE {$table} ENABLE ROW LEVEL SECURITY");