feat: Implement value change logging functionality with models, traits, and migration; add tests for logging behavior and value change mapping

This commit is contained in:
2026-08-03 15:43:50 -03:00
parent 3b2977a330
commit c4b317d5fc
6 changed files with 307 additions and 0 deletions

View File

@@ -0,0 +1,9 @@
<?php
namespace App\Domains\Logging\Enums;
enum ValueChangeActorType: string
{
case User = 'user';
case System = 'system';
}

View File

@@ -0,0 +1,62 @@
<?php
namespace App\Domains\Logging\Models\Concerns;
use App\Domains\Logging\Enums\ValueChangeActorType;
use App\Domains\Logging\Models\ValueChange;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\MorphMany;
use Illuminate\Support\Facades\Auth;
use LogicException;
trait LogsValueChanges
{
public static function bootLogsValueChanges(): void
{
static::updated(function (Model $model): void {
$changedAttributes = array_values(array_intersect(
$model->getLoggedAttributes(),
array_keys($model->getChanges()),
));
if ($changedAttributes === []) {
return;
}
$userId = Auth::id();
$actorType = $userId === null
? ValueChangeActorType::System
: ValueChangeActorType::User;
foreach ($changedAttributes as $attribute) {
$model->valueChanges()->create([
'attribute' => $attribute,
'old_value' => $model->getRawOriginal($attribute),
'new_value' => $model->getAttributes()[$attribute] ?? null,
'changed_at' => now(),
'actor_type' => $actorType,
'user_id' => $userId,
]);
}
});
}
/** @return array<int, string> */
public function getLoggedAttributes(): array
{
if (! property_exists($this, 'loggedAttributes')) {
throw new LogicException(sprintf(
'The [%s] model must define a $loggedAttributes property.',
static::class,
));
}
return array_values(array_unique($this->loggedAttributes));
}
/** @return MorphMany<ValueChange, $this> */
public function valueChanges(): MorphMany
{
return $this->morphMany(ValueChange::class, 'trackable');
}
}

View File

@@ -0,0 +1,47 @@
<?php
namespace App\Domains\Logging\Models;
use App\Domains\Auth\Models\User;
use App\Domains\Logging\Enums\ValueChangeActorType;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\MorphTo;
#[Fillable([
'trackable_type',
'trackable_id',
'attribute',
'old_value',
'new_value',
'changed_at',
'actor_type',
'user_id',
])]
class ValueChange extends Model
{
public $timestamps = false;
/** @return MorphTo<Model, $this> */
public function trackable(): MorphTo
{
return $this->morphTo();
}
/** @return BelongsTo<User, $this> */
public function user(): BelongsTo
{
return $this->belongsTo(User::class);
}
protected function casts(): array
{
return [
'trackable_id' => 'integer',
'changed_at' => 'datetime',
'actor_type' => ValueChangeActorType::class,
'user_id' => 'integer',
];
}
}

View File

@@ -0,0 +1,31 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::create('value_changes', function (Blueprint $table): void {
$table->id();
$table->morphs('trackable');
$table->string('attribute');
$table->text('old_value')->nullable();
$table->text('new_value')->nullable();
$table->timestamp('changed_at');
$table->string('actor_type');
$table->foreignId('user_id')
->nullable()
->constrained('users')
->cascadeOnUpdate()
->nullOnDelete();
});
}
public function down(): void
{
Schema::dropIfExists('value_changes');
}
};

View File

