Last active
January 31, 2018 13:50
-
-
Save samsonasik/e0b391a737baa7a7335715c63c8d23f9 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class DsnReader | |
{ | |
private $dsn; | |
public function __construct($dsn) | |
{ | |
$this->dsn = $dsn; | |
} | |
public function getDsnValue($element) | |
{ | |
list($value) = explode(';', substr($this->dsn, strpos($this->dsn, $element) + strlen($element) + 1)); | |
if (false !== strpos($value, '=') || ! $value) { | |
throw new \InvalidArgumentException(sprintf( | |
'element "%s" not found in the dsn string', | |
$element | |
)); | |
} | |
return $value; | |
} | |
public function getScheme() | |
{ | |
$scheme = strstr($this->dsn, ':', true) . ':'; | |
if (! $scheme) { | |
throw new \InvalidArgumentException( | |
'scheme not found in the dsn string' | |
); | |
} | |
return $scheme; | |
} | |
public function extract() | |
{ | |
$data = []; | |
$data['scheme'] = $this->getScheme(); | |
$lists = explode(';', substr($this->dsn, strlen($data['scheme']))); | |
if (empty($lists[1])) { | |
throw new \InvalidArgumentException( | |
'no dsn element found' | |
); | |
} | |
foreach ($lists as $val) { | |
list($element, $value) = explode('=', $val); | |
$data[$element] = $value; | |
} | |
return $data; | |
} | |
} | |
$dsn = new DsnReader('mysql:dbname=foo;host=localhost;port=3306'); | |
echo $dsn->getDsnValue('dbname') . PHP_EOL; | |
echo $dsn->getDsnValue('host') . PHP_EOL; | |
echo $dsn->getDsnValue('port') . PHP_EOL; | |
var_dump($dsn->extract()); echo PHP_EOL; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment