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

More connections #24

Open
wants to merge 21 commits into
base: master
Choose a base branch
from
Open
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
2 changes: 1 addition & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
],
"require": {
"php": ">=7.1",
"nette/di": "~2.4.15",
"nette/di": "~2.4.15 || ~3.0.0",
"doctrine/dbal": "^2.9.2"
},
"require-dev": {
Expand Down
1 change: 0 additions & 1 deletion phpstan.neon
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ includes:

parameters:
ignoreErrors:
- '#^Cannot call method getMessage\(\) on Throwable\|null\.$#'
- "#^Parameter \\#1 \\$function of function call_user_func expects callable\\(\\): mixed, array\\(object, 'getSubscribedEvents'\\) given.#"
# No replacement available
- '#^Fetching class constant class of deprecated class Doctrine\\DBAL\\Tools\\Console\\Command\\ImportCommand\.$#'
173 changes: 103 additions & 70 deletions src/DI/DbalExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
use Doctrine\DBAL\Portability\Connection as PortabilityConnection;
use Nette\DI\CompilerExtension;
use Nette\DI\ContainerBuilder;
use Nette\InvalidArgumentException;
use Nette\PhpGenerator\ClassType;
use Nette\Utils\AssertionException;
use Nette\Utils\Validators;
Expand All @@ -26,6 +27,10 @@ final class DbalExtension extends CompilerExtension

public const TAG_NETTRINE_SUBSCRIBER = 'nettrine.subscriber';

public const TAG_CONNECTION = 'nettrine.connection';

public const DEFAULT_CONNECTION_NAME = 'default';

/** @var mixed[] */
private $defaults = [
'debug' => false,
Expand All @@ -35,27 +40,30 @@ final class DbalExtension extends CompilerExtension
'filterSchemaAssetsExpression' => null,
'autoCommit' => true,
],
'connection' => [
'url' => null,
'pdo' => null,
'memory' => null,
'driver' => 'pdo_mysql',
'driverClass' => null,
'unix_socket' => null,
'host' => null,
'port' => null,
'dbname' => null,
'servicename' => null,
'user' => null,
'password' => null,
'charset' => 'UTF8',
'portability' => PortabilityConnection::PORTABILITY_ALL,
'fetchCase' => PDO::CASE_LOWER,
'persistent' => true,
'types' => [],
'typesMapping' => [],
'wrapperClass' => null,
],
'connections' => [],
];

/** @var mixed[] */
private $connectionDefaults = [
'url' => null,
'pdo' => null,
'memory' => null,
'driver' => 'pdo_mysql',
'driverClass' => null,
'unix_socket' => null,
'host' => null,
'port' => null,
'dbname' => null,
'servicename' => null,
'user' => null,
'password' => null,
'charset' => 'UTF8',
'portability' => PortabilityConnection::PORTABILITY_ALL,
'fetchCase' => PDO::CASE_LOWER,
'persistent' => true,
'types' => [],
'typesMapping' => [],
'wrapperClass' => null,
];

