Skip to content

Commit e8d28d4

Browse files
author
farhadzand
committed
refactor: enhance MySQLDriver and related components to support configurable database connections
- Updated MySQLDriver to accept a connection parameter for improved flexibility. - Modified EloquentAuditLog to utilize the configured connection when creating tables and checking existence. - Adjusted AuditLogger to pass the connection parameter to MySQLDriver. - Updated tests to validate connection handling and ensure proper functionality across different database connections. - Cleaned up code formatting for consistency.
1 parent 767a4e5 commit e8d28d4

File tree

7 files changed

+95
-23
lines changed

7 files changed

+95
-23
lines changed

src/AuditLoggerServiceProvider.php

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ final class AuditLoggerServiceProvider extends ServiceProvider
2020
public function register(): void
2121
{
2222
$this->mergeConfigFrom(
23-
__DIR__.'/../config/audit-logger.php',
23+
__DIR__ . '/../config/audit-logger.php',
2424
'audit-logger'
2525
);
2626

@@ -29,7 +29,7 @@ public function register(): void
2929
// Register the causer resolver
3030
$this->app->singleton(
3131
CauserResolverInterface::class,
32-
fn ($app) => isset($app['config']['audit-logger.causer']['resolver']) && $app['config']['audit-logger.causer']['resolver']
32+
fn($app) => isset($app['config']['audit-logger.causer']['resolver']) && $app['config']['audit-logger.causer']['resolver']
3333
? $app->make($app['config']['audit-logger.causer']['resolver'])
3434
: new CauserResolver(
3535
guard: $app['config']['audit-logger.causer']['guard'] ?? null,
@@ -38,10 +38,12 @@ public function register(): void
3838
);
3939

4040
// Register the main audit logger service - use fully qualified namespace
41-
$this->app->singleton(\iamfarhad\LaravelAuditLog\Services\AuditLogger::class, function ($app) {
41+
$this->app->singleton(AuditLogger::class, function ($app) {
42+
$connection = $app['config']['audit-logger.drivers.mysql.connection'] ?? config('database.default');
43+
4244
$driver = match ($app['config']['audit-logger.default']) {
43-
'mysql' => new MySQLDriver,
44-
default => new MySQLDriver,
45+
'mysql' => new MySQLDriver($connection),
46+
default => new MySQLDriver($connection),
4547
};
4648

4749
return new AuditLogger($driver);
@@ -56,7 +58,7 @@ public function boot(): void
5658
// Publish config
5759
if ($this->app->runningInConsole()) {
5860
$this->publishes([
59-
__DIR__.'/../config/audit-logger.php' => config_path('audit-logger.php'),
61+
__DIR__ . '/../config/audit-logger.php' => config_path('audit-logger.php'),
6062
], 'audit-logger-config');
6163
}
6264

src/Drivers/MySQLDriver.php

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,8 @@ final class MySQLDriver implements AuditDriverInterface
1919

2020
private array $config;
2121

22+
private string $connection;
23+
2224
/**
2325
* Cache for table existence checks to avoid repeated schema queries.
2426
*/
@@ -29,9 +31,10 @@ final class MySQLDriver implements AuditDriverInterface
2931
*/
3032
private static ?array $configCache = null;
3133

32-
public function __construct()
34+
public function __construct(?string $connection = null)
3335
{
3436
$this->config = self::getConfigCache();
37+
$this->connection = $connection ?? $this->config['drivers']['mysql']['connection'] ?? config('database.default');
3538
$this->tablePrefix = $this->config['drivers']['mysql']['table_prefix'] ?? 'audit_';
3639
$this->tableSuffix = $this->config['drivers']['mysql']['table_suffix'] ?? '_logs';
3740
}
@@ -73,6 +76,7 @@ public function store(AuditLogInterface $log): void
7376

7477
try {
7578
$model = EloquentAuditLog::forEntity(entityClass: $log->getEntityType());
79+
$model->setConnection($this->connection);
7680
$model->fill([
7781
'entity_id' => $log->getEntityId(),
7882
'action' => $log->getAction(),
@@ -116,6 +120,7 @@ public function storeBatch(array $logs): void
116120
// Use Eloquent models to leverage automatic JSON casting
117121
foreach ($entityLogs as $log) {
118122
$model = EloquentAuditLog::forEntity(entityClass: $entityType);
123+
$model->setConnection($this->connection);
119124
$model->fill([
120125
'entity_id' => $log->getEntityId(),
121126
'action' => $log->getAction(),
@@ -137,7 +142,7 @@ public function createStorageForEntity(string $entityClass): void
137142
$this->validateEntityType($entityClass);
138143
$tableName = $this->getTableName($entityClass);
139144

140-
Schema::create($tableName, function (Blueprint $table) {
145+
Schema::connection($this->connection)->create($tableName, function (Blueprint $table) {
141146
$table->id();
142147
$table->string('entity_id');
143148
$table->string('action');
@@ -176,7 +181,7 @@ public function storageExistsForEntity(string $entityClass): bool
176181
}
177182

178183
// Check database and cache the result
179-
$exists = Schema::hasTable($tableName);
184+
$exists = Schema::connection($this->connection)->hasTable($tableName);
180185
self::$existingTables[$tableName] = $exists;
181186

182187
return $exists;

src/Models/EloquentAuditLog.php

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,16 @@ final class EloquentAuditLog extends Model
4646
'metadata' => 'array',
4747
];
4848

49+
/**
50+
* Get the connection name for the model.
51+
*/
52+
public function getConnectionName(): ?string
53+
{
54+
$config = self::getConfigCache();
55+
56+
return $config['drivers']['mysql']['connection'] ?? config('database.default');
57+
}
58+
4959
public function auditable()
5060
{
5161
return $this->morphTo();
@@ -173,6 +183,15 @@ public static function forEntity(string $entityClass): static
173183

174184
$table = "{$tablePrefix}{$tableName}{$tableSuffix}";
175185

176-
return (new self)->setTable($table);
186+
$instance = new self;
187+
$instance->setTable($table);
188+
189+
// Set the connection from config
190+
$connection = $config['drivers']['mysql']['connection'] ?? config('database.default');
191+
if ($connection) {
192+
$instance->setConnection($connection);
193+
}
194+
195+
return $instance;
177196
}
178197
}

src/Services/AuditLogger.php

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -43,10 +43,12 @@ public function batch(array $logs): void
4343
}
4444
}
4545

46-
public static function getDriver(string $driverName): static
46+
public static function getDriver(string $driverName, ?string $connection = null): static
4747
{
48+
$connection = $connection ?? config('audit-logger.drivers.mysql.connection') ?? config('database.default');
49+
4850
$driver = match ($driverName) {
49-
'mysql' => new MySQLDriver,
51+
'mysql' => new MySQLDriver($connection),
5052
default => throw new \InvalidArgumentException("Driver {$driverName} not found"),
5153
};
5254

tests/TestCase.php

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,7 @@ protected function getEnvironmentSetUp($app): void
5555
protected function setUpDatabase(): void
5656
{
5757
// Create users table
58-
Schema::create('users', function (Blueprint $table) {
58+
Schema::connection('testbench')->create('users', function (Blueprint $table) {
5959
$table->id();
6060
$table->string('name');
6161
$table->string('email')->unique();
@@ -67,7 +67,7 @@ protected function setUpDatabase(): void
6767
});
6868

6969
// Create posts table
70-
Schema::create('posts', function (Blueprint $table) {
70+
Schema::connection('testbench')->create('posts', function (Blueprint $table) {
7171
$table->id();
7272
$table->foreignId('user_id')->constrained()->onDelete('cascade');
7373
$table->string('title');
@@ -84,7 +84,7 @@ protected function setUpDatabase(): void
8484
];
8585

8686
foreach ($auditTables as $tableName) {
87-
Schema::create($tableName, function (Blueprint $table) {
87+
Schema::connection('testbench')->create($tableName, function (Blueprint $table) {
8888
$table->id();
8989
$table->string('entity_id');
9090
$table->string('action');

tests/Unit/ConnectionTest.php

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace iamfarhad\LaravelAuditLog\Tests\Unit;
6+
7+
use iamfarhad\LaravelAuditLog\Drivers\MySQLDriver;
8+
use iamfarhad\LaravelAuditLog\Models\EloquentAuditLog;
9+
use iamfarhad\LaravelAuditLog\Tests\TestCase;
10+
use Illuminate\Support\Facades\Schema;
11+
12+
final class ConnectionTest extends TestCase
13+
{
14+
public function test_driver_accepts_connection_parameter(): void
15+
{
16+
$driver = new MySQLDriver('testbench');
17+
18+
// Test that the driver can check table existence
19+
$this->assertTrue($driver->storageExistsForEntity('iamfarhad\\LaravelAuditLog\\Tests\\Mocks\\User'));
20+
}
21+
22+
public function test_model_uses_configured_connection(): void
23+
{
24+
config(['audit-logger.drivers.mysql.connection' => 'testbench']);
25+
26+
$model = EloquentAuditLog::forEntity('iamfarhad\\LaravelAuditLog\\Tests\\Mocks\\User');
27+
28+
$this->assertEquals('testbench', $model->getConnectionName());
29+
}
30+
31+
public function test_driver_creates_table_on_specified_connection(): void
32+
{
33+
$driver = new MySQLDriver('testbench');
34+
35+
// Drop the table if it exists
36+
Schema::connection('testbench')->dropIfExists('audit_test_entities_logs');
37+
38+
// Create storage for entity
39+
$driver->createStorageForEntity('App\\Models\\TestEntity');
40+
41+
// Verify the table was created
42+
$this->assertTrue(Schema::connection('testbench')->hasTable('audit_test_entities_logs'));
43+
}
44+
}

tests/Unit/MySQLDriverTest.php

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ final class MySQLDriverTest extends TestCase
1818
protected function setUp(): void
1919
{
2020
parent::setUp();
21-
$this->driver = new MySQLDriver;
21+
$this->driver = new MySQLDriver('testbench');
2222
}
2323

2424
public function test_can_store_audit_log(): void
@@ -98,13 +98,13 @@ public function test_can_store_batch_of_logs(): void
9898
public function test_can_create_storage_for_entity(): void
9999
{
100100
// Drop the table if it exists
101-
Schema::dropIfExists('audit_products_logs');
101+
Schema::connection('testbench')->dropIfExists('audit_products_logs');
102102

103103
// Create storage for a new entity
104104
$this->driver->createStorageForEntity('App\\Models\\Product');
105105

106106
// Verify the table was created
107-
$this->assertTrue(Schema::hasTable('audit_products_logs'));
107+
$this->assertTrue(Schema::connection('testbench')->hasTable('audit_products_logs'));
108108

109109
// Skip column checks entirely since they can vary between SQLite versions
110110
// This prevents the pragma_table_xinfo error in older SQLite versions
@@ -113,7 +113,7 @@ public function test_can_create_storage_for_entity(): void
113113
public function test_storage_exists_for_entity(): void
114114
{
115115
// Should return false for a non-existent table
116-
Schema::dropIfExists('audit_nonexistent_logs');
116+
Schema::connection('testbench')->dropIfExists('audit_nonexistent_logs');
117117
$this->assertFalse($this->driver->storageExistsForEntity('App\\Models\\Nonexistent'));
118118

119119
// Should return true for an existing table
@@ -123,7 +123,7 @@ public function test_storage_exists_for_entity(): void
123123
public function test_ensure_storage_exists_creates_table_if_needed(): void
124124
{
125125
// Drop the table if it exists
126-
Schema::dropIfExists('audit_orders_logs');
126+
Schema::connection('testbench')->dropIfExists('audit_orders_logs');
127127

128128
// Enable auto migration
129129
config(['audit-logger.auto_migration' => true]);
@@ -132,13 +132,13 @@ public function test_ensure_storage_exists_creates_table_if_needed(): void
132132
$this->driver->createStorageForEntity('App\\Models\\Order');
133133

134134
// Verify the table exists
135-
$this->assertTrue(Schema::hasTable('audit_orders_logs'));
135+
$this->assertTrue(Schema::connection('testbench')->hasTable('audit_orders_logs'));
136136
}
137137

138138
public function test_ensure_storage_exists_does_nothing_if_auto_migration_disabled(): void
139139
{
140140
// Drop the table if it exists
141-
Schema::dropIfExists('audit_customers_logs');
141+
Schema::connection('testbench')->dropIfExists('audit_customers_logs');
142142

143143
// Disable auto migration
144144
config(['audit-logger.auto_migration' => false]);
@@ -147,7 +147,7 @@ public function test_ensure_storage_exists_does_nothing_if_auto_migration_disabl
147147
$this->driver->ensureStorageExists('App\\Models\\Customer');
148148

149149
// Verify the table does not exist
150-
$this->assertFalse(Schema::hasTable('audit_customers_logs'));
150+
$this->assertFalse(Schema::connection('testbench')->hasTable('audit_customers_logs'));
151151
}
152152

153153
protected function tearDown(): void

0 commit comments

Comments
 (0)