Make ConnectionConfig an abstract value class

This commit is contained in:
Aaron Piotrowski 2018-07-13 10:15:09 -05:00
parent b370f6b232
commit 97b10e4361
No known key found for this signature in database
GPG Key ID: ADD1EF783EDE9EEB

View File

@ -2,7 +2,146 @@
namespace Amp\Sql;
interface ConnectionConfig
abstract class ConnectionConfig
{
public function connectionString(): string;
/** @var string */
private $host;
/** @var int */
private $port;
/** @var string|null */
private $user;
/** @var string|null */
private $password;
/** @var string|null */
private $database;
/**
* Parses a connection string into an array of keys and values given.
*
* @param string $connectionString
*
* @return array
*/
protected static function parseConnectionString(string $connectionString): array
{
$values = [];
$params = \explode(";", $connectionString);
if (\count($params) === 1) { // Attempt to explode on a space if no ';' are found.
$params = \explode(" ", $connectionString);
}
foreach ($params as $param) {
list($key, $value) = \array_map("trim", \explode("=", $param, 2) + [1 => null]);
$values[$key] = $value;
}
return $values;
}
public function __construct(string $host, int $port, string $user = null, string $password = null, string $database = null)
{
$this->host = $host;
$this->port = $port;
$this->user = $user;
$this->password = $password;
$this->database = $database;
}
public function getConnectionString(): string
{
$chunks = [
"host=" . $this->host,
"port=" . $this->port,
];
if ($this->user !== null) {
$chunks[] = "user=" . $this->user;
}
if ($this->password !== null) {
$chunks[] = "password=" . $this->password;
}
if ($this->database !== null) {
$chunks[] = "db=" . $this->database;
}
return \implode(" ", $chunks);
}
final public function getHost(): string
{
return $this->host;
}
final public function withHost(string $host): self
{
$new = clone $this;
$new->host = $host;
return $new;
}
final public function getPort(): int
{
return $this->port;
}
final public function withPort(int $port): self
{
$new = clone $this;
$new->port = $port;
return $new;
}
/**
* @return string|null
*/
final public function getUser() /* : ?string */
{
return $this->user;
}
final public function withUser(string $user = null): self
{
$new = clone $this;
$new->user = $user;
return $new;
}
/**
* @return string|null
*/
final public function getPassword() /* : ?string */
{
return $this->password;
}
final public function withPassword(string $password = null): self
{
$new = clone $this;
$new->password = $password;
return $new;
}
/**
* @return string|null
*/
final public function getDatabase() /* : ?string */
{
return $this->database;
}
final public function withDatabase(string $database = null): self
{
$new = clone $this;
$new->database = $database;
return $new;
}
}