Dsn.php 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. <?php
  2. namespace common\helpers;
  3. use yii\base\BaseObject;
  4. class Dsn extends BaseObject {
  5. public $dsn;
  6. public $sheme;
  7. protected $defaultHostKey = 'host';
  8. protected $defaultDatabaseKey = 'dbname';
  9. protected $parseDsn = [
  10. 'host' => null,
  11. 'port' => null,
  12. 'database' => null
  13. ];
  14. protected $path;
  15. protected $parse_url;
  16. protected $defaultPort;
  17. public function init()
  18. {
  19. parent::init();
  20. if(is_null($this->parse_url))
  21. $this->parse_url = parse_url($this->dsn);
  22. $this->path = $this->parse_url['path'];
  23. $this->parseDsn();
  24. }
  25. public static function parse($dsn)
  26. {
  27. $scheme = substr($dsn, 0, strpos($dsn, ':'));
  28. if (strpos($dsn, '+')) {
  29. $dsn = substr($dsn, 0, strpos($dsn, '+'));
  30. }
  31. if (!$dsn) {
  32. throw new \Exception(sprintf('The url \'%s\' could not be parsed', $dsn));
  33. }
  34. $className = __NAMESPACE__ . '\\Dsn\\' . ucfirst($scheme) . 'Dsn';
  35. return new $className([
  36. 'dsn' => $dsn,
  37. 'sheme' => $scheme
  38. ]);
  39. }
  40. protected function parseDsn() {
  41. $data = $this->path;
  42. $array = array_map(
  43. function ($_) {
  44. return explode('=', $_);
  45. },
  46. explode(';', $data)
  47. );
  48. if (count($array) > 1) {
  49. $parseArray = [];
  50. foreach ($array as $index => $element) {
  51. $parseArray[$element[0]] = $element[1];
  52. }
  53. $this->parseDsn = [
  54. 'host' => $parseArray[$this->defaultHostKey],
  55. 'port' => $parseArray['port'] ? $parseArray['port'] : $this->defaultPort,
  56. 'database' => $parseArray[$this->defaultDatabaseKey]
  57. ];
  58. return true;
  59. }
  60. $this->parseDsn = [
  61. 'host' => $this->parse_url[$this->defaultHostKey],
  62. 'port' => $this->parse_url['port'] ? $this->parse_url['port'] : $this->defaultPort,
  63. 'database' => basename($this->dsn)
  64. ];
  65. return true;
  66. }
  67. public function getParseDsn() {
  68. return $this->parseDsn;
  69. }
  70. public function getDatabase() {
  71. return $this->parseDsn['database'];
  72. }
  73. public function getHost() {
  74. return $this->parseDsn['host'];
  75. }
  76. public function getPort() {
  77. return $this->parseDsn['port'];
  78. }
  79. }