DataSourceName.php 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. <?php
  2. declare(strict_types=1);
  3. namespace Doctrine\DBAL\Driver\IBMDB2;
  4. use function implode;
  5. use function sprintf;
  6. use function strpos;
  7. /**
  8. * IBM DB2 DSN
  9. */
  10. final class DataSourceName
  11. {
  12. /** @var string */
  13. private $string;
  14. private function __construct(string $string)
  15. {
  16. $this->string = $string;
  17. }
  18. public function toString(): string
  19. {
  20. return $this->string;
  21. }
  22. /**
  23. * Creates the object from an array representation
  24. *
  25. * @param array<string,mixed> $params
  26. */
  27. public static function fromArray(array $params): self
  28. {
  29. $chunks = [];
  30. foreach ($params as $key => $value) {
  31. $chunks[] = sprintf('%s=%s', $key, $value);
  32. }
  33. return new self(implode(';', $chunks));
  34. }
  35. /**
  36. * Creates the object from the given DBAL connection parameters.
  37. *
  38. * @param array<string,mixed> $params
  39. */
  40. public static function fromConnectionParameters(array $params): self
  41. {
  42. if (isset($params['dbname']) && strpos($params['dbname'], '=') !== false) {
  43. return new self($params['dbname']);
  44. }
  45. $dsnParams = [];
  46. foreach (
  47. [
  48. 'host' => 'HOSTNAME',
  49. 'port' => 'PORT',
  50. 'protocol' => 'PROTOCOL',
  51. 'dbname' => 'DATABASE',
  52. 'user' => 'UID',
  53. 'password' => 'PWD',
  54. ] as $dbalParam => $dsnParam
  55. ) {
  56. if (! isset($params[$dbalParam])) {
  57. continue;
  58. }
  59. $dsnParams[$dsnParam] = $params[$dbalParam];
  60. }
  61. return self::fromArray($dsnParams);
  62. }
  63. }