Skip to content

Instantly share code, notes, and snippets.

@samsonasik
Last active January 31, 2018 13:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save samsonasik/e0b391a737baa7a7335715c63c8d23f9 to your computer and use it in GitHub Desktop.
Save samsonasik/e0b391a737baa7a7335715c63c8d23f9 to your computer and use it in GitHub Desktop.
<?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