1
0
Fork 0
mirror of https://github.com/archtechx/tenancy.git synced 2026-05-06 20:14:04 +00:00
tenancy/src/Database/Concerns/HasDatabase.php
Samuel Štancl a0a9b85982 Refactor DatabaseConfig, minor DB manager improvements, resolve todos
Notable changes:
- CreateUserWithRLSPolicies: Clarify why we're creating a custom
  DatabaseConfing instance
- HasDatabase: Clarify why we're ignoring tenancy_db_connection
- DatabaseConfig: General refactor, clarify the role of the host conn
- SQLiteDatabaseManager: Handle trailing DIRECTORY_SEPARATOR
  in static::$path
- DisallowSqliteAttach: Don't throw any exceptions, just silently fail
  since the class isn't 100% portable
- Clean up todos that are no longer relevant
- Clean up dead code or comments in some database managers
2025-10-13 16:01:34 +02:00

44 lines
1.4 KiB
PHP

<?php
declare(strict_types=1);
namespace Stancl\Tenancy\Database\Concerns;
use Illuminate\Database\Eloquent\Model;
use Stancl\Tenancy\Database\Contracts\TenantWithDatabase;
use Stancl\Tenancy\Database\DatabaseConfig;
/**
* @mixin Model
*/
trait HasDatabase
{
use HasInternalKeys;
public function database(): DatabaseConfig
{
/** @var TenantWithDatabase&Model $this */
$databaseConfig = [];
foreach (array_keys($this->getAttributes()) as $key) {
if (str($key)->startsWith($this->internalPrefix() . 'db_')) {
if ($key === $this->internalPrefix() . 'db_name') {
// Remove DB name because we set that separately
continue;
}
if ($key === $this->internalPrefix() . 'db_connection') {
// Remove DB connection because that's not used for the connection *contents*.
// Instead the code uses getInternal('db_connection').
continue;
}
// We use getAttribute() instead of getting the value directly from the attributes array
// to support encrypted columns and any other types of casts.
$databaseConfig[str($key)->after($this->internalPrefix() . 'db_')->toString()] = $this->getAttribute($key);
}
}
return new DatabaseConfig($this, $databaseConfig);
}
}