You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

65 lines
1.8KB

  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 switchToTemplate(): void
  23. {
  24. $connectionsRoot = "database.connections";
  25. $connectionHtmsCustomer = "htpms_customer";
  26. $databaseNameKey = "{$connectionsRoot}.{$connectionHtmsCustomer}.database";
  27. $currentDatabaseName = config($databaseNameKey);
  28. $afterDatabaseName = "htpms_template";
  29. if ($currentDatabaseName !== $afterDatabaseName) {
  30. Config::set($databaseNameKey, $afterDatabaseName);
  31. }
  32. }
  33. public static function isEnable(int $customerId): bool
  34. {
  35. $dsn = sprintf(
  36. 'pgsql:dbname=htpms_%d host=%s port=%d',
  37. $customerId,
  38. config("database.connections.htpms_customer.host"),
  39. config("database.connections.htpms_customer.port"),
  40. );
  41. $user = config("database.connections.htpms_customer.username");
  42. $password = config("database.connections.htpms_customer.password");
  43. try {
  44. new PDO($dsn, $user, $password);
  45. } catch (Exception $e) {
  46. return false;
  47. }
  48. return true;
  49. }
  50. }