Skip to content

[dbal] Add DSN support. #104

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

Merged
merged 5 commits into from
May 26, 2017
Merged
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
1 change: 1 addition & 0 deletions docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ services:
- './:/mqdev'
environment:
- AMQP_DSN=amqp://guest:guest@rabbitmq:5672/mqdev
- DOCTINE_DSN=mysql://root:rootpass@mysql/mqdev
- SYMFONY__RABBITMQ__HOST=rabbitmq
- SYMFONY__RABBITMQ__USER=guest
- SYMFONY__RABBITMQ__PASSWORD=guest
Expand Down
72 changes: 65 additions & 7 deletions pkg/dbal/DbalConnectionFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,21 +19,33 @@ class DbalConnectionFactory implements PsrConnectionFactory
private $connection;

/**
* The config could be an array, string DSN or null. In case of null it will attempt to connect to mysql localhost with default credentials.
*
* $config = [
* 'connection' => [] - dbal connection options. see http://docs.doctrine-project.org/projects/doctrine-dbal/en/latest/reference/configuration.html
* 'table_name' => 'enqueue', - database table name.
* 'polling_interval' => '1000', - How often query for new messages (milliseconds)
* 'lazy' => true, - Use lazy database connection (boolean)
* ].
* ]
*
* or
*
* mysql://user:pass@localhost:3606/db?charset=UTF-8
*
* @param $config
* @param array|string|null $config
*/
public function __construct(array $config = [])
public function __construct($config = 'mysql://')
{
$this->config = array_replace([
'connection' => [],
'lazy' => true,
], $config);
if (empty($config)) {
$config = $this->parseDsn('mysql://');
} elseif (is_string($config)) {
$config = $this->parseDsn($config);
} elseif (is_array($config)) {
} else {
throw new \LogicException('The config must be either an array of options, a DSN string or null');
}

$this->config = $config;
}

/**
Expand Down Expand Up @@ -74,4 +86,50 @@ private function establishConnection()

return $this->connection;
}

/**
* @param string $dsn
*
* @return array
*/
private function parseDsn($dsn)
{
if (false === strpos($dsn, '://')) {
throw new \LogicException(sprintf('The given DSN "%s" is not valid. Must contain "://".', $dsn));
}

list($schema, $rest) = explode('://', $dsn, 2);

$supported = [
'db2' => true,
'ibm_db2' => true,
'mssql' => true,
'pdo_sqlsrv' => true,
'mysql' => true,
'mysql2' => true,
'pdo_mysql' => true,
'pgsql' => true,
'postgres' => true,
'postgresql' => true,
'pdo_pgsql' => true,
'sqlite' => true,
'sqlite3' => true,
'pdo_sqlite' => true,
];

if (false == isset($supported[$schema])) {
throw new \LogicException(sprintf(
'The given DSN schema "%s" is not supported. There are supported schemes: "%s".',
$schema,
implode('", "', array_keys($supported))
));
}

return [
'lazy' => true,
'connection' => [
'url' => empty($rest) ? $schema.'://root@localhost' : $dsn,
],
];
}
}
6 changes: 5 additions & 1 deletion pkg/dbal/DbalContext.php
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,11 @@ public function __construct($connection, array $config = [])
} elseif (is_callable($connection)) {
$this->connectionFactory = $connection;
} else {
throw new \InvalidArgumentException('The connection argument must be either Doctrine\DBAL\Connection or callable that returns Doctrine\DBAL\Connection.');
throw new \InvalidArgumentException(sprintf(
'The connection argument must be either %s or callable that returns %s.',
Connection::class,
Connection::class
));
}
}

