Driver.php 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. <?php
  2. namespace Doctrine\DBAL\Driver\SQLAnywhere;
  3. use Doctrine\DBAL\DBALException;
  4. use Doctrine\DBAL\Driver\AbstractSQLAnywhereDriver;
  5. use function array_keys;
  6. use function array_map;
  7. use function implode;
  8. /**
  9. * A Doctrine DBAL driver for the SAP Sybase SQL Anywhere PHP extension.
  10. */
  11. class Driver extends AbstractSQLAnywhereDriver
  12. {
  13. /**
  14. * {@inheritdoc}
  15. *
  16. * @throws DBALException If there was a problem establishing the connection.
  17. */
  18. public function connect(array $params, $username = null, $password = null, array $driverOptions = [])
  19. {
  20. try {
  21. return new SQLAnywhereConnection(
  22. $this->buildDsn(
  23. $params['host'] ?? null,
  24. $params['port'] ?? null,
  25. $params['server'] ?? null,
  26. $params['dbname'] ?? null,
  27. $username,
  28. $password,
  29. $driverOptions
  30. ),
  31. $params['persistent'] ?? false
  32. );
  33. } catch (SQLAnywhereException $e) {
  34. throw DBALException::driverException($this, $e);
  35. }
  36. }
  37. /**
  38. * {@inheritdoc}
  39. */
  40. public function getName()
  41. {
  42. return 'sqlanywhere';
  43. }
  44. /**
  45. * Build the connection string for given connection parameters and driver options.
  46. *
  47. * @param string $host Host address to connect to.
  48. * @param int $port Port to use for the connection (default to SQL Anywhere standard port 2638).
  49. * @param string $server Database server name on the host to connect to.
  50. * SQL Anywhere allows multiple database server instances on the same host,
  51. * therefore specifying the server instance name to use is mandatory.
  52. * @param string $dbname Name of the database on the server instance to connect to.
  53. * @param string $username User name to use for connection authentication.
  54. * @param string $password Password to use for connection authentication.
  55. * @param mixed[] $driverOptions Additional parameters to use for the connection.
  56. *
  57. * @return string
  58. */
  59. private function buildDsn($host, $port, $server, $dbname, $username = null, $password = null, array $driverOptions = [])
  60. {
  61. $host = $host ?: 'localhost';
  62. $port = $port ?: 2638;
  63. if (! empty($server)) {
  64. $server = ';ServerName=' . $server;
  65. }
  66. return 'HOST=' . $host . ':' . $port .
  67. $server .
  68. ';DBN=' . $dbname .
  69. ';UID=' . $username .
  70. ';PWD=' . $password .
  71. ';' . implode(
  72. ';',
  73. array_map(static function ($key, $value) {
  74. return $key . '=' . $value;
  75. }, array_keys($driverOptions), $driverOptions)
  76. );
  77. }
  78. }