/**
Expand All @@ -66,13 +74,19 @@ public function loadConfiguration(): void
$builder = $this->getContainerBuilder();
$config = $this->validateConfig($this->defaults);

if (!array_key_exists(self::DEFAULT_CONNECTION_NAME, $config['connections'])) {
throw new InvalidArgumentException('Default connection must be set!');
}

$this->loadDoctrineConfiguration();
$this->loadConnectionConfiguration();

if ($config['debug'] === true) {
$builder->addDefinition($this->prefix('queryPanel'))
->setFactory(QueryPanel::class)
->setAutowired(false);
foreach ($config['connections'] as $name => $connection) {
$builder->addDefinition($this->prefix($name . '.queryPanel'))
->setFactory(QueryPanel::class, ['@' . $this->prefix($name . '.connection')])
->setAutowired(false);
}
}
}

Expand All @@ -82,42 +96,44 @@ public function loadConfiguration(): void
public function loadDoctrineConfiguration(): void
{
$builder = $this->getContainerBuilder();
$config = $this->validateConfig($this->defaults['configuration'], $this->config['configuration']);
$config = $this->validateConfig($this->defaults);

$logger = $builder->addDefinition($this->prefix('logger'))
->setType(LoggerChain::class)
->setAutowired('self');
foreach ($config['connections'] as $name => $connection) {
$logger = $builder->addDefinition($this->prefix($name . '.logger'))
->setType(LoggerChain::class)
->setAutowired('self');

$configuration = $builder->addDefinition($this->prefix('configuration'));
$configuration->setFactory(Configuration::class)
->setAutowired(false)
->addSetup('setSQLLogger', [$this->prefix('@logger')]);
$configuration = $builder->addDefinition($this->prefix($name . '.configuration'))
->setFactory(Configuration::class)
->setAutowired(false)
->addSetup('setSQLLogger', [$this->prefix('@' . $name . '.logger')]);

// SqlLogger (append to chain)
if ($config['sqlLogger'] !== null) {
$logger->addSetup('addLogger', [$config['sqlLogger']]);
}
// SqlLogger (append to chain)
if ($config['configuration']['sqlLogger'] !== null) {
$logger->addSetup('addLogger', [$config['configuration']['sqlLogger']]);
}

// ResultCacheImpl
if ($config['resultCacheImpl'] !== null) {
$configuration->addSetup('setResultCacheImpl', [$config['resultCacheImpl']]);
}
// ResultCacheImpl
if ($config['configuration']['resultCacheImpl'] !== null) {
$configuration->addSetup('setResultCacheImpl', [$config['configuration']['resultCacheImpl']]);
}

// FilterSchemaAssetsExpression
if ($config['filterSchemaAssetsExpression'] !== null) {
$configuration->addSetup('setFilterSchemaAssetsExpression', [$config['filterSchemaAssetsExpression']]);
}
// FilterSchemaAssetsExpression
if ($config['configuration']['filterSchemaAssetsExpression'] !== null) {
$configuration->addSetup('setFilterSchemaAssetsExpression', [$config['configuration']['filterSchemaAssetsExpression']]);
}

// AutoCommit
Validators::assert($config['autoCommit'], 'bool', 'configuration.autoCommit');
$configuration->addSetup('setAutoCommit', [$config['autoCommit']]);
// AutoCommit
Validators::assert($config['configuration']['autoCommit'], 'bool', 'configuration.autoCommit');
$configuration->addSetup('setAutoCommit', [$config['configuration']['autoCommit']]);
}
}

public function loadConnectionConfiguration(): void
{
$builder = $this->getContainerBuilder();
$globalConfig = $this->validateConfig($this->defaults);
$config = $this->validateConfig($this->defaults['connection'], $this->config['connection']);
$config = $globalConfig['connections'];

$builder->addDefinition($this->prefix('eventManager'))
->setFactory(ContainerAwareEventManager::class);
Expand All @@ -129,16 +145,30 @@ public function loadConnectionConfiguration(): void
->setFactory(DebugEventManager::class, [$this->prefix('@eventManager')]);
}

$builder->addDefinition($this->prefix('connectionFactory'))
->setFactory(ConnectionFactory::class, [$config['types'], $config['typesMapping']]);
foreach ($config as $name => $connection) {
if (!array_key_exists('types', $connection)) {// temporary solution
$connection['types'] = [];
}
if (!array_key_exists('typesMapping', $connection)) {// temporary solution
$connection['typesMapping'] = [];
}

$builder->addDefinition($this->prefix('connection'))
->setFactory(Connection::class)
->setFactory('@' . $this->prefix('connectionFactory') . '::createConnection', [
$config,
'@' . $this->prefix('configuration'),
$builder->getDefinitionByType(EventManager::class),
]);
$autowired = $name === self::DEFAULT_CONNECTION_NAME ? true : false;

$builder->addDefinition($this->prefix($name . '.connectionFactory'))
->setFactory(ConnectionFactory::class, [$connection['types'], $connection['typesMapping']])
->setAutowired($autowired);

$builder->addDefinition($this->prefix($name . '.connection'))
->setFactory(Connection::class)
->setFactory('@' . $this->prefix($name . '.connectionFactory') . '::createConnection', [
$connection,
'@' . $this->prefix($name . '.configuration'),
$builder->getDefinitionByType(EventManager::class),
])
->setAutowired($autowired)
->addTag(self::TAG_CONNECTION);
}
}

/**
Expand All @@ -153,6 +183,7 @@ public function beforeCompile(): void

$eventManager = $builder->getDefinition($this->prefix('eventManager'));
foreach ($builder->findByTag(self::TAG_NETTRINE_SUBSCRIBER) as $serviceName => $tag) {
$serviceName = (string) $serviceName; // nette/di 2.4 allows numeric names, which are converted to integers
$class = $builder->getDefinition($serviceName)->getType();

if ($class === null || !is_subclass_of($class, EventSubscriber::class)) {
Expand Down Expand Up @@ -183,19 +214,21 @@ public function afterCompile(ClassType $class): void
$config = $this->validateConfig($this->defaults);

if ($config['debug'] === true) {
$initialize = $class->getMethod('initialize');
$initialize->addBody(
'$this->getService(?)->addPanel($this->getService(?));',
['tracy.bar', $this->prefix('queryPanel')]
);
$initialize->addBody(
'$this->getService(?)->getConfiguration()->getSqlLogger()->addLogger($this->getService(?));',
[$this->prefix('connection'), $this->prefix('queryPanel')]
);
$initialize->addBody(
'$this->getService(?)->addPanel(new ?);',
['tracy.blueScreen', ContainerBuilder::literal(DbalBlueScreen::class)]
);
foreach ($config['connections'] as $name => $connection) {
$initialize = $class->getMethod('initialize');
$initialize->addBody(
'$this->getService(?)->addPanel($this->getService(?));',
['tracy.bar', $this->prefix($name . '.queryPanel')]
);
$initialize->addBody(
'$this->getService(?)->getConfiguration()->getSqlLogger()->addLogger($this->getService(?));',
[$this->prefix($name . '.connection'), $this->prefix($name . '.queryPanel')]
);
$initialize->addBody(
'$this->getService(?)->addPanel(new ?);',
['tracy.blueScreen', ContainerBuilder::literal(DbalBlueScreen::class)]
);
}
}
}

Expand Down
23 changes: 21 additions & 2 deletions tests/cases/DI/DbalExtensionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
namespace Tests\Nettrine\DBAL\Cases\DI;

use Doctrine\DBAL\Connection;
use Doctrine\DBAL\Platforms\PostgreSQL100Platform;
use Doctrine\DBAL\Query\QueryBuilder;
use Nette\DI\Compiler;
use Nette\DI\Container;
Expand All @@ -19,7 +20,7 @@ public function testRegister(): void
$loader = new ContainerLoader(TEMP_PATH, true);
$class = $loader->load(function (Compiler $compiler): void {
$compiler->addExtension('dbal', new DbalExtension());
$compiler->addConfig(['dbal' => ['connection' => ['driver' => 'pdo_sqlite']]]);
$compiler->addConfig(['dbal' => ['connections' => [DbalExtension::DEFAULT_CONNECTION_NAME => ['driver' => 'pdo_sqlite', 'foo' => 'bar']]]]);
}, '1a');

/** @var Container $container */
Expand Down Expand Up @@ -73,7 +74,7 @@ public function testDebugMode(): void
$loader = new ContainerLoader(TEMP_PATH, true);
$class = $loader->load(function (Compiler $compiler): void {
$compiler->addExtension('dbal', new DbalExtension());
$compiler->addConfig(['dbal' => ['debug' => true]]);
$compiler->addConfig(['dbal' => ['debug' => true, 'connections' => [DbalExtension::DEFAULT_CONNECTION_NAME => []]]]);
}, '1b');