@@ -0,0 +1,120 @@
<?php
namespace Tests\Feature\Logging;
use App\Domains\Logging\Enums\ValueChangeActorType;
use App\Domains\Logging\Models\Concerns\LogsValueChanges;
use App\Domains\Logging\Models\ValueChange;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Schema;
use Tests\TestCase;
class LogsValueChangesTest extends TestCase
{
protected function setUp(): void
{
parent::setUp();
config()->set('database.default', 'logging_test');
config()->set('database.connections.logging_test', [
'driver' => 'sqlite',
'database' => ':memory:',
'foreign_key_constraints' => true,
]);
Schema::create('users', function (Blueprint $table): void {
$table->id();
});
Schema::create('logging_test_products', function (Blueprint $table): void {
$table->id();
$table->string('name');
$table->unsignedInteger('price');
$table->text('description')->nullable();
$table->timestamps();
});
$migration = require database_path('migrations/2026_08_03_000200_create_value_changes_table.php');
$migration->up();
}
public function test_it_creates_one_system_record_per_configured_change(): void
{
$product = LoggingTestProduct::create([
'name' => 'Original',
'price' => 100,
'description' => 'Old description',
]);
$product->update([
'name' => 'Updated',
'price' => 150,
'description' => 'New description',
]);
$this->assertDatabaseCount('value_changes', 2);
$this->assertDatabaseHas('value_changes', [
'attribute' => 'name',
'old_value' => 'Original',
'new_value' => 'Updated',
'actor_type' => ValueChangeActorType::System->value,
'user_id' => null,
]);
$this->assertDatabaseHas('value_changes', [
'attribute' => 'price',
'old_value' => '100',
'new_value' => '150',
'actor_type' => ValueChangeActorType::System->value,
'user_id' => null,
]);
$this->assertTrue(ValueChange::firstOrFail()->trackable->is($product));
}
public function test_it_associates_an_authenticated_user_with_the_change(): void
{
Schema::getConnection()->table('users')->insert(['id' => 7]);
Auth::shouldReceive('id')->once()->andReturn(7);
$product = LoggingTestProduct::create([
'name' => 'Original',
'price' => 100,
]);
$product->update(['price' => 200]);
$change = ValueChange::firstOrFail();
$this->assertSame(ValueChangeActorType::User, $change->actor_type);
$this->assertSame(7, $change->user_id);
}
public function test_it_does_not_log_updates_to_unconfigured_attributes(): void
{
$product = LoggingTestProduct::create([
'name' => 'Original',
'price' => 100,
'description' => 'Old description',
]);
$product->update(['description' => 'New description']);
$this->assertDatabaseCount('value_changes', 0);
}
}
#[Fillable(['name', 'price', 'description'])]
class LoggingTestProduct extends Model
{
use LogsValueChanges;
protected $table = 'logging_test_products';
/** @var array<int, string> */
protected array $loggedAttributes = [
'name',
'price',
];
}

View File

@@ -0,0 +1,38 @@
<?php
namespace Tests\Unit\Logging;
use App\Domains\Auth\Models\User;
use App\Domains\Logging\Enums\ValueChangeActorType;
use App\Domains\Logging\Models\ValueChange;
use Illuminate\Database\Eloquent\Relations\MorphTo;
use Tests\TestCase;
class ValueChangeTest extends TestCase
{
public function test_value_change_maps_its_values_and_relations(): void
{
$valueChange = new ValueChange;
$valueChange->setRawAttributes([
'trackable_id' => '10',
'attribute' => 'status',
'old_value' => 'pending',
'new_value' => 'paid',
'changed_at' => '2026-08-03 15:30:00',
'actor_type' => ValueChangeActorType::User->value,
'user_id' => '20',
]);
$this->assertSame('value_changes', $valueChange->getTable());
$this->assertFalse($valueChange->usesTimestamps());
$this->assertSame(10, $valueChange->trackable_id);
$this->assertSame('status', $valueChange->attribute);
$this->assertSame('pending', $valueChange->old_value);
$this->assertSame('paid', $valueChange->new_value);
$this->assertSame('2026-08-03 15:30:00', $valueChange->changed_at->format('Y-m-d H:i:s'));
$this->assertSame(ValueChangeActorType::User, $valueChange->actor_type);
$this->assertSame(20, $valueChange->user_id);
$this->assertInstanceOf(MorphTo::class, $valueChange->trackable());
$this->assertInstanceOf(User::class, $valueChange->user()->getRelated());
}
}