Skip to content

Commit

Permalink
Add sslmode to config
Browse files Browse the repository at this point in the history
  • Loading branch information
trowski committed May 2, 2020
1 parent 54186c9 commit 737f982
Show file tree
Hide file tree
Showing 2 changed files with 65 additions and 2 deletions.
49 changes: 47 additions & 2 deletions src/ConnectionConfig.php
Expand Up @@ -6,7 +6,19 @@

final class ConnectionConfig extends SqlConnectionConfig
{
const DEFAULT_PORT = 5432;
public const DEFAULT_PORT = 5432;

public const SSL_MODES = [
'disable',
'allow',
'prefer',
'require',
'verify-ca',
'verify-full',
];

/** @var string|null */
private $sslMode = null;

/** @var string|null */
private $string;
Expand All @@ -19,13 +31,19 @@ public static function fromString(string $connectionString): self
throw new \Error("Host must be provided in connection string");
}

return new self(
$config = new self(
$parts["host"],
(int) ($parts["port"] ?? self::DEFAULT_PORT),
$parts["user"] ?? null,
$parts["password"] ?? null,
$parts["db"] ?? null
);

if (isset($parts["sslmode"])) {
$config = $config->withSslMode($parts["sslmode"]);
}

return $config;
}

public function __construct(
Expand All @@ -43,6 +61,29 @@ public function __clone()
$this->string = null;
}

public function getSslMode(): ?string
{
return $this->sslMode;
}

public function withSslMode(string $mode): self
{
if (!\in_array($mode, self::SSL_MODES, true)) {
throw new \Error('Invalid SSL mode, must be one of: ' . \implode(', ', self::SSL_MODES));
}

$new = clone $this;
$new->sslMode = $mode;
return $new;
}

public function withoutSslMode(): self
{
$new = clone $this;
$new->sslMode = null;
return $new;
}

/**
* @return string Connection string used with ext-pgsql and pecl-pq.
*/
Expand Down Expand Up @@ -72,6 +113,10 @@ public function getConnectionString(): string
$chunks[] = "dbname=" . $database;
}

if ($this->sslMode !== null) {
$chunks[] = "sslmode=" . $this->sslMode;
}

return $this->string = \implode(" ", $chunks);
}
}
18 changes: 18 additions & 0 deletions test/ConnectionConfigTest.php
Expand Up @@ -42,4 +42,22 @@ public function testInvalidString(): void
$this->expectExceptionMessage("Host must be provided in connection string");
$config = ConnectionConfig::fromString("invalid connection string");
}

public function testSslMode(): void
{
$config = ConnectionConfig::fromString("host=localhost sslmode=verify-ca");
$this->assertSame('verify-ca', $config->getSslMode());

$altered = $config->withoutSslMode();
$this->assertNull($altered->getSslMode());
$this->assertSame('verify-ca', $config->getSslMode());

$altered = $altered->withSslMode('allow');
$this->assertSame('allow', $altered->getSslMode());

$this->expectException(\Error::class);
$this->expectExceptionMessage('Invalid SSL mode');

$config->withSslMode('invalid');
}
}

0 comments on commit 737f982

Please sign in to comment.