|
- <?php
-
- namespace App\Models\HtpmsCustomer;
-
- use Exception;
- use Illuminate\Support\Facades\Config;
- use PDO;
-
- class HtpmsCustomerConnectionSwitch
- {
- public static function switch(int $customerId): void
- {
-
- if (!self::isEnable($customerId)) {
- throw new Exception("顧客切り替え不正");
- }
-
- $connectionsRoot = "database.connections";
- $connectionHtmsCustomer = "htpms_customer";
-
- $databaseNameKey = "{$connectionsRoot}.{$connectionHtmsCustomer}.database";
- $currentDatabaseName = config($databaseNameKey);
-
- $afterDatabaseName = "htpms_{$customerId}";
-
- if ($currentDatabaseName !== $afterDatabaseName) {
- Config::set($databaseNameKey, $afterDatabaseName);
- }
- }
-
- public static function switchToTemplate(): void
- {
- $connectionsRoot = "database.connections";
- $connectionHtmsCustomer = "htpms_customer";
-
- $databaseNameKey = "{$connectionsRoot}.{$connectionHtmsCustomer}.database";
- $currentDatabaseName = config($databaseNameKey);
-
- $afterDatabaseName = "htpms_template";
-
- if ($currentDatabaseName !== $afterDatabaseName) {
- Config::set($databaseNameKey, $afterDatabaseName);
- }
- }
-
- public static function isEnable(int $customerId): bool
- {
- $dsn = sprintf(
- 'pgsql:dbname=htpms_%d host=%s port=%d',
- $customerId,
- config("database.connections.htpms_customer.host"),
- config("database.connections.htpms_customer.port"),
- );
- $user = config("database.connections.htpms_customer.username");
- $password = config("database.connections.htpms_customer.password");
- try {
- new PDO($dsn, $user, $password);
- } catch (Exception $e) {
- return false;
- }
-
- return true;
- }
- }
|