diff --git a/src/Console/PruneCommand.php b/src/Console/PruneCommand.php index 7dfa0db..74deb8f 100644 --- a/src/Console/PruneCommand.php +++ b/src/Console/PruneCommand.php @@ -13,6 +13,9 @@ class PruneCommand extends Command public function handle() : void { - VerificationCode::where('created_at', '<=', now()->subHours($this->option('hours')))->delete(); + VerificationCode::query() + ->where('created_at', '<=', now()->subHours($this->option('hours'))) + ->where('expires_at', '<', now()) + ->delete(); } } diff --git a/tests/Commands/PruneCommandTest.php b/tests/Commands/PruneCommandTest.php index c7641ec..0f4f953 100644 --- a/tests/Commands/PruneCommandTest.php +++ b/tests/Commands/PruneCommandTest.php @@ -8,24 +8,47 @@ class PruneCommandTest extends TestCase { /** @test */ - public function it_cleans_the_verification_code_table() + public function it_deletes_old_expired_code() { - VerificationCode::create([ + $verificationCode = VerificationCode::create([ 'code' => 'ABC123', 'verifiable' => 'taylor@laravel.com', - 'created_at' => now()->subHours(5), + 'expires_at' => now()->subHour(), ]); + VerificationCode::where('id', $verificationCode->id)->update(['created_at' => now()->subHours(5)]); + + $this->artisan('verification-code:prune', ['--hours' => 3]); + + $this->assertNull(VerificationCode::find($verificationCode->id)); + } + /** @test */ + public function it_does_not_delete_old_but_not_expired_code() + { $verificationCode = VerificationCode::create([ - 'code' => '123ABC', + 'code' => 'ABC123', 'verifiable' => 'taylor@laravel.com', + 'expires_at' => now()->addHour(), ]); + VerificationCode::where('id', $verificationCode->id)->update(['created_at' => now()->subHours(5)]); $this->artisan('verification-code:prune', ['--hours' => 3]); - $dbVerificationCodes = VerificationCode::all(); + $this->assertNotNull(VerificationCode::find($verificationCode->id)); + } + + /** @test */ + public function it_does_not_delete_code_that_is_not_old_enough() + { + $verificationCode = VerificationCode::create([ + 'code' => 'ABC123', + 'verifiable' => 'taylor@laravel.com', + 'expires_at' => now()->subHour(), + ]); + VerificationCode::where('id', $verificationCode->id)->update(['created_at' => now()->subHours(2)]); + + $this->artisan('verification-code:prune', ['--hours' => 3]); - $this->assertCount(1, $dbVerificationCodes); - $this->assertEquals($verificationCode->id, $dbVerificationCodes->first()->id); + $this->assertNotNull(VerificationCode::find($verificationCode->id)); } }