Skip to content

Commit

Permalink
Merge pull request #695 from ragingdave/add-bulk-without-logs
Browse files Browse the repository at this point in the history
Add withoutLogs function to be able to more fluently disable logging
  • Loading branch information
Gummibeer authored Mar 13, 2020
2 parents 461bd83 + f7a1d0d commit ba4b86a
Show file tree
Hide file tree
Showing 2 changed files with 80 additions and 0 deletions.
15 changes: 15 additions & 0 deletions src/ActivityLogger.php
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,21 @@ public function log(string $description)
return $activity;
}

public function withoutLogs(callable $callback)
{
if ($this->logStatus->disabled()) {
return $callback();
}

$this->logStatus->disable();

try {
return $callback();
} finally {
$this->logStatus->enable();
}
}

protected function normalizeCauser($modelOrId): Model
{
if ($modelOrId instanceof Model) {
Expand Down
65 changes: 65 additions & 0 deletions tests/ActivityLoggerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

use Auth;
use Carbon\Carbon;
use Exception;
use Illuminate\Support\Collection;
use Spatie\Activitylog\Exceptions\CouldNotLogActivity;
use Spatie\Activitylog\Models\Activity;
Expand Down Expand Up @@ -337,4 +338,68 @@ public function it_will_log_a_custom_created_at_date_time()

$this->assertEquals($activityDateTime->toAtomString(), $firstActivity->created_at->toAtomString());
}

/** @test */
public function it_will_disable_logs_for_a_callback()
{
$result = activity()->withoutLogs(function () {
activity()->log('created');

return 'hello';
});

$this->assertNull($this->getLastActivity());
$this->assertEquals('hello', $result);
}

/** @test */
public function it_will_disable_logs_for_a_callback_without_affecting_previous_state()
{
activity()->withoutLogs(function () {
activity()->log('created');
});

$this->assertNull($this->getLastActivity());

activity()->log('outer');

$this->assertEquals('outer', $this->getLastActivity()->description);
}

/** @test */
public function it_will_disable_logs_for_a_callback_without_affecting_previous_state_even_when_already_disabled()
{
activity()->disableLogging();

activity()->withoutLogs(function () {
activity()->log('created');
});

$this->assertNull($this->getLastActivity());

activity()->log('outer');

$this->assertNull($this->getLastActivity());
}

/** @test */
public function it_will_disable_logs_for_a_callback_without_affecting_previous_state_even_with_exception()
{
activity()->disableLogging();

try {
activity()->withoutLogs(function () {
activity()->log('created');
throw new Exception('OH NO');
});
} catch (Exception $ex) {
//
}

$this->assertNull($this->getLastActivity());

activity()->log('outer');

$this->assertNull($this->getLastActivity());
}
}

0 comments on commit ba4b86a

Please sign in to comment.