Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.

50 lines
1.3KB

  1. <?php
  2. namespace App\Models\HtpmsCustomer;
  3. use Exception;
  4. use Illuminate\Support\Facades\Config;
  5. use PDO;
  6. class HtpmsCustomerConnectionSwitch
  7. {
  8. public static function switch(int $customerId): void
  9. {
  10. if (!self::isEnable($customerId)) {
  11. throw new Exception("顧客切り替え不正");
  12. }
  13. $connectionsRoot = "database.connections";
  14. $connectionHtmsCustomer = "htpms_customer";
  15. $databaseNameKey = "{$connectionsRoot}.{$connectionHtmsCustomer}.database";
  16. $currentDatabaseName = config($databaseNameKey);
  17. $afterDatabaseName = "htpms_{$customerId}";
  18. if ($currentDatabaseName !== $afterDatabaseName) {
  19. Config::set($databaseNameKey, $afterDatabaseName);
  20. }
  21. }
  22. public static function isEnable(int $customerId): bool
  23. {
  24. $dsn = sprintf(
  25. 'pgsql:dbname=htpms_%d host=%s port=%d',
  26. $customerId,
  27. config("database.connections.htpms_customer.host"),
  28. config("database.connections.htpms_customer.port"),
  29. );
  30. $user = config("database.connections.htpms_customer.username");
  31. $password = config("database.connections.htpms_customer.password");
  32. try {
  33. new PDO($dsn, $user, $password);
  34. } catch (Exception $e) {
  35. return false;
  36. }
  37. return true;
  38. }
  39. }