/** @var Container $container */
Expand All @@ -85,4 +86,22 @@ public function testDebugMode(): void
$this->assertInstanceOf(DebugEventManager::class, $connection->getEventManager());
}

public function testServerVersion(): void
{
$loader = new ContainerLoader(TEMP_PATH, true);
$class = $loader->load(function (Compiler $compiler): void {
$compiler->addExtension('dbal', new DbalExtension());
$compiler->addConfig(['dbal' => ['connections' => [DbalExtension::DEFAULT_CONNECTION_NAME => ['driver' => 'pdo_pgsql', 'serverVersion' => '10.0']]]]);
}, '1c');

/** @var Container $container */
$container = new $class();

/** @var Connection $connection */
$connection = $container->getByType(Connection::class);

$this->assertInstanceOf(PostgreSQL100Platform::class, $connection->getDatabasePlatform());
$this->assertFalse($connection->isConnected());
}

}
7 changes: 4 additions & 3 deletions tests/cases/Events/EventManagerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,10 @@ public function testPostConnectEvent(): void
$compiler->addExtension('dbal', new DbalExtension());
$compiler->addConfig(NeonLoader::load('
dbal:
connection:
driver: pdo_sqlite
host: ":memory:"
connections:
default:
driver: pdo_sqlite
host: ":memory:"

services:
sub1:
Expand Down