Expand Down
12 changes: 12 additions & 0 deletions pkg/dbal/Symfony/DbalTransportFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,16 @@ public function __construct($name = 'dbal')
public function addConfiguration(ArrayNodeDefinition $builder)
{
$builder
->beforeNormalization()
->ifString()
->then(function ($v) {
return ['dsn' => $v];
})
->end()
->children()
->scalarNode('dsn')
->info('The Doctrine DBAL DSN. Other parameters are ignored if set')
->end()
->variableNode('connection')
->treatNullLike([])
->info('Doctrine DBAL connection options. See http://docs.doctrine-project.org/projects/doctrine-dbal/en/latest/reference/configuration.html')
Expand Down Expand Up @@ -66,6 +75,9 @@ public function createConnectionFactory(ContainerBuilder $container, array $conf
if (false == empty($config['dbal_connection_name'])) {
$factory = new Definition(ManagerRegistryConnectionFactory::class);
$factory->setArguments([new Reference('doctrine'), $config]);
} elseif (false == empty($config['dsn'])) {
$factory = new Definition(DbalConnectionFactory::class);
$factory->setArguments([$config['dsn']]);
} elseif (false == empty($config['connection'])) {
$factory = new Definition(DbalConnectionFactory::class);
$factory->setArguments([$config]);
Expand Down
110 changes: 110 additions & 0 deletions pkg/dbal/Tests/DbalConnectionFactoryConfigTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
<?php

namespace Enqueue\Dbal\Tests;

use Enqueue\Dbal\DbalConnectionFactory;
use Enqueue\Test\ClassExtensionTrait;
use PHPUnit\Framework\TestCase;

/**
* The class contains the factory tests dedicated to configuration.
*/
class DbalConnectionFactoryConfigTest extends TestCase
{
use ClassExtensionTrait;

public function testThrowNeitherArrayStringNorNullGivenAsConfig()
{
$this->expectException(\LogicException::class);
$this->expectExceptionMessage('The config must be either an array of options, a DSN string or null');

new DbalConnectionFactory(new \stdClass());
}

public function testThrowIfSchemeIsNotSupported()
{
$this->expectException(\LogicException::class);
$this->expectExceptionMessage('The given DSN schema "http" is not supported. There are supported schemes: "db2", "ibm_db2", "mssql", "pdo_sqlsrv", "mysql", "mysql2", "pdo_mysql", "pgsql", "postgres", "postgresql", "pdo_pgsql", "sqlite", "sqlite3", "pdo_sqlite"');

new DbalConnectionFactory('http://example.com');
}

public function testThrowIfDsnCouldNotBeParsed()
{
$this->expectException(\LogicException::class);
$this->expectExceptionMessage('The given DSN "invalidDSN" is not valid. Must contain "://".');

new DbalConnectionFactory('invalidDSN');
}

/**
* @dataProvider provideConfigs
*
* @param mixed $config
* @param mixed $expectedConfig
*/
public function testShouldParseConfigurationAsExpected($config, $expectedConfig)
{
$factory = new DbalConnectionFactory($config);

$this->assertAttributeEquals($expectedConfig, 'config', $factory);
}

public static function provideConfigs()
{
yield [
null,
[
'lazy' => true,
'connection' => [
'url' => 'mysql://root@localhost',
],
],
];

yield [
'mysql://',
[
'lazy' => true,
'connection' => [
'url' => 'mysql://root@localhost',
],
],
];

yield [
'pgsql://',
[
'lazy' => true,
'connection' => [
'url' => 'pgsql://root@localhost',
],
],
];

yield [
'mysql://user:pass@host:10000/db',
[
'lazy' => true,
'connection' => [
'url' => 'mysql://user:pass@host:10000/db',
],
],
];

yield [
[],
[
'lazy' => true,
'connection' => [
'url' => 'mysql://root@localhost',
],
],
];

yield [
['table_name' => 'a_queue_table', 'connection' => ['foo' => 'fooVal', 'bar' => 'barVal']],
['table_name' => 'a_queue_table', 'connection' => ['foo' => 'fooVal', 'bar' => 'barVal']],
];
}
}
2 changes: 1 addition & 1 deletion pkg/dbal/Tests/DbalConnectionFactoryTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ public function testCouldBeConstructedWithEmptyConfiguration()

$this->assertAttributeEquals([
'lazy' => true,
'connection' => [],
'connection' => ['url' => 'mysql://root@localhost'],
], 'config', $factory);
}

Expand Down
39 changes: 39 additions & 0 deletions pkg/dbal/Tests/Symfony/DbalTransportFactoryTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,25 @@ public function testShouldAllowAddConfiguration()
], $config);
}

