2
0

DSNParser.php 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. <?php
  2. namespace PhpDevCommunity\PaperORM\Parser;
  3. final class DSNParser
  4. {
  5. public static function parse(string $dsn): array
  6. {
  7. if (str_starts_with($dsn, 'sqlite:')) {
  8. $rest = substr($dsn, 7);
  9. $memory = false;
  10. $options = [];
  11. if (str_contains($rest, '?')) {
  12. [$path, $query] = explode('?', $rest, 2);
  13. parse_str($query, $options);
  14. } else {
  15. $path = $rest;
  16. }
  17. $path = ltrim($path, '/');
  18. if ($path === '' || $path === 'memory' || $path === ':memory:') {
  19. $memory = true;
  20. $path = null;
  21. } elseif (str_starts_with($rest, '///')) {
  22. $path = '/' . $path;
  23. }
  24. return [
  25. 'driver' => 'sqlite',
  26. 'path' => $path,
  27. 'memory' => $memory,
  28. 'options' => $options,
  29. ];
  30. }
  31. $params = parse_url($dsn);
  32. if ($params === false) {
  33. throw new \InvalidArgumentException("Unable to parse DSN: $dsn");
  34. }
  35. $options = [];
  36. if (isset($params['query'])) {
  37. parse_str($params['query'], $options);
  38. unset($params['query']);
  39. }
  40. $driver = $params['scheme'] ?? null;
  41. $host = $params['host'] ?? null;
  42. $port = isset($params['port']) ? (int) $params['port'] : null;
  43. $user = $params['user'] ?? null;
  44. $password = $params['pass'] ?? null;
  45. $path = $params['path'] ?? null;
  46. if ($path !== null && $path[0] === '/') {
  47. $path = substr($path, 1);
  48. }
  49. $isMemory = ($path === 'memory' || $path === ':memory:');
  50. return [
  51. 'driver' => $driver,
  52. 'host' => $host,
  53. 'port' => $port,
  54. 'user' => $user,
  55. 'password' => $password,
  56. 'path' => $path,
  57. 'memory' => $isMemory,
  58. 'options' => $options
  59. ];
  60. }
  61. }