Skip to content
Open
Show file tree
Hide file tree
Changes from 1 commit
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
21 changes: 20 additions & 1 deletion app/TermsOfUseVersion.php
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,26 @@ class TermsOfUseVersion extends Model {
'active' => 'boolean',
];

/**
* Get the active ToU version.
*/
public static function latestActiveVersion(): ?self {
Comment thread
dati18 marked this conversation as resolved.
Outdated
return self::query()->where('active', true)->latest()->first();
return self::query()->where('active', true)->first();
}

/**
* Ensure only one ToU version remains active after any save operation.
*/
protected static function booted(): void {
static::saving(function (self $model): void {
if (!$model->active) {
return;
}

self::query()
->where('version', '!=', $model->version)
->where('active', true)
->update(['active' => false]);
});
}
}
40 changes: 40 additions & 0 deletions tests/Models/TermsOfUseVersionTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
<?php

namespace Tests\Models;

use App\TermsOfUseVersion;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

class TermsOfUseVersionTest extends TestCase {
use RefreshDatabase;

public function testSavingActiveVersionDeactivatesOtherVersions(): void {
$first = TermsOfUseVersion::create([
'version' => '2024-01-01',
'active' => true,
]);

$second = TermsOfUseVersion::create([
'version' => '2025-01-01',
'active' => true,
]);

$this->assertFalse($first->fresh()->active);
$this->assertTrue($second->fresh()->active);
}

public function testSavingInactiveVersionDoesNotAffectExistingActiveVersion(): void {
$active = TermsOfUseVersion::create([
'version' => '2024-03-01',
'active' => true,
]);

TermsOfUseVersion::create([
'version' => '2024-04-01',
'active' => false,
]);

$this->assertTrue($active->fresh()->active);
}
}
Loading