Skip to content

Commit

Permalink
Merge pull request #472 from spatie/ft-activity-tap
Browse files Browse the repository at this point in the history
Add tap method to ActivityLogger
  • Loading branch information
Gummibeer authored Jan 29, 2019
2 parents 492fa4c + 96ae2f6 commit 2ed89a8
Show file tree
Hide file tree
Showing 6 changed files with 111 additions and 51 deletions.
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,12 @@

All notable changes to `spatie/laravel-activitylog` will be documented in this file

## 3.2.0 - 2019-01-29

- add `ActivityLogger::tap()` method
- add `LogsActivity::tapActivity()` method
- the `ActivityLogger` will work on an activity model instance instead of cache variables

## 3.1.2 - 2018-10-18

- add `shouldLogUnguarded()` method
Expand Down
82 changes: 36 additions & 46 deletions src/ActivityLogger.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,9 @@
use Illuminate\Auth\AuthManager;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Traits\Macroable;
use Spatie\Activitylog\Contracts\Activity;
use Illuminate\Contracts\Config\Repository;
use Spatie\Activitylog\Exceptions\CouldNotLogActivity;
use Spatie\Activitylog\Contracts\Activity as ActivityContract;

class ActivityLogger
{
Expand All @@ -16,40 +16,24 @@ class ActivityLogger
/** @var \Illuminate\Auth\AuthManager */
protected $auth;

protected $logName = '';

/** @var \Illuminate\Database\Eloquent\Model */
protected $performedOn;

/** @var \Illuminate\Database\Eloquent\Model */
protected $causedBy;

/** @var \Illuminate\Support\Collection */
protected $properties;
protected $defaultLogName = '';

/** @var string */
protected $authDriver;

/** @var \Spatie\Activitylog\ActivityLogStatus */
protected $logStatus;

/** @var \Spatie\Activitylog\Contracts\Activity */
protected $activity;

public function __construct(AuthManager $auth, Repository $config, ActivityLogStatus $logStatus)
{
$this->auth = $auth;

$this->properties = collect();

$this->authDriver = $config['activitylog']['default_auth_driver'] ?? $auth->getDefaultDriver();

if (starts_with(app()->version(), '5.1')) {
$this->causedBy = $auth->driver($this->authDriver)->user();
} else {
$this->causedBy = $auth->guard($this->authDriver)->user();
}

$this->logName = $config['activitylog']['default_log_name'];

$this->logEnabled = $config['activitylog']['enabled'] ?? true;
$this->defaultLogName = $config['activitylog']['default_log_name'];

$this->logStatus = $logStatus;
}
Expand All @@ -63,7 +47,7 @@ public function setLogStatus(ActivityLogStatus $logStatus)

public function performedOn(Model $model)
{
$this->performedOn = $model;
$this->getActivity()->subject()->associate($model);

return $this;
}
Expand All @@ -81,7 +65,7 @@ public function causedBy($modelOrId)

$model = $this->normalizeCauser($modelOrId);

$this->causedBy = $model;
$this->getActivity()->causer()->associate($model);

return $this;
}
Expand All @@ -93,21 +77,21 @@ public function by($modelOrId)

public function withProperties($properties)
{
$this->properties = collect($properties);
$this->getActivity()->properties = collect($properties);

return $this;
}

public function withProperty(string $key, $value)
{
$this->properties->put($key, $value);
$this->getActivity()->properties = $this->getActivity()->properties->put($key, $value);

return $this;
}

public function useLog(string $logName)
{
$this->logName = $logName;
$this->getActivity()->log_name = $logName;

return $this;
}
Expand All @@ -117,6 +101,13 @@ public function inLog(string $logName)
return $this->useLog($logName);
}

public function tap(callable $callback, string $eventName = null)
{
call_user_func($callback, $this->getActivity(), $eventName);

return $this;
}

public function enableLogging()
{
$this->logStatus->enable();
Expand All @@ -137,24 +128,14 @@ public function log(string $description)
return;
}

$activity = ActivitylogServiceProvider::getActivityModelInstance();

if ($this->performedOn) {
$activity->subject()->associate($this->performedOn);
}

if ($this->causedBy) {
$activity->causer()->associate($this->causedBy);
}

$activity->properties = $this->properties;
$activity = $this->activity;

$activity->description = $this->replacePlaceholders($description, $activity);

$activity->log_name = $this->logName;

$activity->save();

$this->activity = null;

return $activity;
}

Expand All @@ -164,11 +145,7 @@ protected function normalizeCauser($modelOrId): Model
return $modelOrId;
}

if (starts_with(app()->version(), '5.1')) {
$model = $this->auth->driver($this->authDriver)->getProvider()->retrieveById($modelOrId);
} else {
$model = $this->auth->guard($this->authDriver)->getProvider()->retrieveById($modelOrId);
}
$model = $this->auth->guard($this->authDriver)->getProvider()->retrieveById($modelOrId);

if ($model) {
return $model;
Expand All @@ -177,7 +154,7 @@ protected function normalizeCauser($modelOrId): Model
throw CouldNotLogActivity::couldNotDetermineUser($modelOrId);
}

