Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[FEATURE] Add support for DB_URL #184

Draft
wants to merge 2 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
74 changes: 0 additions & 74 deletions adapters/Doctrine/DBAL/ConnectionFactory.php

This file was deleted.

40 changes: 40 additions & 0 deletions adapters/Doctrine/DBAL/Factory/ConnectionFactory.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
<?php

namespace Liuggio\Fastest\Doctrine\DBAL\Factory;

use Doctrine\Bundle\DoctrineBundle\ConnectionFactory as BaseConnectionFactory;
use Liuggio\Fastest\Process\EnvCommandCreator;

class ConnectionFactory extends BaseConnectionFactory
{
protected const CONNECTION_STRING_PATTERNS = [
'sql' => '/(?P<protocol>^(mysql|postgresql))\:\/\/(?P<user>.+)?\:(?P<password>.+)'.
'?\@(?P<host>.+)\:(?P<port>\d{4})\/(?P<database>.+)\?(?P<parameters>[a-zA-Z].+=.+&?)/',
'sqlite' => '/(?P<protocol>^(sqlite))\:\/\/(\%kernel\..+\%|.+)(?P<database>.*\.db$)/',
];

protected function getDbNameFromEnv(string $dbName): string
{
if ($this->issetDbNameEnvValue()) {
return preg_match('/\d$/m', $dbName)
? $dbName.'_test'
: $dbName.'_'.$this->getDbNameEnvValue();
}

return $dbName;
}

protected function issetDbNameEnvValue(): bool
{
$dbName = $this->getDbNameEnvValue();

return !empty($dbName);
}

protected function getDbNameEnvValue(): ?string
{
$dbName = getenv(EnvCommandCreator::ENV_TEST_CHANNEL_READABLE);

return is_string($dbName) ? $dbName : null;
}
}
126 changes: 126 additions & 0 deletions adapters/Doctrine/DBAL/Factory/SqlConnectionFactory.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
<?php

namespace Liuggio\Fastest\Doctrine\DBAL\Factory;

use Doctrine\Common\EventManager;
use Doctrine\DBAL\Configuration;
use Doctrine\DBAL\Connection;
use Doctrine\DBAL\Exception;
use InvalidArgumentException;

class SqlConnectionFactory extends ConnectionFactory
{
private const DSN_TEMPLATE = '{{PROTOCOL}}://{{USER}}:{{PASSWORD}}@{{HOST}}:{{PORT}}/{{DB}}?{{PARAMS}}';

private const DEFAULT_PORTS = [
'mysql' => 3306,
'postgresql' => 5432,
];

private const PARAMS_LIST = [
'default' => [
'driver',
'host',
'port',
'user',
'password',
'charset',
],
'dsn' => ['url', 'dbname'],
];

/**
* @throws Exception
*/
public function createConnection(
array $params,
Configuration $config = null,
EventManager $eventManager = null,
array $mappingTypes = []
): Connection {

if ($this->isMasterSlaveOrUnique($params)) {
$originalDatabaseName = $params['master']['dbname'] ?? $params['dbname'] ?? null;
$params['dbname'] = $originalDatabaseName ? $this->getDbNameFromEnv($originalDatabaseName) : null;
$params = $this->prepareParamsByConnectionType($params);

return parent::createConnection($params, $config, $eventManager, $mappingTypes);
}

if ($this->isDsn($params)) {
[$dsn, $databaseName] = $this->getCompiledDsn($params);

$params['url'] = $dsn;
$params['dbname'] = $this->getDbNameFromEnv($databaseName);
$params = $this->prepareParamsByConnectionType($params);

return parent::createConnection($params, $config, $eventManager, $mappingTypes);
}

return parent::createConnection($params, $config, $eventManager, $mappingTypes);
}

private function isDsn(array $params): bool
{
return !empty($params['url']) && preg_match_all(self::CONNECTION_STRING_PATTERNS['sql'], $params['url']);
}

private function isMasterSlaveOrUnique(array $params): bool
{
return isset($params['master']['dbname']) || isset($params['dbname']);
}

private function getCompiledDsn(array $params = []): array
{
[$protocol, $user, $password, $databaseName, $host, $port, $parameters] = $this->getInfoFromDsn($params);

$dsn = str_replace(
['{{PROTOCOL}}', '{{USER}}', '{{PASSWORD}}', '{{HOST}}', ':{{PORT}}', '{{DB}}', '?{{PARAMS}}'],
[
$protocol,
$user,
$password,
$host,
$port ? ":$port" : ':'.self::DEFAULT_PORTS[$protocol],
$databaseName,
$parameters ? "?$parameters" : '',
],
self::DSN_TEMPLATE
);

return [$dsn, $databaseName];
}

private function getInfoFromDsn(array $params): array
{
$dsn = preg_match(self::CONNECTION_STRING_PATTERNS['sql'], $params['url'] ?? '', $dsnPieces);

$isValidDsn = $dsn
&& !empty($dsnPieces['protocol'])
&& !empty($dsnPieces['user'])
&& !empty($dsnPieces['password'])
&& !empty($dsnPieces['database'])
&& !empty($dsnPieces['host']);

if ($isValidDsn) {
return [
$dsnPieces['protocol'],
$dsnPieces['user'],
$dsnPieces['password'],
$dsnPieces['database'],
$dsnPieces['host'],
$dsnPieces['port'] ?? null,
$dsnPieces['parameters'] ?? null,
];
}

throw new InvalidArgumentException(sprintf('Unable to get database name from DSN <%s>', $params['url'] ?? ''));
}

private function prepareParamsByConnectionType(array $params, string $connectionType = 'default'): array
{
$paramsList = self::PARAMS_LIST[$connectionType];

return array_diff_key($params, array_flip($paramsList));
}
}
4 changes: 3 additions & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,9 @@
"require-dev": {
"behat/behat": "^3.6",
"phpstan/phpstan": "^0.12.99",
"phpstan/phpstan-phpunit": "^0.12.22"
"phpstan/phpstan-phpunit": "^0.12.22",
"phpunit/phpunit": "^9.5",
"doctrine/doctrine-bundle": "^2.7"
},
"config": {
"bin-dir": "bin/"
Expand Down