public function testShouldAllowAddConfigurationAsString()
{
$transport = new DbalTransportFactory();
$tb = new TreeBuilder();
$rootNode = $tb->root('foo');

$transport->addConfiguration($rootNode);
$processor = new Processor();
$config = $processor->process($tb->buildTree(), ['mysqlDSN']);

$this->assertEquals([
'dsn' => 'mysqlDSN',
'dbal_connection_name' => null,
'table_name' => 'enqueue',
'polling_interval' => 1000,
'lazy' => true,
], $config);
}

public function testShouldCreateDbalConnectionFactory()
{
$container = new ContainerBuilder();
Expand Down Expand Up @@ -89,6 +108,26 @@ public function testShouldCreateDbalConnectionFactory()
], $factory->getArgument(0));
}

public function testShouldCreateConnectionFactoryFromDsnString()
{
$container = new ContainerBuilder();

$transport = new DbalTransportFactory();

$serviceId = $transport->createConnectionFactory($container, [
'dsn' => 'theDSN',
'connection' => [],
'lazy' => true,
'table_name' => 'enqueue',
'polling_interval' => 1000,
]);

$this->assertTrue($container->hasDefinition($serviceId));
$factory = $container->getDefinition($serviceId);
$this->assertEquals(DbalConnectionFactory::class, $factory->getClass());
$this->assertSame('theDSN', $factory->getArgument(0));
}

public function testShouldCreateManagerRegistryConnectionFactory()
{
$container = new ContainerBuilder();
Expand Down
4 changes: 2 additions & 2 deletions pkg/enqueue-bundle/DependencyInjection/EnqueueExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ public function load(array $configs, ContainerBuilder $container)
$this->factories[$name]->createDriver($container, $transportConfig);
}

if (false == isset($config['transport'][$config['transport']['default']['alias']])) {
if (isset($config['transport']['default']['alias']) && false == isset($config['transport'][$config['transport']['default']['alias']])) {
throw new \LogicException(sprintf('Transport is not enabled: %s', $config['transport']['default']['alias']));
}

Expand All @@ -82,7 +82,7 @@ public function load(array $configs, ContainerBuilder $container)
$config['client']['router_queue'],
$config['client']['default_processor_queue'],
$config['client']['router_processor'],
$config['transport'][$config['transport']['default']['alias']],
isset($config['transport']['default']['alias']) ? $config['transport'][$config['transport']['default']['alias']] : [],
]);

$container->setParameter('enqueue.client.router_queue_name', $config['client']['router_queue']);
Expand Down
5 changes: 5 additions & 0 deletions pkg/enqueue-bundle/Tests/Functional/App/CustomAppKernel.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
use Symfony\Bundle\FrameworkBundle\Kernel\MicroKernelTrait;
use Symfony\Component\Config\Loader\LoaderInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\HttpKernel\Kernel;
use Symfony\Component\Routing\RouteCollectionBuilder;

Expand All @@ -24,6 +25,10 @@ class CustomAppKernel extends Kernel

public function setEnqueueConfig(array $config)
{
$fs = new Filesystem();
$fs->remove(sys_get_temp_dir().'/EnqueueBundleCustom/cache');
$fs->mkdir(sys_get_temp_dir().'/EnqueueBundleCustom/cache');

$this->enqueueConfig = array_replace_recursive($this->enqueueConfig, $config);
}

Expand Down
Loading