Driver.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. <?php
  2. namespace Doctrine\DBAL\Driver\PDOSqlsrv;
  3. use Doctrine\DBAL\Driver\AbstractSQLServerDriver;
  4. use function is_int;
  5. use function sprintf;
  6. /**
  7. * The PDO-based Sqlsrv driver.
  8. */
  9. class Driver extends AbstractSQLServerDriver
  10. {
  11. /**
  12. * {@inheritdoc}
  13. */
  14. public function connect(array $params, $username = null, $password = null, array $driverOptions = [])
  15. {
  16. [$driverOptions, $connectionOptions] = $this->splitOptions($driverOptions);
  17. return new Connection(
  18. $this->_constructPdoDsn($params, $connectionOptions),
  19. $username,
  20. $password,
  21. $driverOptions
  22. );
  23. }
  24. /**
  25. * Constructs the Sqlsrv PDO DSN.
  26. *
  27. * @param mixed[] $params
  28. * @param string[] $connectionOptions
  29. *
  30. * @return string The DSN.
  31. */
  32. private function _constructPdoDsn(array $params, array $connectionOptions)
  33. {
  34. $dsn = 'sqlsrv:server=';
  35. if (isset($params['host'])) {
  36. $dsn .= $params['host'];
  37. }
  38. if (isset($params['port']) && ! empty($params['port'])) {
  39. $dsn .= ',' . $params['port'];
  40. }
  41. if (isset($params['dbname'])) {
  42. $connectionOptions['Database'] = $params['dbname'];
  43. }
  44. if (isset($params['MultipleActiveResultSets'])) {
  45. $connectionOptions['MultipleActiveResultSets'] = $params['MultipleActiveResultSets'] ? 'true' : 'false';
  46. }
  47. return $dsn . $this->getConnectionOptionsDsn($connectionOptions);
  48. }
  49. /**
  50. * Separates a connection options from a driver options
  51. *
  52. * @param int[]|string[] $options
  53. *
  54. * @return int[][]|string[][]
  55. */
  56. private function splitOptions(array $options) : array
  57. {
  58. $driverOptions = [];
  59. $connectionOptions = [];
  60. foreach ($options as $optionKey => $optionValue) {
  61. if (is_int($optionKey)) {
  62. $driverOptions[$optionKey] = $optionValue;
  63. } else {
  64. $connectionOptions[$optionKey] = $optionValue;
  65. }
  66. }
  67. return [$driverOptions, $connectionOptions];
  68. }
  69. /**
  70. * Converts a connection options array to the DSN
  71. *
  72. * @param string[] $connectionOptions
  73. */
  74. private function getConnectionOptionsDsn(array $connectionOptions) : string
  75. {
  76. $connectionOptionsDsn = '';
  77. foreach ($connectionOptions as $paramName => $paramValue) {
  78. $connectionOptionsDsn .= sprintf(';%s=%s', $paramName, $paramValue);
  79. }
  80. return $connectionOptionsDsn;
  81. }
  82. /**
  83. * {@inheritdoc}
  84. */
  85. public function getName()
  86. {
  87. return 'pdo_sqlsrv';
  88. }
  89. }