protected function replacePlaceholders(string $description, Activity $activity): string
protected function replacePlaceholders(string $description, ActivityContract $activity): string
{
return preg_replace_callback('/:[a-z0-9._-]+/i', function ($match) use ($activity) {
$match = $match[0];
Expand All @@ -201,4 +178,17 @@ protected function replacePlaceholders(string $description, Activity $activity):
return array_get($attributeValue, $propertyName, $match);
}, $description);
}

protected function getActivity(): ActivityContract
{
if (! $this->activity instanceof ActivityContract) {
$this->activity = ActivitylogServiceProvider::getActivityModelInstance();
$this
->useLog($this->defaultLogName)
->withProperties([])
->causedBy($this->auth->guard($this->authDriver)->user());
}

return $this->activity;
}
}
3 changes: 2 additions & 1 deletion src/ActivitylogServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
use Spatie\Activitylog\Contracts\Activity;
use Spatie\Activitylog\Exceptions\InvalidConfiguration;
use Spatie\Activitylog\Models\Activity as ActivityModel;
use Spatie\Activitylog\Contracts\Activity as ActivityContract;

class ActivitylogServiceProvider extends ServiceProvider
{
Expand Down Expand Up @@ -52,7 +53,7 @@ public static function determineActivityModel(): string
return $activityModel;
}

public static function getActivityModelInstance(): Model
public static function getActivityModelInstance(): ActivityContract
{
$activityModelClassName = self::determineActivityModel();

Expand Down
11 changes: 8 additions & 3 deletions src/Traits/LogsActivity.php
Original file line number Diff line number Diff line change
Expand Up @@ -31,11 +31,16 @@ protected static function bootLogsActivity()
return;
}

app(ActivityLogger::class)
$logger = app(ActivityLogger::class)
->useLog($logName)
->performedOn($model)
->withProperties($model->attributeValuesToBeLogged($eventName))
->log($description);
->withProperties($model->attributeValuesToBeLogged($eventName));

if (method_exists($model, 'tapActivity')) {
$logger->tap([$model, 'tapActivity'], $eventName);
}

$logger->log($description);
});
});
}
Expand Down
26 changes: 25 additions & 1 deletion tests/ActivityloggerTest.php → tests/ActivityLoggerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,14 @@
namespace Spatie\Activitylog\Test;

use Auth;
use Carbon\Carbon;
use Illuminate\Support\Collection;
use Spatie\Activitylog\Models\Activity;
use Spatie\Activitylog\Test\Models\User;
use Spatie\Activitylog\Test\Models\Article;
use Spatie\Activitylog\Exceptions\CouldNotLogActivity;

class ActivityloggerTest extends TestCase
class ActivityLoggerTest extends TestCase
{
/** @var string */
protected $activityDescription;
Expand Down Expand Up @@ -273,4 +274,27 @@ public function it_accepts_null_parameter_for_caused_by()

$this->markTestAsPassed();
}

/** @test */
public function it_can_log_activity_when_attributes_are_changed_with_tap()
{
$properties = [
'property' => [
'subProperty' => 'value',
],
];

activity()
->tap(function (Activity $activity) use ($properties) {
$activity->properties = collect($properties);
$activity->created_at = Carbon::yesterday()->startOfDay();
})
->log($this->activityDescription);

$firstActivity = Activity::first();

$this->assertInstanceOf(Collection::class, $firstActivity->properties);
$this->assertEquals('value', $firstActivity->getExtraProperty('property.subProperty'));
$this->assertEquals(Carbon::yesterday()->startOfDay()->format('Y-m-d H:i:s'), $firstActivity->created_at->format('Y-m-d H:i:s'));
}
}
34 changes: 34 additions & 0 deletions tests/LogsActivityTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

namespace Spatie\Activitylog\Test;

use Carbon\Carbon;
use Illuminate\Support\Collection;
use Spatie\Activitylog\Models\Activity;
use Spatie\Activitylog\Test\Models\User;
use Spatie\Activitylog\Test\Models\Article;
Expand Down Expand Up @@ -296,6 +298,38 @@ public function it_can_log_activity_on_subject_by_same_causer()
$this->assertCount(1, $user->actions);
}

/** @test */
public function it_can_log_activity_when_attributes_are_changed_with_tap()
{
$model = new class() extends Article {
use LogsActivity;

protected $properties = [
'property' => [
'subProperty' => 'value',
],
];

public function tapActivity(Activity $activity, string $eventName)
{
$properties = $this->properties;
$properties['event'] = $eventName;
$activity->properties = collect($properties);
$activity->created_at = Carbon::yesterday()->startOfDay();
}
};

$entity = new $model();
$entity->save();

$firstActivity = $entity->activities()->first();

$this->assertInstanceOf(Collection::class, $firstActivity->properties);
$this->assertEquals('value', $firstActivity->getExtraProperty('property.subProperty'));
$this->assertEquals('created', $firstActivity->getExtraProperty('event'));
$this->assertEquals(Carbon::yesterday()->startOfDay()->format('Y-m-d H:i:s'), $firstActivity->created_at->format('Y-m-d H:i:s'));
}

public function loginWithFakeUser()
{
$user = new $this->user();
Expand Down

0 comments on commit 2ed89a8

Please sign in to comment.