Skip to content
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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
- Chg #222: Bump minimal version of `yiisoft/aliases` to `^3.0` (@dagpro)
- Chg #222: Bump `symfony/console` version to `^6.4 || ^7.2` (@dagpro)
- Chg #222: Bump `symfony/finder` version to `^6.4 || ^7.2` (@dagpro)
- Enh #228: Improve `DbalFactory` and it's config (@rustamwin)

## 1.0.0 March 21, 2024

Expand Down
4 changes: 2 additions & 2 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -69,12 +69,12 @@
},
"autoload": {
"psr-4": {
"Yiisoft\\Yii\\Cycle\\": "src"
"Yiisoft\\Yii\\Cycle\\": "src/"
}
},
"autoload-dev": {
"psr-4": {
"Yiisoft\\Yii\\Cycle\\Tests\\": "tests"
"Yiisoft\\Yii\\Cycle\\Tests\\": "tests/"
}
},
"extra": {
Expand Down
6 changes: 5 additions & 1 deletion config/di.php
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,11 @@
return [
// Cycle DBAL
DatabaseProviderInterface::class => Reference::to(DatabaseManager::class),
DatabaseManager::class => new DbalFactory($params['yiisoft/yii-cycle']['dbal']),
DatabaseManager::class => static function (DbalFactory $dbalFactory) use (&$params) {
$config = $params['yiisoft/yii-cycle']['dbal'];

return $dbalFactory->create($config);
},

// Cycle ORM
ORMInterface::class => Reference::to(ORM::class),
Expand Down
4 changes: 2 additions & 2 deletions config/params.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,8 @@
'yiisoft/yii-cycle' => [
// DBAL config
'dbal' => [
// SQL query logger. Definition of Psr\Log\LoggerInterface
'query-logger' => null,
// Whether to enable logging of all SQL queries to PSR logger.
'query-logging' => false,
// Default database
'default' => null,
'aliases' => [],
Expand Down
4 changes: 2 additions & 2 deletions docs/guide/en/installation.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,8 @@ return [
'yiisoft/yii-cycle' => [
// Cycle DBAL config
'dbal' => [
// PSR-3 compatible SQL query logger
'query-logger' => null,
// Whether to enable logging of all SQL queries to PSR logger.
'query-logging' => false,
// Default database (from 'databases' list)
'default' => 'default',
'aliases' => [],
Expand Down
4 changes: 2 additions & 2 deletions docs/guide/es/installation.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,8 @@ return [
'yiisoft/yii-cycle' => [
// Configuración de Cycle DBAL
'dbal' => [
// PSR-3 SQL query logger
'query-logger' => null,
// Whether to enable logging of all SQL queries to PSR logger.
'query-logging' => false,
// Bases de datos por defecto (De la lista 'databases')
'default' => 'default',
'aliases' => [],
Expand Down
4 changes: 2 additions & 2 deletions docs/guide/pt-BR/installation.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,8 @@ return [
'yiisoft/yii-cycle' => [
// Cycle DBAL config
'dbal' => [
// PSR-3 compatible SQL query logger
'query-logger' => null,
// Whether to enable logging of all SQL queries to PSR logger.
'query-logging' => false,
// Default database (from 'databases' list)
'default' => 'default',
'aliases' => [],
Expand Down
4 changes: 2 additions & 2 deletions docs/guide/ru/installation.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,8 @@ return [
'yiisoft/yii-cycle' => [
// Конфиг Cycle DBAL
'dbal' => [
// PSR-3 совместимый логгер SQL запросов
'query-logger' => null,
// Включить ли логирование всех SQL-запросов в PSR-3 совместимый логгере.
'query-logging' => false,
// БД по умолчанию (из списка 'databases')
'default' => 'default',
'aliases' => [],
Expand Down
65 changes: 8 additions & 57 deletions src/Factory/DbalFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,78 +4,29 @@

namespace Yiisoft\Yii\Cycle\Factory;

use Cycle\Database\Driver\Driver;
use Exception;
use Cycle\Database\Config\DatabaseConfig;
use Cycle\Database\DatabaseManager;
use Psr\Container\ContainerInterface;
use Psr\Log\LoggerInterface;
use RuntimeException;

final class DbalFactory
{
private readonly array|DatabaseConfig $dbalConfig;

/** @var LoggerInterface|string|null */
private mixed $logger = null;

public function __construct(array|DatabaseConfig $config)
{
if (is_array($config) && array_key_exists('query-logger', $config)) {
$this->logger = $config['query-logger'];
unset($config['query-logger']);
}
$this->dbalConfig = $config;
public function __construct(
private readonly ?LoggerInterface $logger = null
) {
}

public function __invoke(ContainerInterface $container): DatabaseManager
public function create(array $dbalConfig): DatabaseManager
{
$loggingEnabled = $dbalConfig['query-logging'] ?? false;
$dbal = new DatabaseManager(
$this->prepareConfig($this->dbalConfig)
new DatabaseConfig($dbalConfig)
);

if ($this->logger !== null) {
$logger = $this->prepareLogger($container, $this->logger);
if ($this->logger !== null && $loggingEnabled === true) {
$logger = $this->logger;
$dbal->setLogger($logger);
/** Remove when issue is resolved {@link https://github.com/cycle/orm/issues/60} */
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Issue is opened yet.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

But it works, see tests.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

But it works, see tests.

Which test checks driver logger?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

$drivers = $dbal->getDrivers();
array_walk($drivers, static fn (Driver $driver) => $driver->setLogger($logger));
}

return $dbal;
}

/**
* @param LoggerInterface|string $logger
*
* @throws Exception
*
* @return LoggerInterface
*/
private function prepareLogger(ContainerInterface $container, mixed $logger): LoggerInterface
{
if (is_string($logger)) {
$logger = $container->get($logger);
}
if (!$logger instanceof LoggerInterface) {
throw new RuntimeException(
sprintf('Logger definition should be subclass of %s.', LoggerInterface::class)
);
}
return $logger;
}

/**
* @param array|DatabaseConfig $config
*
* @return DatabaseConfig
*/
private function prepareConfig(array|DatabaseConfig $config): DatabaseConfig
{
if ($config instanceof DatabaseConfig) {
return $config;
}

return new DatabaseConfig($config);
}
}
4 changes: 2 additions & 2 deletions tests/Unit/Factory/DbalFactory/BaseDbalFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,12 @@

use PHPUnit\Framework\TestCase;
use Psr\Container\ContainerInterface;
use Psr\Log\NullLogger;
use Spiral\Core\FactoryInterface;
use Yiisoft\Aliases\Aliases;
use Yiisoft\Injector\Injector;
use Yiisoft\Test\Support\Container\Exception\NotFoundException;
use Yiisoft\Test\Support\Container\SimpleContainer;
use Yiisoft\Test\Support\Log\SimpleLogger;
use Yiisoft\Yii\Cycle\Factory\CycleDynamicFactory;

abstract class BaseDbalFactory extends TestCase
Expand All @@ -26,7 +26,7 @@ protected function setUp(): void
{
$this->container = new SimpleContainer(
[
NullLogger::class => new NullLogger(),
SimpleLogger::class => new SimpleLogger(),
Aliases::class => new Aliases(self::ALIASES),
],
function (string $id) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,8 @@

namespace Yiisoft\Yii\Cycle\Tests\Unit\Factory\DbalFactory;

use Psr\Container\NotFoundExceptionInterface;
use Psr\Log\LoggerInterface;
use Psr\Log\NullLogger;
use RuntimeException;
use stdClass;
use Yiisoft\Aliases\Aliases;
use Yiisoft\Test\Support\Log\SimpleLogger;
use Yiisoft\Yii\Cycle\Factory\DbalFactory;
use Yiisoft\Yii\Cycle\Tests\Unit\Stub\FakeConnectionConfig;
use Yiisoft\Yii\Cycle\Tests\Unit\Stub\FakeDriver;
Expand All @@ -18,14 +14,14 @@
final class DbalFactoryConfigureQueryLoggerTest extends BaseDbalFactory
{
/**
* @param LoggerInterface|string $logger Classname or object
* @param LoggerInterface|null $logger Classname or object
*
* @return LoggerInterface|null
*/
protected function prepareLoggerFromDbalFactory($logger): ?LoggerInterface
protected function prepareLoggerFromDbalFactory(?LoggerInterface $logger): ?LoggerInterface
{
$factory = (new DbalFactory([
'query-logger' => $logger,
$factory = (new DbalFactory($logger))->create([
'query-logging' => true,
'default' => 'default',
'aliases' => [],
'databases' => [
Expand All @@ -37,47 +33,16 @@ protected function prepareLoggerFromDbalFactory($logger): ?LoggerInterface
driver: FakeDriver::class,
),
],
]))($this->container);
]);
return $factory->driver('fake')->getLogger();
}

public function testLoggerDefinitionAsStringDefinition(): void
public function testLoggerDefinition(): void
{
$nullLogger = $this->container->get(NullLogger::class);
$simpleLogger = $this->container->get(SimpleLogger::class);

$dbalLogger = $this->prepareLoggerFromDbalFactory(NullLogger::class);
$dbalLogger = $this->prepareLoggerFromDbalFactory($simpleLogger);

// Logger was got from the container
$this->assertSame($nullLogger, $dbalLogger);
}

public function testLoggerDefinitionAsObject(): void
{
$nullLogger = $this->container->get(NullLogger::class);

$dbalLogger = $this->prepareLoggerFromDbalFactory($nullLogger);

$this->assertSame($dbalLogger, $nullLogger);
}

public function testLoggerDefinitionAsInvalidDefinition(): void
{
$this->expectException(NotFoundExceptionInterface::class);

$this->prepareLoggerFromDbalFactory('Invalid definition');
}

public function testLoggerDefinitionAsInvalidClassName(): void
{
$this->expectException(RuntimeException::class);

$this->prepareLoggerFromDbalFactory(Aliases::class);
}

public function testLoggerDefinitionAsInvalidObject(): void
{
$this->expectException(RuntimeException::class);

$this->prepareLoggerFromDbalFactory(new stdClass());
$this->assertSame($dbalLogger, $simpleLogger);
}
}
15 changes: 6 additions & 9 deletions tests/Unit/Factory/DbalFactory/DbalFactoryTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,10 @@

final class DbalFactoryTest extends BaseDbalFactory
{
public function testPrepareConfig(): void
public function testCreate(): void
{
$config = [
'query-logger' => 'foo',
'query-logging' => true,
'default' => 'default',
'aliases' => [],
'databases' => [
Expand All @@ -29,13 +29,10 @@ public function testPrepareConfig(): void
],
];

$factory = new DbalFactory([]);
$ref = new \ReflectionMethod($factory, 'prepareConfig');
$ref->setAccessible(true);
$factory = new DbalFactory();
$dbal = $factory->create($config);
$dbalConfig = new DatabaseConfig($config);

$this->assertEquals(new DatabaseConfig($config), $ref->invoke($factory, $config));

$obj = new DatabaseConfig($config);
$this->assertSame($obj, $ref->invoke($factory, $obj));
$this->assertSame($dbal->database()->getName(), $dbalConfig->getDefaultDatabase());
}
}
8 changes: 3 additions & 5 deletions tests/Unit/Factory/OrmFactory/BaseOrmFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -40,8 +40,8 @@ function (string $id) {
return new CycleDynamicFactory($this->container->get(Injector::class));
}
if ($id === DatabaseManager::class) {
return (new DbalFactory([
'query-logger' => null,
return (new DbalFactory())->create([
'query-logging' => false,
'default' => 'default',
'aliases' => [],
'databases' => [
Expand All @@ -53,9 +53,7 @@ function (string $id) {
driver: FakeDriver::class,
),
],
]))(
$this->container,
);
]);
}
throw new NotFoundException($id);
}
Expand Down
Loading