EasyConnectString.php 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121
  1. <?php
  2. declare(strict_types=1);
  3. namespace Doctrine\DBAL\Driver\AbstractOracleDriver;
  4. use function implode;
  5. use function is_array;
  6. use function sprintf;
  7. /**
  8. * Represents an Oracle Easy Connect string
  9. *
  10. * @link https://docs.oracle.com/database/121/NETAG/naming.htm
  11. */
  12. final class EasyConnectString
  13. {
  14. /** @var string */
  15. private $string;
  16. private function __construct(string $string)
  17. {
  18. $this->string = $string;
  19. }
  20. public function __toString(): string
  21. {
  22. return $this->string;
  23. }
  24. /**
  25. * Creates the object from an array representation
  26. *
  27. * @param mixed[] $params
  28. */
  29. public static function fromArray(array $params): self
  30. {
  31. return new self(self::renderParams($params));
  32. }
  33. /**
  34. * Creates the object from the given DBAL connection parameters.
  35. *
  36. * @param mixed[] $params
  37. */
  38. public static function fromConnectionParameters(array $params): self
  39. {
  40. if (! empty($params['connectstring'])) {
  41. return new self($params['connectstring']);
  42. }
  43. if (empty($params['host'])) {
  44. return new self($params['dbname'] ?? '');
  45. }
  46. $connectData = [];
  47. if (isset($params['servicename']) || isset($params['dbname'])) {
  48. $serviceKey = 'SID';
  49. if (! empty($params['service'])) {
  50. $serviceKey = 'SERVICE_NAME';
  51. }
  52. $serviceName = $params['servicename'] ?? $params['dbname'];
  53. $connectData[$serviceKey] = $serviceName;
  54. }
  55. if (! empty($params['instancename'])) {
  56. $connectData['INSTANCE_NAME'] = $params['instancename'];
  57. }
  58. if (! empty($params['pooled'])) {
  59. $connectData['SERVER'] = 'POOLED';
  60. }
  61. return self::fromArray([
  62. 'DESCRIPTION' => [
  63. 'ADDRESS' => [
  64. 'PROTOCOL' => 'TCP',
  65. 'HOST' => $params['host'],
  66. 'PORT' => $params['port'] ?? 1521,
  67. ],
  68. 'CONNECT_DATA' => $connectData,
  69. ],
  70. ]);
  71. }
  72. /**
  73. * @param mixed[] $params
  74. */
  75. private static function renderParams(array $params): string
  76. {
  77. $chunks = [];
  78. foreach ($params as $key => $value) {
  79. $string = self::renderValue($value);
  80. if ($string === '') {
  81. continue;
  82. }
  83. $chunks[] = sprintf('(%s=%s)', $key, $string);
  84. }
  85. return implode('', $chunks);
  86. }
  87. /**
  88. * @param mixed $value
  89. */
  90. private static function renderValue($value): string
  91. {
  92. if (is_array($value)) {
  93. return self::renderParams($value);
  94. }
  95. return (string) $value;
  96. }
  97. }