Dataset Viewer
Auto-converted to Parquet
language
stringclasses
1 value
code
stringlengths
101
1.92M
content
stringclasses
1 value
php
<?php namespace Spatie\Activitylog\Test; use AddBatchUuidColumnToActivityLogTable; use AddEventColumnToActivityLogTable; use CreateActivityLogTable; use Illuminate\Database\Schema\Blueprint; use Illuminate\Encryption\Encrypter; use Illuminate\Support\Facades\Schema; use Orchestra\Testbench\TestCase as OrchestraTestCase; use Spatie\Activitylog\ActivitylogServiceProvider; use Spatie\Activitylog\Models\Activity; use Spatie\Activitylog\Test\Models\Article; use Spatie\Activitylog\Test\Models\User; abstract class TestCase extends OrchestraTestCase { protected function setUp(): void { parent::setUp(); $this->setUpDatabase(); } protected function getPackageProviders($app) { return [ ActivitylogServiceProvider::class, ]; } public function getEnvironmentSetUp($app) { config()->set('activitylog.table_name', 'activity_log'); config()->set('activitylog.database_connection', 'sqlite'); config()->set('database.default', 'sqlite'); config()->set('database.connections.sqlite', [ 'driver' => 'sqlite', 'database' => ':memory:', ]); config()->set('auth.providers.users.model', User::class); config()->set('app.key', 'base64:'.base64_encode( Encrypter::generateKey(config()['app.cipher']) )); } protected function setUpDatabase(): void { $this->migrateActivityLogTable(); $this->createTables('articles', 'users'); $this->seedModels(Article::class, User::class); } protected function migrateActivityLogTable(): void { require_once __DIR__.'/../database/migrations/create_activity_log_table.php.stub'; require_once __DIR__.'/../database/migrations/add_event_column_to_activity_log_table.php.stub'; require_once __DIR__.'/../database/migrations/add_batch_uuid_column_to_activity_log_table.php.stub'; (new CreateActivityLogTable())->up(); (new AddEventColumnToActivityLogTable())->up(); (new AddBatchUuidColumnToActivityLogTable())->up(); } protected function createTables(...$tableNames): void { collect($tableNames)->each(function (string $tableName) { Schema::create($tableName, function (Blueprint $table) use ($tableName) { $table->increments('id'); $table->string('name')->nullable(); $table->string('text')->nullable(); $table->timestamps(); $table->softDeletes(); if ($tableName === 'articles') { $table->integer('user_id')->unsigned()->nullable(); $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade'); $table->text('json')->nullable(); $table->string('interval')->nullable(); $table->decimal('price')->nullable(); $table->string('status')->nullable(); } }); }); } protected function seedModels(...$modelClasses): void { collect($modelClasses)->each(function (string $modelClass) { foreach (range(1, 0) as $index) { $modelClass::create(['name' => "name {$index}"]); } }); } public function getLastActivity(): ?Activity { return Activity::all()->last(); } public function markTestAsPassed(): void { $this->assertTrue(true); } public function createArticle(): Article { $article = new $this->article(); $article->name = 'my name'; $article->save(); return $article; } public function loginWithFakeUser() { $user = new $this->user(); $user::find(1); $this->be($user); return $user; } }
php
<?php use Carbon\Carbon; use Illuminate\Database\Eloquent\SoftDeletes; use Illuminate\Foundation\Application; use Illuminate\Support\Collection; use Spatie\Activitylog\LogOptions; use Spatie\Activitylog\Models\Activity; use Spatie\Activitylog\Test\Enums\NonBackedEnum; use Spatie\Activitylog\Test\Models\Article; use Spatie\Activitylog\Test\Models\ArticleWithLogDescriptionClosure; use Spatie\Activitylog\Test\Models\Issue733; use Spatie\Activitylog\Test\Models\User; use Spatie\Activitylog\Traits\LogsActivity; beforeEach(function () { $this->article = new class() extends Article { use LogsActivity; use SoftDeletes; public function getActivitylogOptions(): LogOptions { return LogOptions::defaults(); } }; $this->user = new class() extends User { use LogsActivity; use SoftDeletes; public function getActivitylogOptions(): LogOptions { return LogOptions::defaults(); } }; $this->assertCount(0, Activity::all()); }); it('will log the creation of the model', function () { $article = $this->createArticle(); $this->assertCount(1, Activity::all()); $this->assertInstanceOf(get_class($this->article), $this->getLastActivity()->subject); $this->assertEquals($article->id, $this->getLastActivity()->subject->id); $this->assertEquals('created', $this->getLastActivity()->description); $this->assertEquals('created', $this->getLastActivity()->event); }); it('can skip logging model events if asked to', function () { $article = new $this->article(); $article->disableLogging(); $article->name = 'my name'; $article->save(); $this->assertCount(0, Activity::all()); $this->assertNull($this->getLastActivity()); }); it('can switch on activity logging after disabling it', function () { $article = new $this->article(); $article->disableLogging(); $article->name = 'my name'; $article->save(); $article->enableLogging(); $article->name = 'my new name'; $article->save(); $this->assertCount(1, Activity::all()); $this->assertInstanceOf(get_class($this->article), $this->getLastActivity()->subject); $this->assertEquals($article->id, $this->getLastActivity()->subject->id); $this->assertEquals('updated', $this->getLastActivity()->description); $this->assertEquals('updated', $this->getLastActivity()->event); }); it('can skip logging if asked to for update method', function () { $article = new $this->article(); $article->disableLogging()->update(['name' => 'How to log events']); $this->assertCount(0, Activity::all()); $this->assertNull($this->getLastActivity()); }); it('will log an update of the model', function () { $article = $this->createArticle(); $article->name = 'changed name'; $article->save(); $this->assertCount(2, Activity::all()); $this->assertInstanceOf(get_class($this->article), $this->getLastActivity()->subject); $this->assertEquals($article->id, $this->getLastActivity()->subject->id); $this->assertEquals('updated', $this->getLastActivity()->description); $this->assertEquals('updated', $this->getLastActivity()->event); }); it('it will log the replication of a model with softdeletes', function () { $article = $this->createArticle(); $replicatedArticle = $this->article::find($article->id)->replicate(); $replicatedArticle->save(); $activityItems = Activity::all(); $this->assertCount(2, $activityItems); $this->assertTrue($activityItems->every(fn (Activity $item): bool => $item->event === 'created' && $item->description === 'created' && get_class($this->article) === $item->subject_type && in_array($item->subject_id, [$article->id, $replicatedArticle->id]))); $this->assertEquals($article->id, $activityItems->first()->subject_id); $this->assertEquals($replicatedArticle->id, $activityItems->last()->subject_id); }); it('will log the deletion of a model without softdeletes', function () { $articleClass = new class() extends Article { use LogsActivity; public function getActivitylogOptions(): LogOptions { return LogOptions::defaults()->logOnly(['name']); } }; $article = new $articleClass(); $article->name = 'my name'; $article->save(); $this->assertEquals('created', $this->getLastActivity()->description); $this->assertEquals('created', $this->getLastActivity()->event); $article->delete(); $activity = $this->getLastActivity(); $this->assertEquals('deleted', $activity->description); $this->assertArrayHasKey('old', $activity->changes()); $this->assertEquals('my name', $activity->changes()['old']['name']); $this->assertArrayNotHasKey('attributes', $activity->changes()); $this->assertEquals('deleted', $activity->description); $this->assertEquals('deleted', $activity->event); }); it('will log the deletion of a model with softdeletes', function () { $article = $this->createArticle(); $article->delete(); $this->assertCount(2, Activity::all()); $this->assertEquals(get_class($this->article), $this->getLastActivity()->subject_type); $this->assertEquals($article->id, $this->getLastActivity()->subject_id); $this->assertEquals('deleted', $this->getLastActivity()->description); $this->assertEquals('deleted', $this->getLastActivity()->event); $article->forceDelete(); $this->assertCount(3, Activity::all()); $this->assertEquals('deleted', $this->getLastActivity()->description); $this->assertEquals('deleted', $this->getLastActivity()->event); $this->assertNull($article->fresh()); }); it('will log the restoring of a model with softdeletes', function () { $article = $this->createArticle(); $article->delete(); $article->restore(); $this->assertCount(3, Activity::all()); $this->assertEquals(get_class($this->article), $this->getLastActivity()->subject_type); $this->assertEquals($article->id, $this->getLastActivity()->subject_id); $this->assertEquals('restored', $this->getLastActivity()->description); $this->assertEquals('restored', $this->getLastActivity()->event); }); it('can fetch all activity for a model', function () { $article = $this->createArticle(); $article->name = 'changed name'; $article->save(); $activities = $article->activities; $this->assertCount(2, $activities); }); it('can fetch soft deleted models', function () { app()['config']->set('activitylog.subject_returns_soft_deleted_models', true); $article = $this->createArticle(); $article->name = 'changed name'; $article->save(); $article->delete(); $activities = $article->activities; $this->assertCount(3, $activities); $this->assertEquals(get_class($this->article), $this->getLastActivity()->subject_type); $this->assertEquals($article->id, $this->getLastActivity()->subject_id); $this->assertEquals('deleted', $this->getLastActivity()->description); $this->assertEquals('deleted', $this->getLastActivity()->event); $this->assertEquals('changed name', $this->getLastActivity()->subject->name); }); it('can log activity to log named in the model', function () { $articleClass = new class() extends Article { use LogsActivity; public function getActivitylogOptions(): LogOptions { return LogOptions::defaults() ->useLogName('custom_log'); } }; $article = new $articleClass(); $article->name = 'my name'; $article->save(); $this->assertSame('custom_log', Activity::latest()->first()->log_name); }); it('will not log an update of the model if only ignored attributes are changed', function () { $articleClass = new class() extends Article { use LogsActivity; public function getActivitylogOptions(): LogOptions { return LogOptions::defaults() ->dontLogIfAttributesChangedOnly(['text']); } }; $article = new $articleClass(); $article->name = 'my name'; $article->save(); $article->text = 'ignore me'; $article->save(); $this->assertCount(1, Activity::all()); $this->assertInstanceOf(get_class($articleClass), $this->getLastActivity()->subject); $this->assertEquals($article->id, $this->getLastActivity()->subject->id); $this->assertEquals('created', $this->getLastActivity()->description); $this->assertEquals('created', $this->getLastActivity()->event); }); it('will not fail if asked to replace from empty attribute', function () { $model = new class() extends Article { use LogsActivity; use SoftDeletes; public function getActivitylogOptions(): LogOptions { return LogOptions::defaults() ->setDescriptionForEvent(fn (string $eventName): string => ":causer.name $eventName"); } }; $entity = new $model(); $entity->save(); $entity->name = 'my name'; $entity->save(); $activities = $entity->activities; $this->assertCount(2, $activities); $this->assertEquals($entity->id, $activities[0]->subject->id); $this->assertEquals($entity->id, $activities[1]->subject->id); $this->assertEquals(':causer.name created', $activities[0]->description); $this->assertEquals(':causer.name updated', $activities[1]->description); }); it('can log activity on subject by same causer', function () { $user = $this->loginWithFakeUser(); $user->name = 'LogsActivity Name'; $user->save(); $this->assertCount(1, Activity::all()); $this->assertInstanceOf(get_class($this->user), $this->getLastActivity()->subject); $this->assertEquals($user->id, $this->getLastActivity()->subject->id); $this->assertEquals($user->id, $this->getLastActivity()->causer->id); $this->assertCount(1, $user->activities); $this->assertCount(1, $user->actions); }); it('can log activity when attributes are changed with tap', function () { $model = new class() extends Article { use LogsActivity; public function getActivitylogOptions(): LogOptions { return LogOptions::defaults(); } 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->description); $this->assertEquals('created', $firstActivity->event); $this->assertEquals(Carbon::yesterday()->startOfDay()->format('Y-m-d H:i:s'), $firstActivity->created_at->format('Y-m-d H:i:s')); }); it('can log activity when description is changed with tap', function () { $model = new class() extends Article { use LogsActivity; public function getActivitylogOptions(): LogOptions { return LogOptions::defaults(); } public function tapActivity(Activity $activity, string $eventName) { $activity->description = 'my custom description'; } }; $entity = new $model(); $entity->save(); $firstActivity = $entity->activities()->first(); $this->assertEquals('my custom description', $firstActivity->description); }); it('can log activity when event is changed with tap', function () { $model = new class() extends Article { use LogsActivity; public function getActivitylogOptions(): LogOptions { return LogOptions::defaults(); } public function tapActivity(Activity $activity, string $eventName) { $activity->event = 'my custom event'; } }; $entity = new $model(); $entity->save(); $firstActivity = $entity->activities()->first(); $this->assertEquals('my custom event', $firstActivity->event); }); it('will not submit log when there is no changes', function () { $model = new class() extends Article { use LogsActivity; public function getActivitylogOptions(): LogOptions { return LogOptions::defaults() ->logOnly(['text']) ->dontSubmitEmptyLogs() ->logOnlyDirty(); } }; $entity = new $model(['text' => 'test']); $entity->save(); $this->assertCount(1, Activity::all()); $entity->name = 'my name'; $entity->save(); $this->assertCount(1, Activity::all()); }); it('will submit a log with json changes', function () { $model = new class() extends Article { use LogsActivity; protected $casts = [ 'json' => 'collection', ]; public function getActivitylogOptions(): LogOptions { return LogOptions::defaults() ->logOnly(['text', 'json->data']) ->dontSubmitEmptyLogs() ->logOnlyDirty(); } }; $entity = new $model([ 'text' => 'test', 'json' => [ 'data' => 'oldish', ], ]); $entity->save(); $this->assertCount(1, Activity::all()); $entity->json = [ 'data' => 'chips', 'irrelevant' => 'should not be', ]; $entity->save(); $expectedChanges = [ 'attributes' => [ 'json' => [ 'data' => 'chips', ], ], 'old' => [ 'json' => [ 'data' => 'oldish', ], ], ]; $changes = $this->getLastActivity()->changes()->toArray(); $this->assertCount(2, Activity::all()); $this->assertSame($expectedChanges, $changes); }); it('will log the retrieval of the model', function () { $article = Issue733::create(['name' => 'my name']); $retrieved = Issue733::whereKey($article->getKey())->first(); $this->assertTrue($article->is($retrieved)); $activity = $this->getLastActivity(); $this->assertInstanceOf(get_class($article), $activity->subject); $this->assertTrue($article->is($activity->subject)); $this->assertEquals('retrieved', $activity->description); }); it('will not log casted attribute of the model if attribute raw values is used', function () { $articleClass = new class() extends Article { use LogsActivity; protected $casts = [ 'name' => 'encrypted', ]; public function getActivitylogOptions(): LogOptions { return LogOptions::defaults()->logOnly(['name'])->useAttributeRawValues(['name']); } }; $article = new $articleClass(); $article->name = 'my name'; $article->save(); $this->assertInstanceOf(get_class($articleClass), $this->getLastActivity()->subject); $this->assertEquals($article->id, $this->getLastActivity()->subject->id); $this->assertNotEquals($article->name, $this->getLastActivity()->properties['attributes']['name']); $this->assertEquals('created', $this->getLastActivity()->description); $this->assertEquals('created', $this->getLastActivity()->event); }); it('can be serialized', function () { $model = ArticleWithLogDescriptionClosure::create(['name' => 'foo']); $this->assertNotNull(serialize($model)); }); it('logs non backed enum casted attribute', function () { $articleClass = new class() extends Article { use LogsActivity; protected $casts = [ 'status' => NonBackedEnum::class, ]; public function getActivitylogOptions(): LogOptions { return LogOptions::defaults()->logOnly(['status']); } }; $article = new $articleClass(); $article->status = NonBackedEnum::Draft; $article->save(); $this->assertInstanceOf(get_class($articleClass), $this->getLastActivity()->subject); $this->assertEquals($article->id, $this->getLastActivity()->subject->id); $this->assertSame('Draft', $this->getLastActivity()->properties['attributes']['status']); $this->assertEquals('created', $this->getLastActivity()->description); $this->assertEquals('created', $this->getLastActivity()->event); })->skip( version_compare(PHP_VERSION, '8.1', '<') || version_compare(Application::VERSION, '9.0', '<'), "PHP < 8.1 doesn't support enums && Laravel < 9.0 doesn't support non-backed-enum casting" ); it('logs int backed enum casted attribute', function () { $articleClass = new class() extends Article { use LogsActivity; protected $casts = [ 'status' => \Spatie\Activitylog\Test\Enums\IntBackedEnum::class, ]; public function getActivitylogOptions(): LogOptions { return LogOptions::defaults()->logOnly(['status']); } }; $article = new $articleClass(); $article->status = \Spatie\Activitylog\Test\Enums\IntBackedEnum::Published; $article->save(); $this->assertInstanceOf(get_class($articleClass), $this->getLastActivity()->subject); $this->assertEquals($article->id, $this->getLastActivity()->subject->id); $this->assertSame(1, $this->getLastActivity()->properties['attributes']['status']); $this->assertEquals('created', $this->getLastActivity()->description); $this->assertEquals('created', $this->getLastActivity()->event); })->skip(version_compare(PHP_VERSION, '8.1', '<'), "PHP < 8.1 doesn't support enum"); it('logs string backed enum casted attribute', function () { $articleClass = new class() extends Article { use LogsActivity; protected $casts = [ 'status' => \Spatie\Activitylog\Test\Enums\StringBackedEnum::class, ]; public function getActivitylogOptions(): LogOptions { return LogOptions::defaults()->logOnly(['status']); } }; $article = new $articleClass(); $article->status = \Spatie\Activitylog\Test\Enums\StringBackedEnum::Draft; $article->save(); $this->assertInstanceOf(get_class($articleClass), $this->getLastActivity()->subject); $this->assertEquals($article->id, $this->getLastActivity()->subject->id); $this->assertSame('draft', $this->getLastActivity()->properties['attributes']['status']); $this->assertEquals('created', $this->getLastActivity()->description); $this->assertEquals('created', $this->getLastActivity()->event); })->skip(version_compare(PHP_VERSION, '8.1', '<'), "PHP < 8.1 doesn't support enum");
php
<?php use Spatie\Activitylog\Models\Activity; use Spatie\Activitylog\Test\Models\CustomTableNameOnActivityModel; it('uses the table name from the configuration', function () { $model = new Activity(); expect(config('activitylog.table_name'))->toEqual($model->getTable()); }); it('uses a custom table name', function () { $model = new Activity(); $newTableName = 'my_personal_activities'; $model->setTable($newTableName); $this->assertNotEquals($model->getTable(), config('activitylog.table_name')); expect($newTableName)->toEqual($model->getTable()); }); it('uses the table name from the model', function () { $model = new CustomTableNameOnActivityModel(); $this->assertNotEquals($model->getTable(), config('activitylog.table_name')); expect('custom_table_name')->toEqual($model->getTable()); });
php
<?php use Spatie\Activitylog\Test\Models\User; it('can get all activity for the causer', function () { $causer = User::first(); activity()->by($causer)->log('perform activity'); activity()->by($causer)->log('perform another activity'); expect($causer->actions)->toHaveCount(2); });
php
<?php use Carbon\Carbon; use Illuminate\Database\Eloquent\JsonEncodingException; use Illuminate\Support\Collection; use Spatie\Activitylog\Exceptions\CouldNotLogActivity; use Spatie\Activitylog\Facades\Activity as ActivityFacade; use Spatie\Activitylog\Facades\CauserResolver; use Spatie\Activitylog\LogOptions; use Spatie\Activitylog\Models\Activity; use Spatie\Activitylog\Test\Enums\NonBackedEnum; use Spatie\Activitylog\Test\Models\Article; use Spatie\Activitylog\Test\Models\User; use Spatie\Activitylog\Traits\LogsActivity; beforeEach(function () { $this->activityDescription = 'My activity'; }); it('can log an activity', function () { activity()->log($this->activityDescription); expect($this->getLastActivity()->description)->toEqual($this->activityDescription); }); it('can log an activity with facade', function () { ActivityFacade::log($this->activityDescription); expect($this->getLastActivity()->description)->toEqual($this->activityDescription); }); it('will not log an activity when the log is not enabled', function () { config(['activitylog.enabled' => false]); activity()->log($this->activityDescription); expect($this->getLastActivity())->toBeNull(); }); it('will log activity with a null log name', function () { config(['activitylog.default_log_name' => null]); activity()->log($this->activityDescription); expect($this->getLastActivity()->log_name)->toBeNull(); }); it('will log an activity when enabled option is null', function () { config(['activitylog.enabled' => null]); activity()->log($this->activityDescription); expect($this->getLastActivity()->description)->toEqual($this->activityDescription); }); it('will log to the default log by default', function () { activity()->log($this->activityDescription); expect($this->getLastActivity()->log_name)->toEqual(config('activitylog.default_log_name')); }); it('can log an activity to a specific log', function () { $customLogName = 'secondLog'; activity($customLogName)->log($this->activityDescription); expect($this->getLastActivity()->log_name)->toEqual($customLogName); activity()->useLog($customLogName)->log($this->activityDescription); expect($this->getLastActivity()->log_name)->toEqual($customLogName); }); it('can log an activity with a subject', function () { $subject = Article::first(); activity() ->performedOn($subject) ->log($this->activityDescription); $firstActivity = Activity::first(); expect($firstActivity->subject->id)->toEqual($subject->id); expect($firstActivity->subject)->toBeInstanceOf(Article::class); }); it('can log an activity with a causer', function () { $user = User::first(); activity() ->causedBy($user) ->log($this->activityDescription); $firstActivity = Activity::first(); expect($firstActivity->causer->id)->toEqual($user->id); expect($firstActivity->causer)->toBeInstanceOf(User::class); }); it('can log an activity with a causer other than user model', function () { $article = Article::first(); activity() ->causedBy($article) ->log($this->activityDescription); $firstActivity = Activity::first(); expect($firstActivity->causer->id)->toEqual($article->id); expect($firstActivity->causer)->toBeInstanceOf(Article::class); }); it('can log an activity with a causer that has been set from other context', function () { $causer = Article::first(); CauserResolver::setCauser($causer); $article = Article::first(); activity() ->log($this->activityDescription); $firstActivity = Activity::first(); expect($firstActivity->causer->id)->toEqual($article->id); expect($firstActivity->causer)->toBeInstanceOf(Article::class); }); it('can log an activity with a causer when there is no web guard', function () { config(['auth.guards.web' => null]); config(['auth.guards.foo' => ['driver' => 'session', 'provider' => 'users']]); config(['activitylog.default_auth_driver' => 'foo']); $user = User::first(); activity() ->causedBy($user) ->log($this->activityDescription); $firstActivity = Activity::first(); expect($firstActivity->causer->id)->toEqual($user->id); expect($firstActivity->causer)->toBeInstanceOf(User::class); }); it('can log activity with properties', function () { $properties = [ 'property' => [ 'subProperty' => 'value', ], ]; activity() ->withProperties($properties) ->log($this->activityDescription); $firstActivity = Activity::first(); expect($firstActivity->properties)->toBeInstanceOf(Collection::class); expect($firstActivity->getExtraProperty('property.subProperty'))->toEqual('value'); }); it('can log activity with null properties', function () { $properties = [ 'property' => null, ]; activity() ->withProperties($properties) ->log($this->activityDescription); $firstActivity = Activity::first(); expect($firstActivity->properties)->toBeInstanceOf(Collection::class); expect($firstActivity->getExtraProperty('property'))->toBeNull(); }); it('can log activity with a single properties', function () { activity() ->withProperty('key', 'value') ->log($this->activityDescription); $firstActivity = Activity::first(); expect($firstActivity->properties)->toBeInstanceOf(Collection::class); expect($firstActivity->getExtraProperty('key'))->toEqual('value'); expect($firstActivity->getExtraProperty('non_existant', 'default value'))->toEqual('default value'); }); it('can translate a given causer id to an object', function () { $userId = User::first()->id; activity() ->causedBy($userId) ->log($this->activityDescription); $firstActivity = Activity::first(); expect($firstActivity->causer)->toBeInstanceOf(User::class); expect($firstActivity->causer->id)->toEqual($userId); }); it('will throw an exception if it cannot translate a causer id', function () { $this->expectException(CouldNotLogActivity::class); activity()->causedBy(999); }); it('will use the logged in user as the causer by default', function () { $userId = 1; Auth::login(User::find($userId)); activity()->log('hello poetsvrouwman'); expect($this->getLastActivity()->causer)->toBeInstanceOf(User::class); expect($this->getLastActivity()->causer->id)->toEqual($userId); }); it('can log activity using an anonymous causer', function () { activity() ->causedByAnonymous() ->log('hello poetsvrouwman'); expect($this->getLastActivity()->causer_id)->toBeNull(); expect($this->getLastActivity()->causer_type)->toBeNull(); }); it('will override the logged in user as the causer when an anonymous causer is specified', function () { $userId = 1; Auth::login(User::find($userId)); activity() ->byAnonymous() ->log('hello poetsvrouwman'); expect($this->getLastActivity()->causer_id)->toBeNull(); expect($this->getLastActivity()->causer_type)->toBeNull(); }); it('can replace the placeholders', function () { $article = Article::create(['name' => 'article name']); $user = Article::create(['name' => 'user name']); activity() ->performedOn($article) ->causedBy($user) ->withProperties(['key' => 'value', 'key2' => ['subkey' => 'subvalue']]) ->log('Subject name is :subject.name, causer name is :causer.name and property key is :properties.key and sub key :properties.key2.subkey'); $expectedDescription = 'Subject name is article name, causer name is user name and property key is value and sub key subvalue'; expect($this->getLastActivity()->description)->toEqual($expectedDescription); }); it('can replace the placeholders with object properties and accessors', function () { $article = Article::create([ 'name' => 'article name', 'user_id' => User::first()->id, ]); $article->foo = new stdClass(); $article->foo->bar = new stdClass(); $article->foo->bar->baz = 'zal'; activity() ->performedOn($article) ->withProperties(['key' => 'value', 'key2' => ['subkey' => 'subvalue']]) ->log('Subject name is :subject.name, deeply nested property is :subject.foo.bar.baz, accessor property is :subject.owner_name'); $expectedDescription = 'Subject name is article name, deeply nested property is zal, accessor property is name 1'; expect($this->getLastActivity()->description)->toEqual($expectedDescription); }); it('can log an activity with event', function () { $article = Article::create(['name' => 'article name']); activity() ->performedOn($article) ->event('create') ->log('test event'); expect($this->getLastActivity()->event)->toEqual('create'); }); it('will not replace non placeholders', function () { $description = 'hello: :hello'; activity()->log($description); expect($this->getLastActivity()->description)->toEqual($description); }); it('returns an instance of the activity log after logging when using a custom model', function () { $activityClass = new class() extends Activity { }; $activityClassName = get_class($activityClass); app()['config']->set('activitylog.activity_model', $activityClassName); $activityModel = activity()->log('test'); expect($activityModel)->toBeInstanceOf($activityClassName); }); it('will not log an activity when the log is manually disabled', function () { activity()->disableLogging(); activity()->log($this->activityDescription); expect($this->getLastActivity())->toBeNull(); }); it('will log an activity when the log is manually enabled', function () { config(['activitylog.enabled' => false]); activity()->enableLogging(); activity()->log($this->activityDescription); expect($this->getLastActivity()->description)->toEqual($this->activityDescription); }); it('accepts null parameter for caused by', function () { activity()->causedBy(null)->log('nothing'); $this->markTestAsPassed(); }); it('can log activity when attributes are changed with tap', function () { $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(); expect($firstActivity->properties)->toBeInstanceOf(Collection::class); expect($firstActivity->getExtraProperty('property.subProperty'))->toEqual('value'); expect($firstActivity->created_at->format('Y-m-d H:i:s'))->toEqual(Carbon::yesterday()->startOfDay()->format('Y-m-d H:i:s')); }); it('will tap a subject', function () { $model = new class() extends Article { use LogsActivity; public function getActivitylogOptions(): LogOptions { return LogOptions::defaults(); } public function tapActivity(Activity $activity, string $eventName) { $activity->description = 'my custom description'; } }; activity() ->on($model) ->log($this->activityDescription); $firstActivity = Activity::first(); $this->assertEquals('my custom description', $firstActivity->description); }); it('will log a custom created at date time', function () { $activityDateTime = now()->subDays(10); activity() ->createdAt($activityDateTime) ->log('created'); $firstActivity = Activity::first(); expect($firstActivity->created_at->toAtomString())->toEqual($activityDateTime->toAtomString()); }); it('will disable logs for a callback', function () { $result = activity()->withoutLogs(function () { activity()->log('created'); return 'hello'; }); expect($this->getLastActivity())->toBeNull(); expect($result)->toEqual('hello'); }); it('will disable logs for a callback without affecting previous state', function () { activity()->withoutLogs(function () { activity()->log('created'); }); expect($this->getLastActivity())->toBeNull(); activity()->log('outer'); expect($this->getLastActivity()->description)->toEqual('outer'); }); it('will disable logs for a callback without affecting previous state even when already disabled', function () { activity()->disableLogging(); activity()->withoutLogs(function () { activity()->log('created'); }); expect($this->getLastActivity())->toBeNull(); activity()->log('outer'); expect($this->getLastActivity())->toBeNull(); }); it('will disable logs for a callback without affecting previous state even with exception', function () { activity()->disableLogging(); try { activity()->withoutLogs(function () { activity()->log('created'); throw new Exception('OH NO'); }); } catch (Exception $ex) { // } expect($this->getLastActivity())->toBeNull(); activity()->log('outer'); expect($this->getLastActivity())->toBeNull(); }); it('logs backed enums in properties', function () { activity() ->withProperties(['int_backed_enum' => \Spatie\Activitylog\Test\Enums\IntBackedEnum::Draft]) ->withProperty('string_backed_enum', \Spatie\Activitylog\Test\Enums\StringBackedEnum::Published) ->log($this->activityDescription); $this->assertSame(0, $this->getLastActivity()->properties['int_backed_enum']); $this->assertSame('published', $this->getLastActivity()->properties['string_backed_enum']); })->skip(version_compare(PHP_VERSION, '8.1', '<'), "PHP < 8.1 doesn't support enum"); it('does not log non backed enums in properties', function () { activity() ->withProperty('non_backed_enum', NonBackedEnum::Published) ->log($this->activityDescription); }) ->throws(JsonEncodingException::class) ->skip(version_compare(PHP_VERSION, '8.1', '<'), "PHP < 8.1 doesn't support enum");
php
<?php use Spatie\Activitylog\Models\Activity; use Spatie\Activitylog\Test\Models\CustomDatabaseConnectionOnActivityModel; it('uses the database connection from the configuration', function () { $model = new Activity(); expect(config('activitylog.database_connection'))->toEqual($model->getConnectionName()); }); it('uses a custom database connection', function () { $model = new Activity(); $model->setConnection('custom_sqlite'); $this->assertNotEquals($model->getConnectionName(), config('activitylog.database_connection')); expect('custom_sqlite')->toEqual($model->getConnectionName()); }); it('uses the default database connection when the one from configuration is null', function () { app()['config']->set('activitylog.database_connection', null); $model = new Activity(); expect($model->getConnection())->toBeInstanceOf('Illuminate\Database\SQLiteConnection'); }); it('uses the database connection from model', function () { $model = new CustomDatabaseConnectionOnActivityModel(); $this->assertNotEquals($model->getConnectionName(), config('activitylog.database_connection')); expect('custom_connection_name')->toEqual($model->getConnectionName()); });
php
<?php use Illuminate\Database\Eloquent\Relations\Relation; use Spatie\Activitylog\Models\Activity; use Spatie\Activitylog\Test\Models\Article; use Spatie\Activitylog\Test\Models\User; beforeEach(function () { collect(range(1, 5))->each(function (int $index) { $logName = "log{$index}"; activity($logName)->log('hello everybody'); }); }); it('provides a scope to get activities from a specific log', function () { $activityInLog3 = Activity::inLog('log3')->get(); expect($activityInLog3)->toHaveCount(1); expect($activityInLog3->first()->log_name)->toEqual('log3'); }); it('provides a scope to get log items from multiple logs', function () { $activity = Activity::inLog('log2', 'log4')->get(); expect($activity)->toHaveCount(2); expect($activity->first()->log_name)->toEqual('log2'); expect($activity->last()->log_name)->toEqual('log4'); }); it('provides a scope to get log items from multiple logs using an array', function () { $activity = Activity::inLog(['log1', 'log2'])->get(); expect($activity)->toHaveCount(2); expect($activity->first()->log_name)->toEqual('log1'); expect($activity->last()->log_name)->toEqual('log2'); }); it('provides a scope to get log items for a specific causer', function () { $subject = Article::first(); $causer = User::first(); activity()->on($subject)->by($causer)->log('Foo'); activity()->on($subject)->by(User::create([ 'name' => 'Another User', ]))->log('Bar'); $activities = Activity::causedBy($causer)->get(); expect($activities)->toHaveCount(1); expect($activities->first()->causer_id)->toEqual($causer->getKey()); expect($activities->first()->causer_type)->toEqual(get_class($causer)); expect($activities->first()->description)->toEqual('Foo'); }); it('provides a scope to get log items for a specific event', function () { $subject = Article::first(); activity() ->on($subject) ->event('create') ->log('Foo'); $activities = Activity::forEvent('create')->get(); expect($activities)->toHaveCount(1); expect($activities->first()->event)->toEqual('create'); }); it('provides a scope to get log items for a specific subject', function () { $subject = Article::first(); $causer = User::first(); activity()->on($subject)->by($causer)->log('Foo'); activity()->on(Article::create([ 'name' => 'Another article', ]))->by($causer)->log('Bar'); $activities = Activity::forSubject($subject)->get(); expect($activities)->toHaveCount(1); expect($activities->first()->subject_id)->toEqual($subject->getKey()); expect($activities->first()->subject_type)->toEqual(get_class($subject)); expect($activities->first()->description)->toEqual('Foo'); }); it('provides a scope to get log items for a specific morphmapped causer', function () { Relation::morphMap([ 'articles' => 'Spatie\Activitylog\Test\Models\Article', 'users' => 'Spatie\Activitylog\Test\Models\User', ]); $subject = Article::first(); $causer = User::first(); activity()->on($subject)->by($causer)->log('Foo'); activity()->on($subject)->by(User::create([ 'name' => 'Another User', ]))->log('Bar'); $activities = Activity::causedBy($causer)->get(); expect($activities)->toHaveCount(1); expect($activities->first()->causer_id)->toEqual($causer->getKey()); expect($activities->first()->causer_type)->toEqual('users'); expect($activities->first()->description)->toEqual('Foo'); Relation::morphMap([], false); }); it('provides a scope to get log items for a specific morphmapped subject', function () { Relation::morphMap([ 'articles' => 'Spatie\Activitylog\Test\Models\Article', 'users' => 'Spatie\Activitylog\Test\Models\User', ]); $subject = Article::first(); $causer = User::first(); activity()->on($subject)->by($causer)->log('Foo'); activity()->on(Article::create([ 'name' => 'Another article', ]))->by($causer)->log('Bar'); $activities = Activity::forSubject($subject)->get(); expect($activities)->toHaveCount(1); expect($activities->first()->subject_id)->toEqual($subject->getKey()); expect($activities->first()->subject_type)->toEqual('articles'); expect($activities->first()->description)->toEqual('Foo'); Relation::morphMap([], false); });
php
<?php use Spatie\Activitylog\Facades\LogBatch; use Illuminate\Support\Str; it('generates uuid after start and end batch properely', function () { LogBatch::startBatch(); $uuid = LogBatch::getUuid(); LogBatch::endBatch(); expect(LogBatch::isopen())->toBeFalse(); expect($uuid)->toBeString(); }); it('returns null uuid after end batch properely', function () { LogBatch::startBatch(); $uuid = LogBatch::getUuid(); LogBatch::endBatch(); expect(LogBatch::isopen())->toBeFalse(); $this->assertNotNull($uuid); expect(LogBatch::getUuid())->toBeNull(); }); it('generates a new uuid after starting new batch properly', function () { LogBatch::startBatch(); $firstBatchUuid = LogBatch::getUuid(); LogBatch::endBatch(); LogBatch::startBatch(); LogBatch::startBatch(); $secondBatchUuid = LogBatch::getUuid(); LogBatch::endBatch(); expect(LogBatch::isopen())->toBeTrue(); $this->assertNotNull($firstBatchUuid); $this->assertNotNull($secondBatchUuid); $this->assertNotEquals($firstBatchUuid, $secondBatchUuid); }); it('will not generate new uuid if start already started batch', function () { LogBatch::startBatch(); $firstUuid = LogBatch::getUuid(); LogBatch::startBatch(); $secondUuid = LogBatch::getUuid(); LogBatch::endBatch(); expect(LogBatch::isopen())->toBeTrue(); expect($secondUuid)->toEqual($firstUuid); }); it('will not generate uuid if end batch before starting', function () { LogBatch::endBatch(); $uuid = LogBatch::getUuid(); LogBatch::startBatch(); expect($uuid)->toBeNull(); }); it('can set uuid and start a batch', function () { $uuid = Str::uuid(); LogBatch::setBatch($uuid); expect(LogBatch::isOpen())->toBeTrue(); expect(LogBatch::getUuid())->toEqual($uuid); LogBatch::endBatch(); expect(LogBatch::isOpen())->toBeFalse(); }); it('can set uuid for already started batch', function () { $uuid = Str::uuid(); LogBatch::startBatch(); expect(LogBatch::isOpen())->toBeTrue(); $this->assertNotEquals($uuid, LogBatch::getUuid()); LogBatch::setBatch($uuid); expect(LogBatch::isOpen())->toBeTrue(); expect(LogBatch::getUuid())->toEqual($uuid); LogBatch::endBatch(); expect(LogBatch::isOpen())->toBeFalse(); }); it('will not return null uuid if end batch that started twice', function () { LogBatch::startBatch(); $firstUuid = LogBatch::getUuid(); LogBatch::startBatch(); LogBatch::endBatch(); $notNullUuid = LogBatch::getUuid(); $this->assertNotNull($firstUuid); $this->assertNotNull($notNullUuid); expect($notNullUuid)->toBe($firstUuid); }); it('will return null uuid if end batch that started twice properly', function () { LogBatch::startBatch(); $firstUuid = LogBatch::getUuid(); LogBatch::startBatch(); LogBatch::endBatch(); LogBatch::endBatch(); $nullUuid = LogBatch::getUuid(); $this->assertNotNull($firstUuid); expect($nullUuid)->toBeNull(); $this->assertNotSame($firstUuid, $nullUuid); });
php
<?php use Carbon\Carbon; use Carbon\CarbonInterval; use Illuminate\Database\Eloquent\SoftDeletes; use Illuminate\Support\Arr; use Spatie\Activitylog\Contracts\LoggablePipe; use Spatie\Activitylog\EventLogBag; use Spatie\Activitylog\LogBatch; use Spatie\Activitylog\LogOptions; use Spatie\Activitylog\Models\Activity; use Spatie\Activitylog\Test\Casts\IntervalCasts; use Spatie\Activitylog\Test\Models\Article; use Spatie\Activitylog\Test\Models\User; use Spatie\Activitylog\Traits\LogsActivity; beforeEach(function () { $this->article = new class() extends Article { use LogsActivity; public function getActivitylogOptions(): LogOptions { return LogOptions::defaults() ->logOnly(['name', 'text']); } }; $this->assertCount(0, Activity::all()); }); it('can store the values when creating a model', function () { $this->createArticle(); $expectedChanges = [ 'attributes' => [ 'name' => 'my name', 'text' => null, ], ]; $this->assertEquals($expectedChanges, $this->getLastActivity()->changes()->toArray()); }); it('deep diff check json field', function () { $articleClass = new class() extends Article { use LogsActivity; protected $casts = [ 'json' => 'collection', ]; public function getActivitylogOptions(): LogOptions { return LogOptions::defaults() ->dontSubmitEmptyLogs() ->logOnlyDirty() ->logOnly(['json->phone', 'json->details', 'json->address']); } }; $articleClass::addLogChange(new class() implements LoggablePipe { public function handle(EventLogBag $event, Closure $next): EventLogBag { if ($event->event === 'updated') { $event->changes['attributes']['json'] = array_udiff_assoc( $event->changes['attributes']['json'], $event->changes['old']['json'], function ($new, $old) { if ($old === null || $new === null) { return 0; } return $new <=> $old; } ); $event->changes['old']['json'] = collect($event->changes['old']['json']) ->only(array_keys($event->changes['attributes']['json'])) ->all(); } return $next($event); } }); $article = $articleClass::create([ 'name' => 'Hamburg', 'json' => ['details' => '', 'phone' => '1231231234', 'address' => 'new address'], ]); $article->update(['json' => ['details' => 'new details']]); $expectedChanges = [ 'attributes' => [ 'json' => [ 'details' => 'new details', ], ], 'old' => [ 'json' => [ 'details' => '', ], ], ]; $this->assertEquals($expectedChanges, $this->getLastActivity()->changes()->toArray()); }); it('detect changes for date inteval attributes', function () { $articleClass = new class() extends Article { use LogsActivity; protected $casts = [ 'interval' => IntervalCasts::class, ]; public function getActivitylogOptions(): LogOptions { return LogOptions::defaults() ->logOnly(['name', 'interval']) ->logOnlyDirty(); } }; $article = $articleClass::create([ 'name' => 'Hamburg', 'interval' => CarbonInterval::minute(), ]); $article->update(['name' => 'New name', 'interval' => CarbonInterval::month()]); $expectedChanges = [ 'attributes' => [ 'name' => 'New name', 'interval' => '1 month', ], 'old' => [ 'name' => 'Hamburg', 'interval' => '1 minute', ], ]; // test case when intervals changing from interval to another $this->assertEquals($expectedChanges, $this->getLastActivity()->changes()->toArray()); }); it('detect changes for null date inteval attributes', function () { $articleClass = new class() extends Article { use LogsActivity; protected $casts = [ 'interval' => IntervalCasts::class, ]; public function getActivitylogOptions(): LogOptions { return LogOptions::defaults() ->logAll() ->dontLogIfAttributesChangedOnly(['created_at', 'updated_at', 'deleted_at']) ->logOnlyDirty(); } }; $nullIntevalArticle = $articleClass::create([ 'name' => 'Hamburg', ]); $nullIntevalArticle->update(['name' => 'New name', 'interval' => CarbonInterval::month()]); $expectedChangesForNullInterval = [ 'attributes' => [ 'name' => 'New name', 'interval' => '1 month', ], 'old' => [ 'name' => 'Hamburg', 'interval' => null, ], ]; $this->assertEquals($expectedChangesForNullInterval, $this->getLastActivity()->changes()->toArray()); $intervalArticle = $articleClass::create([ 'name' => 'Hamburg', 'interval' => CarbonInterval::month(), ]); $intervalArticle->update(['name' => 'New name', 'interval' => null]); $expectedChangesForInterval = [ 'attributes' => [ 'name' => 'New name', 'interval' => null, ], 'old' => [ 'name' => 'Hamburg', 'interval' => '1 month', ], ]; $this->assertEquals($expectedChangesForInterval, $this->getLastActivity()->changes()->toArray()); }); it('can store the relation values when creating a model', function () { $articleClass = new class() extends Article { use LogsActivity; public function getActivitylogOptions(): LogOptions { return LogOptions::defaults() ->logOnly(['name', 'text', 'user.name']); } }; $user = User::create([ 'name' => 'user name', ]); $article = $articleClass::create([ 'name' => 'original name', 'text' => 'original text', 'user_id' => $user->id, ]); $article->name = 'updated name'; $article->text = 'updated text'; $article->save(); $expectedChanges = [ 'attributes' => [ 'name' => 'updated name', 'text' => 'updated text', 'user.name' => 'user name', ], 'old' => [ 'name' => 'original name', 'text' => 'original text', 'user.name' => 'user name', ], ]; $this->assertEquals($expectedChanges, $this->getLastActivity()->changes()->toArray()); }); it('retruns same uuid for all log changes under one batch', function () { $articleClass = new class() extends Article { use LogsActivity; use SoftDeletes; public function getActivitylogOptions(): LogOptions { return LogOptions::defaults() ->logOnly(['name', 'text']); } }; app(LogBatch::class)->startBatch(); $user = User::create([ 'name' => 'user name', ]); $article = $articleClass::create([ 'name' => 'original name', 'text' => 'original text', 'user_id' => $user->id, ]); $article->name = 'updated name'; $article->text = 'updated text'; $article->save(); $article->delete(); $article->forceDelete(); $batchUuid = app(LogBatch::class)->getUuid(); app(LogBatch::class)->endBatch(); $this->assertTrue(Activity::pluck('batch_uuid')->every(fn ($uuid) => $uuid === $batchUuid)); }); it('assigns new uuid for multiple change logs in different batches', function () { $articleClass = new class() extends Article { use LogsActivity; use SoftDeletes; public function getActivitylogOptions(): LogOptions { return LogOptions::defaults() ->logOnly(['name', 'text']); } }; app(LogBatch::class)->startBatch(); $uuidForCreatedEvent = app(LogBatch::class)->getUuid(); $user = User::create([ 'name' => 'user name', ]); $article = $articleClass::create([ 'name' => 'original name', 'text' => 'original text', 'user_id' => $user->id, ]); app(LogBatch::class)->endBatch(); $this->assertTrue(Activity::pluck('batch_uuid')->every(fn ($uuid) => $uuid === $uuidForCreatedEvent)); app(LogBatch::class)->startBatch(); $article->name = 'updated name'; $article->text = 'updated text'; $article->save(); $uuidForUpdatedEvents = app(LogBatch::class)->getUuid(); app(LogBatch::class)->endBatch(); $this->assertCount(1, Activity::where('description', 'updated')->get()); $this->assertEquals($uuidForUpdatedEvents, Activity::where('description', 'updated')->first()->batch_uuid); app(LogBatch::class)->startBatch(); $article->delete(); $article->forceDelete(); $uuidForDeletedEvents = app(LogBatch::class)->getUuid(); app(LogBatch::class)->endBatch(); $this->assertCount(2, Activity::where('batch_uuid', $uuidForDeletedEvents)->get()); $this->assertNotSame($uuidForCreatedEvent, $uuidForDeletedEvents); }); it('can removes key event if it was loggable', function () { $articleClass = new class() extends Article { use LogsActivity; public function getActivitylogOptions(): LogOptions { return LogOptions::defaults() ->logOnly(['name', 'text', 'user.name']); } }; $user = User::create([ 'name' => 'user name', ]); $articleClass::addLogChange(new class() implements LoggablePipe { public function handle(EventLogBag $event, Closure $next): EventLogBag { Arr::forget($event->changes, ['attributes.name', 'old.name']); return $next($event); } }); $article = $articleClass::create([ 'name' => 'original name', 'text' => 'original text', 'user_id' => $user->id, ]); $article->name = 'updated name'; $article->text = 'updated text'; $article->save(); $expectedChanges = [ 'attributes' => [ 'text' => 'updated text', 'user.name' => 'user name', ], 'old' => [ 'text' => 'original text', 'user.name' => 'user name', ], ]; $this->assertEquals($expectedChanges, $this->getLastActivity()->changes()->toArray()); }); it('can store empty relation when creating a model', function () { $articleClass = new class() extends Article { use LogsActivity; public function getActivitylogOptions(): LogOptions { return LogOptions::defaults() ->logOnly(['name', 'text', 'user.name']); } }; $user = User::create([ 'name' => 'user name', ]); $article = $articleClass::create([ 'name' => 'original name', 'text' => 'original text', ]); $article->name = 'updated name'; $article->text = 'updated text'; $article->save(); $expectedChanges = [ 'attributes' => [ 'name' => 'updated name', 'text' => 'updated text', 'user.name' => null, ], 'old' => [ 'name' => 'original name', 'text' => 'original text', 'user.name' => null, ], ]; $this->assertEquals($expectedChanges, $this->getLastActivity()->changes()->toArray()); }); it('can store the changes when updating a model', function () { $article = $this->createArticle(); $article->name = 'updated name'; $article->text = 'updated text'; $article->save(); $expectedChanges = [ 'attributes' => [ 'name' => 'updated name', 'text' => 'updated text', ], 'old' => [ 'name' => 'my name', 'text' => null, ], ]; $this->assertEquals($expectedChanges, $this->getLastActivity()->changes()->toArray()); }); it('can store dirty changes only', function () { $article = createDirtyArticle(); $article->name = 'updated name'; $article->save(); $expectedChanges = [ 'attributes' => [ 'name' => 'updated name', ], 'old' => [ 'name' => 'my name', ], ]; $this->assertEquals($expectedChanges, $this->getLastActivity()->changes()->toArray()); }); it('can store dirty changes for swapping values', function () { $article = createDirtyArticle(); $originalName = $article->name; $originalText = $article->text; $article->text = $originalName; $article->name = $originalText; $article->save(); $expectedChanges = [ 'attributes' => [ 'name' => $originalText, 'text' => $originalName, ], 'old' => [ 'name' => $originalName, 'text' => $originalText, ], ]; $this->assertEquals($expectedChanges, $this->getLastActivity()->changes()->toArray()); }); it('can store the changes when updating a related model', function () { $articleClass = new class() extends Article { use LogsActivity; public function getActivitylogOptions(): LogOptions { return LogOptions::defaults() ->logOnly(['name', 'text', 'user.name']); } }; $user = User::create([ 'name' => 'a name', ]); $anotherUser = User::create([ 'name' => 'another name', ]); $article = $articleClass::create([ 'name' => 'name', 'text' => 'text', 'user_id' => $user->id, ]); $article->user()->associate($anotherUser)->save(); $expectedChanges = [ 'attributes' => [ 'name' => 'name', 'text' => 'text', 'user.name' => 'another name', ], 'old' => [ 'name' => 'name', 'text' => 'text', 'user.name' => 'a name', ], ]; $this->assertEquals($expectedChanges, $this->getLastActivity()->changes()->toArray()); }); it('can store the changes when updating a snake case related model', function () { $articleClass = new class() extends Article { use LogsActivity; public function getActivitylogOptions(): LogOptions { return LogOptions::defaults() ->logOnly(['name', 'text', 'snakeUser.name']); } public function snake_user() { return $this->belongsTo(User::class, 'user_id'); } }; $user = User::create([ 'name' => 'a name', ]); $anotherUser = User::create([ 'name' => 'another name', ]); $article = $articleClass::create([ 'name' => 'name', 'text' => 'text', 'user_id' => $user->id, ]); $article->user()->associate($anotherUser)->save(); $expectedChanges = [ 'attributes' => [ 'name' => 'name', 'text' => 'text', 'snake_user.name' => 'another name', ], 'old' => [ 'name' => 'name', 'text' => 'text', 'snake_user.name' => 'a name', ], ]; $this->assertEquals($expectedChanges, $this->getLastActivity()->changes()->toArray()); }); it('can store the changes when updating a camel case related model', function () { $articleClass = new class() extends Article { use LogsActivity; public function getActivitylogOptions(): LogOptions { return LogOptions::defaults() ->logOnly(['name', 'text', 'camel_user.name']); } public function camelUser() { return $this->belongsTo(User::class, 'user_id'); } }; $user = User::create([ 'name' => 'a name', ]); $anotherUser = User::create([ 'name' => 'another name', ]); $article = $articleClass::create([ 'name' => 'name', 'text' => 'text', 'user_id' => $user->id, ]); $article->user()->associate($anotherUser)->save(); $expectedChanges = [ 'attributes' => [ 'name' => 'name', 'text' => 'text', 'camelUser.name' => 'another name', ], 'old' => [ 'name' => 'name', 'text' => 'text', 'camelUser.name' => 'a name', ], ]; $this->assertEquals($expectedChanges, $this->getLastActivity()->changes()->toArray()); }); it('can store the changes when updating a custom case related model', function () { $articleClass = new class() extends Article { use LogsActivity; public function getActivitylogOptions(): LogOptions { return LogOptions::defaults() ->logOnly(['name', 'text', 'Custom_Case_User.name']); } public function Custom_Case_User() { return $this->belongsTo(User::class, 'user_id'); } }; $user = User::create([ 'name' => 'a name', ]); $anotherUser = User::create([ 'name' => 'another name', ]); $article = $articleClass::create([ 'name' => 'name', 'text' => 'text', 'user_id' => $user->id, ]); $article->user()->associate($anotherUser)->save(); $expectedChanges = [ 'attributes' => [ 'name' => 'name', 'text' => 'text', 'Custom_Case_User.name' => 'another name', ], 'old' => [ 'name' => 'name', 'text' => 'text', 'Custom_Case_User.name' => 'a name', ], ]; $this->assertEquals($expectedChanges, $this->getLastActivity()->changes()->toArray()); }); it('can store the dirty changes when updating a related model', function () { $articleClass = new class() extends Article { use LogsActivity; public function getActivitylogOptions(): LogOptions { return LogOptions::defaults() ->logOnly(['name', 'text', 'user.name']) ->logOnlyDirty(); } }; $user = User::create([ 'name' => 'a name', ]); $anotherUser = User::create([ 'name' => 'another name', ]); $article = $articleClass::create([ 'name' => 'name', 'text' => 'text', 'user_id' => $user->id, ]); $article->user()->associate($anotherUser)->save(); $expectedChanges = [ 'attributes' => [ 'user.name' => 'another name', ], 'old' => [ 'user.name' => 'a name', ], ]; $this->assertEquals($expectedChanges, $this->getLastActivity()->changes()->toArray()); }); it('can store the changes when saving including multi level related model', function () { $articleClass = new class() extends Article { use LogsActivity; public function getActivitylogOptions(): LogOptions { return LogOptions::defaults() ->logOnly(['name', 'text', 'user.latest_article.name']) ->logOnlyDirty(); } }; $user = User::create([ 'name' => 'a name', ]); $articleClass::create([ 'name' => 'name #1', 'text' => 'text #1', 'user_id' => $user->id, ]); $articleClass::create([ 'name' => 'name #2', 'text' => 'text #2', 'user_id' => $user->id, ]); $expectedChanges = [ 'attributes' => [ 'name' => 'name #2', 'text' => 'text #2', 'user.latestArticle.name' => 'name #1', ], ]; $this->assertEquals($expectedChanges, $this->getLastActivity()->changes()->toArray()); }); it('will store no changes when not logging attributes', function () { $articleClass = new class() extends Article { use LogsActivity; public function getActivitylogOptions(): LogOptions { return LogOptions::defaults() ->logOnly([]); } }; $article = new $articleClass(); $article->name = 'updated name'; $article->save(); $this->assertEquals(collect(), $this->getLastActivity()->changes()); }); it('will store the values when deleting the model', function () { $article = $this->createArticle(); $article->delete(); $expectedChanges = collect([ 'old' => [ 'name' => 'my name', 'text' => null, ], ]); $this->assertEquals('deleted', $this->getLastActivity()->description); $this->assertEquals($expectedChanges, $this->getLastActivity()->changes()); }); it('will store the values when deleting the model with softdeletes', function () { $articleClass = new class() extends Article { use LogsActivity; use SoftDeletes; public function getActivitylogOptions(): LogOptions { return LogOptions::defaults() ->logOnly(['name', 'text']); } }; $article = new $articleClass(); $article->name = 'my name'; $article->save(); $article->delete(); $expectedChanges = collect([ 'old' => [ 'name' => 'my name', 'text' => null, ], ]); $this->assertEquals('deleted', $this->getLastActivity()->description); $this->assertEquals($expectedChanges, $this->getLastActivity()->changes()); $article->forceDelete(); $expectedChanges = collect([ 'old' => [ 'name' => 'my name', 'text' => null, ], ]); $activities = $article->activities; $this->assertCount(3, $activities); $this->assertEquals('deleted', $this->getLastActivity()->description); $this->assertEquals($expectedChanges, $this->getLastActivity()->changes()); }); it('can store the changes of collection casted properties', function () { $articleClass = new class() extends Article { use LogsActivity; protected $casts = ['json' => 'collection']; public function getActivitylogOptions(): LogOptions { return LogOptions::defaults() ->logOnly(['json']) ->logOnlyDirty(); } }; $article = $articleClass::create([ 'json' => ['value' => 'original'], ]); $article->json = collect(['value' => 'updated']); $article->save(); $expectedChanges = [ 'attributes' => [ 'json' => [ 'value' => 'updated', ], ], 'old' => [ 'json' => [ 'value' => 'original', ], ], ]; $this->assertEquals($expectedChanges, $this->getLastActivity()->changes()->toArray()); }); it('can store the changes of array casted properties', function () { $articleClass = new class() extends Article { use LogsActivity; protected $casts = ['json' => 'array']; public function getActivitylogOptions(): LogOptions { return LogOptions::defaults() ->logOnly(['json']) ->logOnlyDirty(); } }; $article = $articleClass::create([ 'json' => ['value' => 'original'], ]); $article->json = collect(['value' => 'updated']); $article->save(); $expectedChanges = [ 'attributes' => [ 'json' => [ 'value' => 'updated', ], ], 'old' => [ 'json' => [ 'value' => 'original', ], ], ]; $this->assertEquals($expectedChanges, $this->getLastActivity()->changes()->toArray()); }); it('can store the changes of json casted properties', function () { $articleClass = new class() extends Article { use LogsActivity; protected $casts = ['json' => 'json']; public function getActivitylogOptions(): LogOptions { return LogOptions::defaults() ->logOnly(['json']) ->logOnlyDirty(); } }; $article = $articleClass::create([ 'json' => ['value' => 'original'], ]); $article->json = collect(['value' => 'updated']); $article->save(); $expectedChanges = [ 'attributes' => [ 'json' => [ 'value' => 'updated', ], ], 'old' => [ 'json' => [ 'value' => 'original', ], ], ]; $this->assertEquals($expectedChanges, $this->getLastActivity()->changes()->toArray()); }); it('can use nothing as loggable attributes', function () { $articleClass = new class() extends Article { use LogsActivity; protected $fillable = ['name', 'text']; public function getActivitylogOptions(): LogOptions { return LogOptions::defaults() ->dontLogFillable(); } }; $article = new $articleClass(); $article->name = 'my name'; $article->text = 'my text'; $article->save(); $expectedChanges = []; $this->assertEquals($expectedChanges, $this->getLastActivity()->changes()->toArray()); }); it('can use text as loggable attributes', function () { $articleClass = new class() extends Article { use LogsActivity; protected $fillable = ['name', 'text']; public function getActivitylogOptions(): LogOptions { return LogOptions::defaults() ->logOnly(['text']) ->dontLogFillable(); } }; $article = new $articleClass(); $article->name = 'my name'; $article->text = 'my text'; $article->save(); $expectedChanges = [ 'attributes' => [ 'text' => 'my text', ], ]; $this->assertEquals($expectedChanges, $this->getLastActivity()->changes()->toArray()); }); it('can use fillable as loggable attributes', function () { $articleClass = new class() extends Article { use LogsActivity; protected $fillable = ['name', 'text']; public function getActivitylogOptions(): LogOptions { return LogOptions::defaults() ->logFillable(); } }; $article = new $articleClass(); $article->name = 'my name'; $article->save(); $expectedChanges = [ 'attributes' => [ 'name' => 'my name', 'text' => null, ], ]; $this->assertEquals($expectedChanges, $this->getLastActivity()->changes()->toArray()); }); it('can use both fillable and log attributes', function () { $articleClass = new class() extends Article { use LogsActivity; protected $fillable = ['name']; public function getActivitylogOptions(): LogOptions { return LogOptions::defaults() ->logOnly(['text']) ->logFillable(); } }; $article = new $articleClass(); $article->name = 'my name'; $article->text = 'my text'; $article->save(); $expectedChanges = [ 'attributes' => [ 'name' => 'my name', 'text' => 'my text', ], ]; $this->assertEquals($expectedChanges, $this->getLastActivity()->changes()->toArray()); }); it('can use wildcard for loggable attributes', function () { $articleClass = new class() extends Article { use LogsActivity; public function getActivitylogOptions(): LogOptions { return LogOptions::defaults() ->logAll(); } }; $article = new $articleClass(); $article->name = 'my name'; Carbon::setTestNow(Carbon::create(2017, 1, 1, 12, 0, 0)); $article->save(); $expectedChanges = [ 'attributes' => [ 'name' => 'my name', 'text' => null, 'deleted_at' => null, 'id' => $article->id, 'user_id' => null, 'json' => null, 'price' => null, 'interval' => null, 'status' => null, 'created_at' => '2017-01-01T12:00:00.000000Z', 'updated_at' => '2017-01-01T12:00:00.000000Z', ], ]; $this->assertEquals($expectedChanges, $this->getLastActivity()->changes()->toArray()); }); it('can use wildcard with relation', function () { $articleClass = new class() extends Article { use LogsActivity; public function getActivitylogOptions(): LogOptions { return LogOptions::defaults() ->logOnly(['*', 'user.name']); } }; $user = User::create([ 'name' => 'user name', ]); Carbon::setTestNow(Carbon::create(2017, 1, 1, 12, 0, 0)); $article = $articleClass::create([ 'name' => 'article name', 'text' => 'article text', 'user_id' => $user->id, ]); $expectedChanges = [ 'attributes' => [ 'id' => $article->id, 'name' => 'article name', 'text' => 'article text', 'deleted_at' => null, 'user_id' => $user->id, 'json' => null, 'price' => null, 'created_at' => '2017-01-01T12:00:00.000000Z', 'updated_at' => '2017-01-01T12:00:00.000000Z', 'user.name' => 'user name', 'interval' => null, 'status' => null, ], ]; $this->assertEquals($expectedChanges, $this->getLastActivity()->changes()->toArray()); }); it('can use wildcard when updating model', function () { $articleClass = new class() extends Article { use LogsActivity; public function getActivitylogOptions(): LogOptions { return LogOptions::defaults() ->logAll() ->logOnlyDirty(); } }; $user = User::create([ 'name' => 'user name', ]); Carbon::setTestNow(Carbon::create(2017, 1, 1, 12, 0, 0)); $article = $articleClass::create([ 'name' => 'article name', 'text' => 'article text', 'user_id' => $user->id, ]); $article->name = 'changed name'; Carbon::setTestNow(Carbon::create(2018, 1, 1, 12, 0, 0)); $article->save(); $expectedChanges = [ 'attributes' => [ 'name' => 'changed name', 'updated_at' => '2018-01-01T12:00:00.000000Z', ], 'old' => [ 'name' => 'article name', 'updated_at' => '2017-01-01T12:00:00.000000Z', ], ]; $this->assertEquals($expectedChanges, $this->getLastActivity()->changes()->toArray()); }); it('can store the changes when a boolean field is changed from false to null', function () { $articleClass = new class() extends Article { use LogsActivity; protected $casts = [ 'text' => 'boolean', ]; public function getActivitylogOptions(): LogOptions { return LogOptions::defaults() ->logAll() ->logOnlyDirty(); } }; $user = User::create([ 'name' => 'user name', ]); Carbon::setTestNow(Carbon::create(2017, 1, 1, 12, 0, 0)); $article = $articleClass::create([ 'name' => 'article name', 'text' => false, 'user_id' => $user->id, ]); $article->text = null; Carbon::setTestNow(Carbon::create(2018, 1, 1, 12, 0, 0)); $article->save(); $expectedChanges = [ 'attributes' => [ 'text' => null, 'updated_at' => '2018-01-01T12:00:00.000000Z', ], 'old' => [ 'text' => false, 'updated_at' => '2017-01-01T12:00:00.000000Z', ], ]; $this->assertSame($expectedChanges, $this->getLastActivity()->changes()->toArray()); }); it('can use ignored attributes while updating', function () { $articleClass = new class() extends Article { use LogsActivity; public function getActivitylogOptions(): LogOptions { return LogOptions::defaults() ->logAll() ->logExcept(['name', 'updated_at']); } }; $article = new $articleClass(); $article->name = 'my name'; Carbon::setTestNow(Carbon::create(2017, 1, 1, 12, 0, 0)); $article->save(); $expectedChanges = [ 'attributes' => [ 'text' => null, 'deleted_at' => null, 'id' => $article->id, 'user_id' => null, 'json' => null, 'price' => null, 'interval' => null, 'status' => null, 'created_at' => '2017-01-01T12:00:00.000000Z', ], ]; $this->assertEquals($expectedChanges, $this->getLastActivity()->changes()->toArray()); }); it('can use unguarded as loggable attributes', function () { $articleClass = new class() extends Article { use LogsActivity; protected $guarded = ['text', 'json']; public function getActivitylogOptions(): LogOptions { return LogOptions::defaults() ->logUnguarded() ->logExcept(['id', 'created_at', 'updated_at', 'deleted_at']); } }; $article = new $articleClass(); $article->name = 'my name'; $article->text = 'my new text'; $article->save(); $expectedChanges = [ 'attributes' => [ 'name' => 'my name', 'user_id' => null, 'price' => null, 'interval' => null, 'status' => null, ], ]; $this->assertEquals($expectedChanges, $this->getLastActivity()->changes()->toArray()); }); it('will store no changes when wildcard guard and log unguarded attributes', function () { $articleClass = new class() extends Article { use LogsActivity; protected $guarded = ['*']; public function getActivitylogOptions(): LogOptions { return LogOptions::defaults() ->logUnguarded(); } }; $article = new $articleClass(); $article->name = 'my name'; $article->text = 'my new text'; $article->save(); $this->assertEquals([], $this->getLastActivity()->changes()->toArray()); }); it('can use hidden as loggable attributes', function () { $articleClass = new class() extends Article { use LogsActivity; protected $hidden = ['text']; protected $fillable = ['name', 'text']; public function getActivitylogOptions(): LogOptions { return LogOptions::defaults() ->logOnly(['name', 'text']); } }; $article = new $articleClass(); $article->name = 'my name'; $article->text = 'my text'; $article->save(); $expectedChanges = [ 'attributes' => [ 'name' => 'my name', 'text' => 'my text', ], ]; $this->assertEquals($expectedChanges, $this->getLastActivity()->changes()->toArray()); }); it('can use overloaded as loggable attributes', function () { $articleClass = new class() extends Article { use LogsActivity; protected $fillable = ['name', 'text']; public function getActivitylogOptions(): LogOptions { return LogOptions::defaults() ->logOnly(['name', 'text', 'description']); } public function setDescriptionAttribute($value) { $this->attributes['json'] = json_encode(['description' => $value]); } public function getDescriptionAttribute() { return Arr::get(json_decode($this->attributes['json'], true), 'description'); } }; $article = new $articleClass(); $article->name = 'my name'; $article->text = 'my text'; $article->description = 'my description'; $article->save(); $expectedChanges = [ 'attributes' => [ 'name' => 'my name', 'text' => 'my text', 'description' => 'my description', ], ]; $this->assertEquals($expectedChanges, $this->getLastActivity()->changes()->toArray()); }); it('can use mutated as loggable attributes', function () { $userClass = new class() extends User { use LogsActivity; protected $fillable = ['name', 'text']; public function getActivitylogOptions(): LogOptions { return LogOptions::defaults() ->logAll(); } public function setNameAttribute($value) { $this->attributes['name'] = strtoupper($value); } }; Carbon::setTestNow(Carbon::create(2017, 1, 1, 12, 0, 0)); $user = new $userClass(); $user->name = 'my name'; $user->text = 'my text'; $user->save(); $expectedChanges = [ 'attributes' => [ 'id' => $user->id, 'name' => 'MY NAME', 'text' => 'my text', 'created_at' => '2017-01-01T12:00:00.000000Z', 'updated_at' => '2017-01-01T12:00:00.000000Z', 'deleted_at' => null, ], ]; $this->assertEquals($expectedChanges, $this->getLastActivity()->changes()->toArray()); $user->name = 'my name 2'; $user->save(); $expectedChanges = [ 'old' => [ 'id' => $user->id, 'name' => 'MY NAME', 'text' => 'my text', 'created_at' => '2017-01-01T12:00:00.000000Z', 'updated_at' => '2017-01-01T12:00:00.000000Z', 'deleted_at' => null, ], 'attributes' => [ 'id' => $user->id, 'name' => 'MY NAME 2', 'text' => 'my text', 'created_at' => '2017-01-01T12:00:00.000000Z', 'updated_at' => '2017-01-01T12:00:00.000000Z', 'deleted_at' => null, ], ]; $this->assertEquals($expectedChanges, $this->getLastActivity()->changes()->toArray()); }); it('can use accessor as loggable attributes', function () { $userClass = new class() extends User { use LogsActivity; protected $fillable = ['name', 'text']; public function getActivitylogOptions(): LogOptions { return LogOptions::defaults() ->logAll(); } public function getNameAttribute($value) { return strtoupper($value); } }; Carbon::setTestNow(Carbon::create(2017, 1, 1, 12, 0, 0)); $user = new $userClass(); $user->name = 'my name'; $user->text = 'my text'; $user->save(); $expectedChanges = [ 'attributes' => [ 'id' => $user->id, 'name' => 'MY NAME', 'text' => 'my text', 'created_at' => '2017-01-01T12:00:00.000000Z', 'updated_at' => '2017-01-01T12:00:00.000000Z', 'deleted_at' => null, ], ]; $this->assertEquals($expectedChanges, $this->getLastActivity()->changes()->toArray()); $user->name = 'my name 2'; $user->save(); $expectedChanges = [ 'old' => [ 'id' => $user->id, 'name' => 'MY NAME', 'text' => 'my text', 'created_at' => '2017-01-01T12:00:00.000000Z', 'updated_at' => '2017-01-01T12:00:00.000000Z', 'deleted_at' => null, ], 'attributes' => [ 'id' => $user->id, 'name' => 'MY NAME 2', 'text' => 'my text', 'created_at' => '2017-01-01T12:00:00.000000Z', 'updated_at' => '2017-01-01T12:00:00.000000Z', 'deleted_at' => null, ], ]; $this->assertEquals($expectedChanges, $this->getLastActivity()->changes()->toArray()); }); it('can use encrypted as loggable attributes', function () { $userClass = new class() extends User { use LogsActivity; protected $fillable = ['name', 'text']; protected $encryptable = ['name', 'text']; public function getActivitylogOptions(): LogOptions { return LogOptions::defaults() ->logOnly(['name', 'text']); } public function getAttributeValue($key) { $value = parent::getAttributeValue($key); if (in_array($key, $this->encryptable)) { $value = decrypt($value); } return $value; } public function setAttribute($key, $value) { if (in_array($key, $this->encryptable)) { $value = encrypt($value); } return parent::setAttribute($key, $value); } }; Carbon::setTestNow(Carbon::create(2017, 1, 1, 12, 0, 0)); $user = new $userClass(); $user->name = 'my name'; $user->text = 'my text'; $user->save(); $expectedChanges = [ 'attributes' => [ 'name' => 'my name', 'text' => 'my text', ], ]; $this->assertEquals($expectedChanges, $this->getLastActivity()->changes()->toArray()); $user->name = 'my name 2'; $user->save(); $expectedChanges = [ 'old' => [ 'name' => 'my name', 'text' => 'my text', ], 'attributes' => [ 'name' => 'my name 2', 'text' => 'my text', ], ]; $this->assertEquals($expectedChanges, $this->getLastActivity()->changes()->toArray()); }); it('can use casted as loggable attribute', function () { $articleClass = new class() extends Article { use LogsActivity; protected $casts = [ 'price' => 'float', ]; public function getActivitylogOptions(): LogOptions { return LogOptions::defaults() ->logOnly(['name', 'text', 'price']) ->logOnlyDirty(); } }; $article = new $articleClass(); $article->name = 'my name'; $article->text = 'my text'; $article->price = '9.99'; $article->save(); $expectedChanges = [ 'attributes' => [ 'name' => 'my name', 'text' => 'my text', 'price' => 9.99, ], ]; $changes = $this->getLastActivity()->changes()->toArray(); $this->assertSame($expectedChanges, $changes); $this->assertIsFloat($changes['attributes']['price']); $article->price = 19.99; $article->save(); $expectedChanges = [ 'attributes' => [ 'price' => 19.99, ], 'old' => [ 'price' => 9.99, ], ]; $changes = $this->getLastActivity()->changes()->toArray(); $this->assertSame($expectedChanges, $changes); $this->assertIsFloat($changes['attributes']['price']); }); it('can use nullable date as loggable attributes', function () { $userClass = new class() extends User { use LogsActivity; use SoftDeletes; protected $fillable = ['name', 'text']; protected $dates = [ 'created_at', 'updated_at', 'deleted_at', ]; public function getActivitylogOptions(): LogOptions { return LogOptions::defaults() ->logAll(); } }; Carbon::setTestNow(Carbon::create(2017, 1, 1, 12, 0, 0)); $user = new $userClass(); $user->name = 'my name'; $user->text = 'my text'; $user->save(); $expectedChanges = [ 'attributes' => [ 'id' => $user->getKey(), 'name' => 'my name', 'text' => 'my text', 'created_at' => '2017-01-01T12:00:00.000000Z', 'updated_at' => '2017-01-01T12:00:00.000000Z', 'deleted_at' => null, ], ]; $this->assertEquals($expectedChanges, $this->getLastActivity()->changes()->toArray()); }); it('can use custom date cast as loggable attributes', function () { $userClass = new class() extends User { use LogsActivity; protected $fillable = ['name', 'text']; protected $casts = [ 'created_at' => 'date:d.m.Y', ]; public function getActivitylogOptions(): LogOptions { return LogOptions::defaults() ->logAll(); } }; Carbon::setTestNow(Carbon::create(2017, 1, 1, 12, 0, 0)); $user = new $userClass(); $user->name = 'my name'; $user->text = 'my text'; $user->save(); $expectedChanges = [ 'attributes' => [ 'id' => $user->getKey(), 'name' => 'my name', 'text' => 'my text', 'created_at' => '01.01.2017', 'updated_at' => '2017-01-01T12:00:00.000000Z', 'deleted_at' => null, ], ]; $this->assertEquals($expectedChanges, $this->getLastActivity()->changes()->toArray()); }); it('can use custom immutable date cast as loggable attributes', function () { $userClass = new class() extends User { use LogsActivity; protected $fillable = ['name', 'text']; protected $casts = [ 'created_at' => 'immutable_date:d.m.Y', ]; public function getActivitylogOptions(): LogOptions { return LogOptions::defaults() ->logAll(); } }; Carbon::setTestNow(Carbon::create(2017, 1, 1, 12, 0, 0)); $user = new $userClass(); $user->name = 'my name'; $user->text = 'my text'; $user->save(); $expectedChanges = [ 'attributes' => [ 'id' => $user->getKey(), 'name' => 'my name', 'text' => 'my text', 'created_at' => '01.01.2017', 'updated_at' => '2017-01-01T12:00:00.000000Z', 'deleted_at' => null, ], ]; $this->assertEquals($expectedChanges, $this->getLastActivity()->changes()->toArray()); }); it('can store the changes of json attributes', function () { $articleClass = new class() extends Article { use LogsActivity; protected $casts = [ 'json' => 'collection', ]; public function getActivitylogOptions(): LogOptions { return LogOptions::defaults() ->logOnly(['name', 'json->data']) ->logOnlyDirty(); } }; $article = new $articleClass(); $article->json = ['data' => 'test']; $article->name = 'I am JSON'; $article->save(); $expectedChanges = [ 'attributes' => [ 'name' => 'I am JSON', 'json' => [ 'data' => 'test', ], ], ]; $changes = $this->getLastActivity()->changes()->toArray(); $this->assertSame($expectedChanges, $changes); }); it('will not store changes to untracked json', function () { $articleClass = new class() extends Article { use LogsActivity; protected $casts = [ 'json' => 'collection', ]; public function getActivitylogOptions(): LogOptions { return LogOptions::defaults() ->logOnly(['name', 'json->data']) ->logOnlyDirty(); } }; $article = new $articleClass(); $article->json = ['unTracked' => 'test']; $article->name = 'a name'; $article->save(); $article->name = 'I am JSON'; $article->json = ['unTracked' => 'different string']; $article->save(); $expectedChanges = [ 'attributes' => [ 'name' => 'I am JSON', ], 'old' => [ 'name' => 'a name', ], ]; $changes = $this->getLastActivity()->changes()->toArray(); $this->assertSame($expectedChanges, $changes); }); it('will return null for missing json attribute', function () { $articleClass = new class() extends Article { use LogsActivity; protected $casts = [ 'json' => 'collection', ]; public function getActivitylogOptions(): LogOptions { return LogOptions::defaults() ->logOnly(['name', 'json->data->missing']) ->logOnlyDirty(); } }; $jsonToStore = []; $article = new $articleClass(); $article->json = $jsonToStore; $article->name = 'I am JSON'; $article->save(); data_set($jsonToStore, 'data.missing', 'I wasn\'t here'); $article->json = $jsonToStore; $article->save(); $expectedChanges = [ 'attributes' => [ 'json' => [ 'data' => [ 'missing' => 'I wasn\'t here', ], ], ], 'old' => [ 'json' => [ 'data' => [ 'missing' => null, ], ], ], ]; $changes = $this->getLastActivity()->changes()->toArray(); $this->assertSame($expectedChanges, $changes); }); it('will return an array for sub key in json attribute', function () { $articleClass = new class() extends Article { use LogsActivity; protected $casts = [ 'json' => 'collection', ]; public function getActivitylogOptions(): LogOptions { return LogOptions::defaults() ->logOnly(['name', 'json->data']) ->logOnlyDirty(); } }; $jsonToStore = [ 'data' => [ 'data_a' => 1, 'data_b' => 2, 'data_c' => 3, 'data_d' => 4, 'data_e' => 5, ], ]; $article = new $articleClass(); $article->json = $jsonToStore; $article->name = 'I am JSON'; $article->save(); data_set($jsonToStore, 'data.data_c', 'I Got The Key'); $article->json = $jsonToStore; $article->save(); $expectedChanges = [ 'attributes' => [ 'json' => [ 'data' => [ 'data_a' => 1, 'data_b' => 2, 'data_c' => 'I Got The Key', 'data_d' => 4, 'data_e' => 5, ], ], ], 'old' => [ 'json' => [ 'data' => [ 'data_a' => 1, 'data_b' => 2, 'data_c' => 3, 'data_d' => 4, 'data_e' => 5, ], ], ], ]; $changes = $this->getLastActivity()->changes()->toArray(); $this->assertSame($expectedChanges, $changes); }); it('will access further than level one json attribute', function () { $articleClass = new class() extends Article { use LogsActivity; protected $casts = [ 'json' => 'collection', ]; public function getActivitylogOptions(): LogOptions { return LogOptions::defaults() ->logOnly(['name', 'json->data->can->go->how->far']) ->logOnlyDirty(); } }; $jsonToStore = []; // data_set($jsonToStore, 'data.can.go.how.far', 'Data'); $article = new $articleClass(); $article->json = $jsonToStore; $article->name = 'I am JSON'; $article->save(); data_set($jsonToStore, 'data.can.go.how.far', 'This far'); $article->json = $jsonToStore; $article->save(); $expectedChanges = [ 'attributes' => [ 'json' => [ 'data' => [ 'can' => [ 'go' => [ 'how' => [ 'far' => 'This far', ], ], ], ], ], ], 'old' => [ 'json' => [ 'data' => [ 'can' => [ 'go' => [ 'how' => [ 'far' => null, ], ], ], ], ], ], ]; $changes = $this->getLastActivity()->changes()->toArray(); $this->assertSame($expectedChanges, $changes); }); function createDirtyArticle(): Article { $articleClass = new class() extends Article { use LogsActivity; public function getActivitylogOptions(): LogOptions { return LogOptions::defaults() ->logOnly(['name', 'text']) ->logOnlyDirty(); } }; $article = new $articleClass(); $article->name = 'my name'; $article->save(); return $article; } function getActivitylogOptions(): LogOptions { return LogOptions::defaults() ->logOnly(['name', 'text']) ->logOnlyDirty(); }
php
<?php use Spatie\Activitylog\Exceptions\InvalidConfiguration; use Spatie\Activitylog\Test\Models\Activity; use Spatie\Activitylog\Test\Models\AnotherInvalidActivity; use Spatie\Activitylog\Test\Models\InvalidActivity; beforeEach(function () { $this->activityDescription = 'My activity'; collect(range(1, 5))->each(function (int $index) { $logName = "log{$index}"; activity($logName)->log('hello everybody'); }); }); it('can log activity using a custom model', function () { app()['config']->set('activitylog.activity_model', Activity::class); $activity = activity()->log($this->activityDescription); expect($activity->description)->toEqual($this->activityDescription); expect($activity)->toBeInstanceOf(Activity::class); }); it('does not throw an exception when model config is null', function () { app()['config']->set('activitylog.activity_model', null); activity()->log($this->activityDescription); $this->markTestAsPassed(); }); it('throws an exception when model doesnt implements activity', function () { app()['config']->set('activitylog.activity_model', InvalidActivity::class); $this->expectException(InvalidConfiguration::class); activity()->log($this->activityDescription); }); it('throws an exception when model doesnt extend model', function () { app()['config']->set('activitylog.activity_model', AnotherInvalidActivity::class); $this->expectException(InvalidConfiguration::class); activity()->log($this->activityDescription); }); it('doesnt conlict with laravel change tracking', function () { app()['config']->set('activitylog.activity_model', Activity::class); $properties = [ 'attributes' => [ 'name' => 'my name', 'text' => null, ], ]; $activity = activity()->withProperties($properties)->log($this->activityDescription); expect($activity->changes()->toArray())->toEqual($properties); expect($activity->custom_property->toArray())->toEqual($properties); });
php
<?php use Illuminate\Support\Facades\Auth; use Spatie\Activitylog\Exceptions\CouldNotLogActivity; use Spatie\Activitylog\Facades\CauserResolver; use Spatie\Activitylog\Test\Models\Article; use Spatie\Activitylog\Test\Models\User; it('can resolve current logged in user', function () { Auth::login($user = User::first()); $causer = CauserResolver::resolve(); expect($causer)->toBeInstanceOf(User::class); expect($causer->id)->toEqual($user->id); }); it('will throw an exception if it cannot resolve user by id', function () { $this->expectException(CouldNotLogActivity::class); CauserResolver::resolve(9999); }); it('can resloved user from passed id', function () { $causer = CauserResolver::resolve(1); expect($causer)->toBeInstanceOf(User::class); expect($causer->id)->toEqual(1); }); it('will resolve the provided override callback', function () { CauserResolver::resolveUsing(fn () => Article::first()); $causer = CauserResolver::resolve(); expect($causer)->toBeInstanceOf(Article::class); expect($causer->id)->toEqual(1); }); it('will resolve any model', function () { $causer = CauserResolver::resolve($article = Article::first()); expect($causer)->toBeInstanceOf(Article::class); expect($causer->id)->toEqual($article->id); });
php
<?php use Carbon\Carbon; use Spatie\Activitylog\Models\Activity; beforeEach(function () { Carbon::setTestNow(Carbon::create(2016, 1, 1, 00, 00, 00)); app()['config']->set('activitylog.delete_records_older_than_days', 31); }); it('can clean the activity log', function () { collect(range(1, 60))->each(function (int $index) { Activity::create([ 'description' => "item {$index}", 'created_at' => Carbon::now()->subDays($index)->startOfDay(), ]); }); expect(Activity::all())->toHaveCount(60); Artisan::call('activitylog:clean'); expect(Activity::all())->toHaveCount(31); $cutOffDate = Carbon::now()->subDays(31)->format('Y-m-d H:i:s'); expect(Activity::where('created_at', '<', $cutOffDate)->get())->toHaveCount(0); }); it('can accept days as option to override config setting', function () { collect(range(1, 60))->each(function (int $index) { Activity::create([ 'description' => "item {$index}", 'created_at' => Carbon::now()->subDays($index)->startOfDay(), ]); }); expect(Activity::all())->toHaveCount(60); Artisan::call('activitylog:clean', ['--days' => 7]); expect(Activity::all())->toHaveCount(7); $cutOffDate = Carbon::now()->subDays(7)->format('Y-m-d H:i:s'); expect(Activity::where('created_at', '<', $cutOffDate)->get())->toHaveCount(0); });
php
<?php namespace Spatie\Activitylog\Test\Enums; enum StringBackedEnum: string { case Published = 'published'; case Draft = 'draft'; }
php
<?php namespace Spatie\Activitylog\Test\Enums; enum IntBackedEnum: int { case Published = 1; case Draft = 0; }
php
<?php namespace Spatie\Activitylog\Test\Enums; enum NonBackedEnum { case Published; case Draft; }
php
<?php namespace Spatie\Activitylog\Test\Casts; use Carbon\CarbonInterval; use Illuminate\Contracts\Database\Eloquent\CastsAttributes; class IntervalCasts implements CastsAttributes { public function get($model, string $key, $value, array $attributes) { if (empty($value)) { return null; } return (string) CarbonInterval::create($value); } public function set($model, string $key, $value, array $attributes) { if (empty($value)) { return null; } $value = is_string($value) ? CarbonInterval::create($value) : $value; return CarbonInterval::getDateIntervalSpec($value); } }
php
<?php namespace Spatie\Activitylog\Test\Models; use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\MorphTo; use Illuminate\Support\Arr; use Illuminate\Support\Collection; use Spatie\Activitylog\Contracts\Activity as ActivityContract; class Activity extends Model implements ActivityContract { protected $table; public $guarded = []; protected $casts = [ 'properties' => 'collection', ]; public function __construct(array $attributes = []) { $this->table = config('activitylog.table_name'); parent::__construct($attributes); } public function subject(): MorphTo { if (config('activitylog.subject_returns_soft_deleted_models')) { return $this->morphTo()->withTrashed(); } return $this->morphTo(); } public function causer(): MorphTo { return $this->morphTo(); } public function getExtraProperty(string $propertyName, mixed $defaultValue = null): mixed { return Arr::get($this->properties->toArray(), $propertyName, $defaultValue); } public function changes(): Collection { if (! $this->properties instanceof Collection) { return new Collection(); } return collect(array_filter($this->properties->toArray(), function ($key) { return in_array($key, ['attributes', 'old']); }, ARRAY_FILTER_USE_KEY)); } public function scopeInLog(Builder $query, ...$logNames): Builder { if (is_array($logNames[0])) { $logNames = $logNames[0]; } return $query->whereIn('log_name', $logNames); } public function scopeCausedBy(Builder $query, Model $causer): Builder { return $query ->where('causer_type', $causer->getMorphClass()) ->where('causer_id', $causer->getKey()); } public function scopeForSubject(Builder $query, Model $subject): Builder { return $query ->where('subject_type', $subject->getMorphClass()) ->where('subject_id', $subject->getKey()); } public function scopeForEvent(Builder $query, string $event): Builder { return $query->where('event', $event); } public function getCustomPropertyAttribute() { return $this->changes(); } }
php
<?php namespace Spatie\Activitylog\Test\Models; use Spatie\Activitylog\Models\Activity; class CustomDatabaseConnectionOnActivityModel extends Activity { protected $connection = 'custom_connection_name'; }
php
<?php namespace Spatie\Activitylog\Test\Models; use Spatie\Activitylog\LogOptions; use Spatie\Activitylog\Traits\LogsActivity; class ArticleWithLogDescriptionClosure extends Article { use LogsActivity; public function getActivitylogOptions(): LogOptions { return LogOptions::defaults() ->setDescriptionForEvent(function ($eventName) { return $eventName; }); } }
php
<?php namespace Spatie\Activitylog\Test\Models; use Spatie\Activitylog\LogOptions; use Spatie\Activitylog\Traits\LogsActivity; class Issue733 extends Article { use LogsActivity; protected static $recordEvents = [ 'retrieved', ]; public function getActivitylogOptions(): LogOptions { return LogOptions::defaults() ->dontSubmitEmptyLogs() ->logOnly(['name']); } }
php
<?php namespace Spatie\Activitylog\Test\Models; use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\MorphTo; use Illuminate\Support\Arr; use Illuminate\Support\Collection; use Spatie\Activitylog\Contracts\Activity as ActivityContract; class AnotherInvalidActivity implements ActivityContract { protected $table; public $guarded = []; protected $casts = [ 'properties' => 'collection', ]; public function __construct(array $attributes = []) { $this->table = config('activitylog.table_name'); } public function subject(): MorphTo { if (config('activitylog.subject_returns_soft_deleted_models')) { return $this->morphTo()->withTrashed(); } return $this->morphTo(); } public function causer(): MorphTo { return $this->morphTo(); } /** * Get the extra properties with the given name. * * @param string $propertyName * @param mixed $defaultValue * * @return mixed */ public function getExtraProperty(string $propertyName, mixed $defaultValue = null): mixed { return Arr::get($this->properties->toArray(), $propertyName, $defaultValue); } public function changes(): Collection { if (! $this->properties instanceof Collection) { return new Collection(); } return collect(array_filter($this->properties->toArray(), function ($key) { return in_array($key, ['attributes', 'old']); }, ARRAY_FILTER_USE_KEY)); } public function scopeInLog(Builder $query, ...$logNames): Builder { if (is_array($logNames[0])) { $logNames = $logNames[0]; } return $query->whereIn('log_name', $logNames); } /** * Scope a query to only include activities by a given causer. * * @param \Illuminate\Database\Eloquent\Builder $query * @param \Illuminate\Database\Eloquent\Model $causer * * @return \Illuminate\Database\Eloquent\Builder */ public function scopeCausedBy(Builder $query, Model $causer): Builder { return $query ->where('causer_type', $causer->getMorphClass()) ->where('causer_id', $causer->getKey()); } /** * Scope a query to only include activities for a given subject. * * @param \Illuminate\Database\Eloquent\Builder $query * @param \Illuminate\Database\Eloquent\Model $subject * * @return \Illuminate\Database\Eloquent\Builder */ public function scopeForSubject(Builder $query, Model $subject): Builder { return $query ->where('subject_type', $subject->getMorphClass()) ->where('subject_id', $subject->getKey()); } public function getCustomPropertyAttribute() { return $this->changes(); } public function scopeForEvent(Builder $query, string $event): Builder { return $query->where('event', $event); } }
php
<?php namespace Spatie\Activitylog\Test\Models; use Illuminate\Contracts\Auth\Authenticatable; use Illuminate\Database\Eloquent\Model; use Spatie\Activitylog\Traits\CausesActivity; class User extends Model implements Authenticatable { use CausesActivity; protected $table = 'users'; protected $guarded = []; protected $fillable = ['id', 'name']; public function getAuthIdentifierName() { return 'id'; } public function getAuthIdentifier() { $name = $this->getAuthIdentifierName(); return $this->attributes[$name]; } public function getAuthPasswordName() { return 'password'; } public function getAuthPassword() { return $this->attributes['password']; } public function getRememberToken() { return 'token'; } public function setRememberToken($value) { } public function getRememberTokenName() { return 'tokenName'; } public function articles() { return $this->hasMany(Article::class); } public function latestArticle() { return $this->hasOne(Article::class)->latest()->limit(1); } }
php
<?php namespace Spatie\Activitylog\Test\Models; use Spatie\Activitylog\Models\Activity; class CustomTableNameOnActivityModel extends Activity { protected $table = 'custom_table_name'; }
php
<?php namespace Spatie\Activitylog\Test\Models; use Illuminate\Database\Eloquent\Model; class Article extends Model { protected $table = 'articles'; protected $guarded = []; public function user() { return $this->belongsTo(User::class); } public function getOwnerNameAttribute() { return $this->user?->name; } }
php
<?php namespace Spatie\Activitylog\Test\Models; use Illuminate\Database\Eloquent\Model; class InvalidActivity extends Model { }
php
<?php return [ /* * If set to false, no activities will be saved to the database. */ 'enabled' => env('ACTIVITY_LOGGER_ENABLED', true), /* * When the clean-command is executed, all recording activities older than * the number of days specified here will be deleted. */ 'delete_records_older_than_days' => 365, /* * If no log name is passed to the activity() helper * we use this default log name. */ 'default_log_name' => 'default', /* * You can specify an auth driver here that gets user models. * If this is null we'll use the current Laravel auth driver. */ 'default_auth_driver' => null, /* * If set to true, the subject returns soft deleted models. */ 'subject_returns_soft_deleted_models' => false, /* * This model will be used to log activity. * It should implement the Spatie\Activitylog\Contracts\Activity interface * and extend Illuminate\Database\Eloquent\Model. */ 'activity_model' => \Spatie\Activitylog\Models\Activity::class, /* * This is the name of the table that will be created by the migration and * used by the Activity model shipped with this package. */ 'table_name' => env('ACTIVITY_LOGGER_TABLE_NAME', 'activity_log'), /* * This is the database connection that will be used by the migration and * the Activity model shipped with this package. In case it's not set * Laravel's database.default will be used instead. */ 'database_connection' => env('ACTIVITY_LOGGER_DB_CONNECTION'), ];
php
<?php namespace Spatie\Activitylog; use Closure; use Illuminate\Auth\AuthManager; use Illuminate\Contracts\Config\Repository; use Illuminate\Database\Eloquent\Model; use Spatie\Activitylog\Exceptions\CouldNotLogActivity; class CauserResolver { protected AuthManager $authManager; protected string | null $authDriver; protected Closure | null $resolverOverride = null; protected Model | null $causerOverride = null; public function __construct(Repository $config, AuthManager $authManager) { $this->authManager = $authManager; $this->authDriver = $config['activitylog']['default_auth_driver']; } public function resolve(Model | int | string | null $subject = null): ?Model { if ($this->causerOverride !== null) { return $this->causerOverride; } if ($this->resolverOverride !== null) { $resultCauser = ($this->resolverOverride)($subject); if (! $this->isResolvable($resultCauser)) { throw CouldNotLogActivity::couldNotDetermineUser($resultCauser); } return $resultCauser; } return $this->getCauser($subject); } protected function resolveUsingId(int | string $subject): Model { $guard = $this->authManager->guard($this->authDriver); $provider = method_exists($guard, 'getProvider') ? $guard->getProvider() : null; $model = method_exists($provider, 'retrieveById') ? $provider->retrieveById($subject) : null; throw_unless($model instanceof Model, CouldNotLogActivity::couldNotDetermineUser($subject)); return $model; } protected function getCauser(Model | int | string | null $subject = null): ?Model { if ($subject instanceof Model) { return $subject; } if (is_null($subject)) { return $this->getDefaultCauser(); } return $this->resolveUsingId($subject); } /** * Override the resover using callback. */ public function resolveUsing(Closure $callback): static { $this->resolverOverride = $callback; return $this; } /** * Override default causer. */ public function setCauser(?Model $causer): static { $this->causerOverride = $causer; return $this; } protected function isResolvable(mixed $model): bool { return $model instanceof Model || is_null($model); } protected function getDefaultCauser(): ?Model { return $this->authManager->guard($this->authDriver)->user(); } }
php
<?php namespace Spatie\Activitylog; use Illuminate\Database\Eloquent\Model; class EventLogBag { public function __construct( public string $event, public Model $model, public array $changes, public ?LogOptions $options = null ) { $this->options ??= $model->getActivitylogOptions(); } }
php
<?php namespace Spatie\Activitylog; use Closure; use Ramsey\Uuid\Uuid; class LogBatch { public ?string $uuid = null; public int $transactions = 0; protected function generateUuid(): string { return Uuid::uuid4()->toString(); } public function getUuid(): ?string { return $this->uuid; } public function setBatch(string $uuid): void { $this->uuid = $uuid; $this->transactions = 1; } public function withinBatch(Closure $callback): mixed { $this->startBatch(); $result = $callback($this->getUuid()); $this->endBatch(); return $result; } public function startBatch(): void { if (! $this->isOpen()) { $this->uuid = $this->generateUuid(); } $this->transactions++; } public function isOpen(): bool { return $this->transactions > 0; } public function endBatch(): void { $this->transactions = max(0, $this->transactions - 1); if ($this->transactions === 0) { $this->uuid = null; } } }
php
<?php namespace Spatie\Activitylog; use Illuminate\Database\Eloquent\Model; use Spatie\Activitylog\Contracts\Activity; use Spatie\Activitylog\Contracts\Activity as ActivityContract; use Spatie\Activitylog\Exceptions\InvalidConfiguration; use Spatie\Activitylog\Models\Activity as ActivityModel; use Spatie\LaravelPackageTools\Package; use Spatie\LaravelPackageTools\PackageServiceProvider; class ActivitylogServiceProvider extends PackageServiceProvider { public function configurePackage(Package $package): void { $package ->name('laravel-activitylog') ->hasConfigFile('activitylog') ->hasMigrations([ 'create_activity_log_table', 'add_event_column_to_activity_log_table', 'add_batch_uuid_column_to_activity_log_table', ]) ->hasCommand(CleanActivitylogCommand::class); } public function registeringPackage() { $this->app->bind(ActivityLogger::class); $this->app->scoped(LogBatch::class); $this->app->scoped(CauserResolver::class); $this->app->scoped(ActivityLogStatus::class); } public static function determineActivityModel(): string { $activityModel = config('activitylog.activity_model') ?? ActivityModel::class; if (! is_a($activityModel, Activity::class, true) || ! is_a($activityModel, Model::class, true)) { throw InvalidConfiguration::modelIsNotValid($activityModel); } return $activityModel; } public static function getActivityModelInstance(): ActivityContract { $activityModelClassName = self::determineActivityModel(); return new $activityModelClassName(); } }
php
<?php namespace Spatie\Activitylog; use Closure; class LogOptions { public ?string $logName = null; public bool $submitEmptyLogs = true; public bool $logFillable = false; public bool $logOnlyDirty = false; public bool $logUnguarded = false; public array $logAttributes = []; public array $logExceptAttributes = []; public array $dontLogIfAttributesChangedOnly = []; public array $attributeRawValues = []; public ?Closure $descriptionForEvent = null; /** * Start configuring model with the default options. */ public static function defaults(): self { return new static(); } /** * Log all attributes on the model. */ public function logAll(): self { return $this->logOnly(['*']); } /** * Log all attributes that are not listed in $guarded. */ public function logUnguarded(): self { $this->logUnguarded = true; return $this; } /** * log changes to all the $fillable attributes of the model. */ public function logFillable(): self { $this->logFillable = true; return $this; } /** * Stop logging $fillable attributes of the model. */ public function dontLogFillable(): self { $this->logFillable = false; return $this; } /** * Log changes that has actually changed after the update. */ public function logOnlyDirty(): self { $this->logOnlyDirty = true; return $this; } /** * Log changes only if these attributes changed. */ public function logOnly(array $attributes): self { $this->logAttributes = $attributes; return $this; } /** * Exclude these attributes from being logged. */ public function logExcept(array $attributes): self { $this->logExceptAttributes = $attributes; return $this; } /** * Don't trigger an activity if these attributes changed logged. */ public function dontLogIfAttributesChangedOnly(array $attributes): self { $this->dontLogIfAttributesChangedOnly = $attributes; return $this; } /** * Don't store empty logs. Storing empty logs can happen when you only * want to log a certain attribute but only another changes. */ public function dontSubmitEmptyLogs(): self { $this->submitEmptyLogs = false; return $this; } /** * Allow storing empty logs. Storing empty logs can happen when you only * want to log a certain attribute but only another changes. */ public function submitEmptyLogs(): self { $this->submitEmptyLogs = true; return $this; } /** * Customize log name. */ public function useLogName(?string $logName): self { $this->logName = $logName; return $this; } /** * Customize log description using callback. */ public function setDescriptionForEvent(Closure $callback): self { $this->descriptionForEvent = $callback; return $this; } /** * Exclude these attributes from being casted. */ public function useAttributeRawValues(array $attributes): self { $this->attributeRawValues = $attributes; return $this; } }
php
<?php use Spatie\Activitylog\ActivityLogger; use Spatie\Activitylog\PendingActivityLog; if (! function_exists('activity')) { function activity(?string $logName = null): ActivityLogger { /** @var PendingActivityLog $log */ $log = app(PendingActivityLog::class); if ($logName) { $log->useLog($logName); } return $log->logger(); } }
php
<?php namespace Spatie\Activitylog; use Illuminate\Support\Traits\ForwardsCalls; /** * @mixin \Spatie\Activitylog\ActivityLogger */ class PendingActivityLog { use ForwardsCalls; protected ActivityLogger $logger; public function __construct(ActivityLogger $logger, ActivityLogStatus $status) { $this->logger = $logger ->setLogStatus($status) ->useLog(config('activitylog.default_log_name')); } public function logger(): ActivityLogger { return $this->logger; } public function __call(string $method, array $parameters): mixed { return $this->forwardCallTo($this->logger, $method, $parameters); } }
php
<?php namespace Spatie\Activitylog; use Illuminate\Contracts\Config\Repository; class ActivityLogStatus { protected $enabled = true; public function __construct(Repository $config) { $this->enabled = $config['activitylog.enabled']; } public function enable(): bool { return $this->enabled = true; } public function disable(): bool { return $this->enabled = false; } public function disabled(): bool { return $this->enabled === false; } }
php
<?php namespace Spatie\Activitylog; use Carbon\Carbon; use Illuminate\Console\Command; use Illuminate\Console\ConfirmableTrait; use Illuminate\Database\Eloquent\Builder; class CleanActivitylogCommand extends Command { use ConfirmableTrait; protected $signature = 'activitylog:clean {log? : (optional) The log name that will be cleaned.} {--days= : (optional) Records older than this number of days will be cleaned.} {--force : (optional) Force the operation to run when in production.}'; protected $description = 'Clean up old records from the activity log.'; public function handle() { if (! $this->confirmToProceed()) { return 1; } $this->comment('Cleaning activity log...'); $log = $this->argument('log'); $maxAgeInDays = $this->option('days') ?? config('activitylog.delete_records_older_than_days'); $cutOffDate = Carbon::now()->subDays($maxAgeInDays)->format('Y-m-d H:i:s'); $activity = ActivitylogServiceProvider::getActivityModelInstance(); $amountDeleted = $activity::query() ->where('created_at', '<', $cutOffDate) ->when($log !== null, function (Builder $query) use ($log) { $query->inLog($log); }) ->delete(); $this->info("Deleted {$amountDeleted} record(s) from the activity log."); $this->comment('All done!'); } }
php
<?php namespace Spatie\Activitylog; use Closure; use DateTimeInterface; use Illuminate\Contracts\Config\Repository; use Illuminate\Database\Eloquent\Model; use Illuminate\Support\Carbon; use Illuminate\Support\Str; use Illuminate\Support\Traits\Conditionable; use Illuminate\Support\Traits\Macroable; use Spatie\Activitylog\Contracts\Activity as ActivityContract; class ActivityLogger { use Conditionable; use Macroable; protected ?string $defaultLogName = null; protected CauserResolver $causerResolver; protected ActivityLogStatus $logStatus; protected ?ActivityContract $activity = null; protected LogBatch $batch; public function __construct(Repository $config, ActivityLogStatus $logStatus, LogBatch $batch, CauserResolver $causerResolver) { $this->causerResolver = $causerResolver; $this->batch = $batch; $this->defaultLogName = $config['activitylog']['default_log_name']; $this->logStatus = $logStatus; } public function setLogStatus(ActivityLogStatus $logStatus): static { $this->logStatus = $logStatus; return $this; } public function performedOn(Model $model): static { $this->getActivity()->subject()->associate($model); return $this; } public function on(Model $model): static { return $this->performedOn($model); } public function causedBy(Model | int | string | null $modelOrId): static { if ($modelOrId === null) { return $this; } $model = $this->causerResolver->resolve($modelOrId); $this->getActivity()->causer()->associate($model); return $this; } public function by(Model | int | string | null $modelOrId): static { return $this->causedBy($modelOrId); } public function causedByAnonymous(): static { $this->activity->causer_id = null; $this->activity->causer_type = null; return $this; } public function byAnonymous(): static { return $this->causedByAnonymous(); } public function event(string $event): static { return $this->setEvent($event); } public function setEvent(string $event): static { $this->activity->event = $event; return $this; } public function withProperties(mixed $properties): static { $this->getActivity()->properties = collect($properties); return $this; } public function withProperty(string $key, mixed $value): static { $this->getActivity()->properties = $this->getActivity()->properties->put($key, $value); return $this; } public function createdAt(DateTimeInterface $dateTime): static { $this->getActivity()->created_at = Carbon::instance($dateTime); return $this; } public function useLog(?string $logName): static { $this->getActivity()->log_name = $logName; return $this; } public function inLog(?string $logName): static { return $this->useLog($logName); } public function tap(callable $callback, ?string $eventName = null): static { call_user_func($callback, $this->getActivity(), $eventName); return $this; } public function enableLogging(): static { $this->logStatus->enable(); return $this; } public function disableLogging(): static { $this->logStatus->disable(); return $this; } public function log(string $description): ?ActivityContract { if ($this->logStatus->disabled()) { return null; } $activity = $this->activity; $activity->description = $this->replacePlaceholders( $activity->description ?? $description, $activity ); if (isset($activity->subject) && method_exists($activity->subject, 'tapActivity')) { $this->tap([$activity->subject, 'tapActivity'], $activity->event ?? ''); } $activity->save(); $this->activity = null; return $activity; } public function withoutLogs(Closure $callback): mixed { if ($this->logStatus->disabled()) { return $callback(); } $this->logStatus->disable(); try { return $callback(); } finally { $this->logStatus->enable(); } } protected function replacePlaceholders(string $description, ActivityContract $activity): string { return preg_replace_callback('/:[a-z0-9._-]+(?<![.])/i', function ($match) use ($activity) { $match = $match[0]; $attribute = Str::before(Str::after($match, ':'), '.'); if (! in_array($attribute, ['subject', 'causer', 'properties'])) { return $match; } $propertyName = substr($match, strpos($match, '.') + 1); $attributeValue = $activity->$attribute; if (is_null($attributeValue)) { return $match; } return data_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->causerResolver->resolve()); $this->activity->batch_uuid = $this->batch->getUuid(); } return $this->activity; } }
php
<?php namespace Spatie\Activitylog\Traits; use Illuminate\Database\Eloquent\Relations\MorphMany; use Spatie\Activitylog\ActivitylogServiceProvider; use Spatie\Activitylog\Models\Activity; trait CausesActivity { /** @return MorphMany<Activity, $this> */ public function actions(): MorphMany { return $this->morphMany( ActivitylogServiceProvider::determineActivityModel(), 'causer' ); } }
php
<?php namespace Spatie\Activitylog\Traits; use Carbon\CarbonInterval; use DateInterval; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\MorphMany; use Illuminate\Database\Eloquent\SoftDeletes; use Illuminate\Pipeline\Pipeline; use Illuminate\Support\Arr; use Illuminate\Support\Collection; use Illuminate\Support\Str; use Spatie\Activitylog\ActivityLogger; use Spatie\Activitylog\ActivitylogServiceProvider; use Spatie\Activitylog\ActivityLogStatus; use Spatie\Activitylog\Contracts\LoggablePipe; use Spatie\Activitylog\EventLogBag; use Spatie\Activitylog\LogOptions; trait LogsActivity { public static array $changesPipes = []; protected array $oldAttributes = []; protected ?LogOptions $activitylogOptions; public bool $enableLoggingModelsEvents = true; abstract public function getActivitylogOptions(): LogOptions; protected static function bootLogsActivity(): void { // Hook into eloquent events that only specified in $eventToBeRecorded array, // checking for "updated" event hook explicitly to temporary hold original // attributes on the model as we'll need them later to compare against. static::eventsToBeRecorded()->each(function ($eventName) { if ($eventName === 'updated') { static::updating(function (Model $model) { $oldValues = (new static())->setRawAttributes($model->getRawOriginal()); $model->oldAttributes = static::logChanges($oldValues); }); } static::$eventName(function (Model $model) use ($eventName) { $model->activitylogOptions = $model->getActivitylogOptions(); if (! $model->shouldLogEvent($eventName)) { return; } $changes = $model->attributeValuesToBeLogged($eventName); $description = $model->getDescriptionForEvent($eventName); $logName = $model->getLogNameToUse(); // Submitting empty description will cause place holder replacer to fail. if ($description == '') { return; } if ($model->isLogEmpty($changes) && ! $model->activitylogOptions->submitEmptyLogs) { return; } // User can define a custom pipelines to mutate, add or remove from changes // each pipe receives the event carrier bag with changes and the model in // question every pipe should manipulate new and old attributes. $event = app(Pipeline::class) ->send(new EventLogBag($eventName, $model, $changes, $model->activitylogOptions)) ->through(static::$changesPipes) ->thenReturn(); // Actual logging $logger = app(ActivityLogger::class) ->useLog($logName) ->event($eventName) ->performedOn($model) ->withProperties($event->changes); if (method_exists($model, 'tapActivity')) { $logger->tap([$model, 'tapActivity'], $eventName); } $logger->log($description); // Reset log options so the model can be serialized. $model->activitylogOptions = null; }); }); } public static function addLogChange(LoggablePipe $pipe): void { static::$changesPipes[] = $pipe; } public function isLogEmpty(array $changes): bool { return empty($changes['attributes'] ?? []) && empty($changes['old'] ?? []); } public function disableLogging(): self { $this->enableLoggingModelsEvents = false; return $this; } public function enableLogging(): self { $this->enableLoggingModelsEvents = true; return $this; } public function activities(): MorphMany { return $this->morphMany(ActivitylogServiceProvider::determineActivityModel(), 'subject'); } public function getDescriptionForEvent(string $eventName): string { if (! empty($this->activitylogOptions->descriptionForEvent)) { return ($this->activitylogOptions->descriptionForEvent)($eventName); } return $eventName; } public function getLogNameToUse(): ?string { if (! empty($this->activitylogOptions->logName)) { return $this->activitylogOptions->logName; } return config('activitylog.default_log_name'); } /** * Get the event names that should be recorded. **/ protected static function eventsToBeRecorded(): Collection { if (isset(static::$recordEvents)) { return collect(static::$recordEvents); } $events = collect([ 'created', 'updated', 'deleted', ]); if (collect(class_uses_recursive(static::class))->contains(SoftDeletes::class)) { $events->push('restored'); } return $events; } protected function shouldLogEvent(string $eventName): bool { $logStatus = app(ActivityLogStatus::class); if (! $this->enableLoggingModelsEvents || $logStatus->disabled()) { return false; } if (! in_array($eventName, ['created', 'updated'])) { return true; } // Do not log update event if the model is restoring if ($this->isRestoring()) { return false; } // Do not log update event if only ignored attributes are changed. return (bool) count(Arr::except($this->getDirty(), $this->activitylogOptions->dontLogIfAttributesChangedOnly)); } /** * Determines if the model is restoring. **/ protected function isRestoring(): bool { $deletedAtColumn = method_exists($this, 'getDeletedAtColumn') ? $this->getDeletedAtColumn() : 'deleted_at'; return $this->isDirty($deletedAtColumn) && count($this->getDirty()) === 1; } /** * Determines what attributes needs to be logged based on the configuration. **/ public function attributesToBeLogged(): array { $this->activitylogOptions = $this->getActivitylogOptions(); $attributes = []; // Check if fillable attributes will be logged then merge it to the local attributes array. if ($this->activitylogOptions->logFillable) { $attributes = array_merge($attributes, $this->getFillable()); } // Determine if unguarded attributes will be logged. if ($this->shouldLogUnguarded()) { // Get only attribute names, not intrested in the values here then guarded // attributes. get only keys than not present in guarded array, because // we are logging the unguarded attributes and we cant have both! $attributes = array_merge($attributes, array_diff(array_keys($this->getAttributes()), $this->getGuarded())); } if (! empty($this->activitylogOptions->logAttributes)) { // Filter * from the logAttributes because will deal with it separately $attributes = array_merge($attributes, array_diff($this->activitylogOptions->logAttributes, ['*'])); // If there's * get all attributes then merge it, dont respect $guarded or $fillable. if (in_array('*', $this->activitylogOptions->logAttributes)) { $attributes = array_merge($attributes, array_keys($this->getAttributes())); } } if ($this->activitylogOptions->logExceptAttributes) { // Filter out the attributes defined in ignoredAttributes out of the local array $attributes = array_diff($attributes, $this->activitylogOptions->logExceptAttributes); } return $attributes; } public function shouldLogUnguarded(): bool { if (! $this->activitylogOptions->logUnguarded) { return false; } // This case means all of the attributes are guarded // so we'll not have any unguarded anyway. if (in_array('*', $this->getGuarded())) { return false; } return true; } /** * Determines values that will be logged based on the difference. **/ public function attributeValuesToBeLogged(string $processingEvent): array { // no loggable attributes, no values to be logged! if (! count($this->attributesToBeLogged())) { return []; } $properties['attributes'] = static::logChanges( // if the current event is retrieved, get the model itself // else get the fresh default properties from database // as wouldn't be part of the saved model instance. $processingEvent == 'retrieved' ? $this : ( $this->exists ? $this->fresh() ?? $this : $this ) ); if (static::eventsToBeRecorded()->contains('updated') && $processingEvent == 'updated') { // Fill the attributes with null values. $nullProperties = array_fill_keys(array_keys($properties['attributes']), null); // Populate the old key with keys from database and from old attributes. $properties['old'] = array_merge($nullProperties, $this->oldAttributes); // Fail safe. $this->oldAttributes = []; } if ($this->activitylogOptions->logOnlyDirty && isset($properties['old'])) { // Get difference between the old and new attributes. $properties['attributes'] = array_udiff_assoc( $properties['attributes'], $properties['old'], function ($new, $old) { // Strict check for php's weird behaviors if ($old === null || $new === null) { return $new === $old ? 0 : 1; } // Handles Date interval comparisons since php cannot use spaceship // Operator to compare them and will throw ErrorException. if ($old instanceof DateInterval) { return CarbonInterval::make($old)->equalTo($new) ? 0 : 1; } elseif ($new instanceof DateInterval) { return CarbonInterval::make($new)->equalTo($old) ? 0 : 1; } return $new <=> $old; } ); $properties['old'] = collect($properties['old']) ->only(array_keys($properties['attributes'])) ->all(); } if (static::eventsToBeRecorded()->contains('deleted') && $processingEvent == 'deleted') { $properties['old'] = $properties['attributes']; unset($properties['attributes']); } return $properties; } public static function logChanges(Model $model): array { $changes = []; $attributes = $model->attributesToBeLogged(); foreach ($attributes as $attribute) { if (Str::contains($attribute, '.')) { $changes += self::getRelatedModelAttributeValue($model, $attribute); continue; } if (Str::contains($attribute, '->')) { Arr::set( $changes, str_replace('->', '.', $attribute), static::getModelAttributeJsonValue($model, $attribute) ); continue; } $changes[$attribute] = in_array($attribute, $model->activitylogOptions->attributeRawValues) ? $model->getAttributeFromArray($attribute) : $model->getAttribute($attribute); if (is_null($changes[$attribute])) { continue; } if ($model->isDateAttribute($attribute)) { $changes[$attribute] = $model->serializeDate( $model->asDateTime($changes[$attribute]) ); } if ($model->hasCast($attribute)) { $cast = $model->getCasts()[$attribute]; if ($model->isEnumCastable($attribute)) { try { $changes[$attribute] = $model->getStorableEnumValue($changes[$attribute]); } catch (\ArgumentCountError $e) { // In Laravel 11, this method has an extra argument // https://github.com/laravel/framework/pull/47465 $changes[$attribute] = $model->getStorableEnumValue($cast, $changes[$attribute]); } } if ($model->isCustomDateTimeCast($cast) || $model->isImmutableCustomDateTimeCast($cast)) { $changes[$attribute] = $model->asDateTime($changes[$attribute])->format(explode(':', $cast, 2)[1]); } } } return $changes; } protected static function getRelatedModelAttributeValue(Model $model, string $attribute): array { $relatedModelNames = explode('.', $attribute); $relatedAttribute = array_pop($relatedModelNames); $attributeName = []; $relatedModel = $model; do { $attributeName[] = $relatedModelName = static::getRelatedModelRelationName($relatedModel, array_shift($relatedModelNames)); $relatedModel = $relatedModel->$relatedModelName ?? $relatedModel->$relatedModelName(); } while (! empty($relatedModelNames)); $attributeName[] = $relatedAttribute; return [implode('.', $attributeName) => $relatedModel->$relatedAttribute ?? null]; } protected static function getRelatedModelRelationName(Model $model, string $relation): string { return Arr::first([ $relation, Str::snake($relation), Str::camel($relation), ], function (string $method) use ($model): bool { return method_exists($model, $method); }, $relation); } protected static function getModelAttributeJsonValue(Model $model, string $attribute): mixed { $path = explode('->', $attribute); $modelAttribute = array_shift($path); $modelAttribute = collect($model->getAttribute($modelAttribute)); return data_get($modelAttribute, implode('.', $path)); } }
php
<?php namespace Spatie\Activitylog\Facades; use Illuminate\Support\Facades\Facade; use Spatie\Activitylog\PendingActivityLog; /** * @method static \Spatie\Activitylog\ActivityLogger setLogStatus(\Spatie\Activitylog\ActivityLogStatus $logStatus) * @method static \Spatie\Activitylog\ActivityLogger performedOn(\Illuminate\Database\Eloquent\Model $model) * @method static \Spatie\Activitylog\ActivityLogger on(\Illuminate\Database\Eloquent\Model $model) * @method static \Spatie\Activitylog\ActivityLogger causedBy(\Illuminate\Database\Eloquent\Model|string|int|null $modelOrId) * @method static \Spatie\Activitylog\ActivityLogger by(\Illuminate\Database\Eloquent\Model|string|int|null $modelOrId) * @method static \Spatie\Activitylog\ActivityLogger causedByAnonymous() * @method static \Spatie\Activitylog\ActivityLogger byAnonymous() * @method static \Spatie\Activitylog\ActivityLogger event(string $event) * @method static \Spatie\Activitylog\ActivityLogger setEvent(string $event) * @method static \Spatie\Activitylog\ActivityLogger withProperties(mixed $properties) * @method static \Spatie\Activitylog\ActivityLogger withProperty(string $key, mixed $value) * @method static \Spatie\Activitylog\ActivityLogger createdAt(\DateTimeInterface $dateTime) * @method static \Spatie\Activitylog\ActivityLogger useLog(string|null $logName) * @method static \Spatie\Activitylog\ActivityLogger inLog(string|null $logName) * @method static \Spatie\Activitylog\ActivityLogger tap(callable $callback, string|null $eventName = null) * @method static \Spatie\Activitylog\ActivityLogger enableLogging() * @method static \Spatie\Activitylog\ActivityLogger disableLogging() * @method static \Spatie\Activitylog\Contracts\Activity|null log(string $description) * @method static mixed withoutLogs(\Closure $callback) * @method static \Spatie\Activitylog\ActivityLogger|mixed when(\Closure|mixed|null $value = null, callable|null $callback = null, callable|null $default = null) * @method static \Spatie\Activitylog\ActivityLogger|mixed unless(\Closure|mixed|null $value = null, callable|null $callback = null, callable|null $default = null) * @method static void macro(string $name, object|callable $macro) * @method static void mixin(object $mixin, bool $replace = true) * @method static bool hasMacro(string $name) * @method static void flushMacros() * * @see \Spatie\Activitylog\PendingActivityLog */ class Activity extends Facade { protected static function getFacadeAccessor(): string { return PendingActivityLog::class; } }
php
<?php namespace Spatie\Activitylog\Facades; use Illuminate\Support\Facades\Facade; use Spatie\Activitylog\CauserResolver as ActivitylogCauserResolver; /** * @method static \Illuminate\Database\Eloquent\Model|null resolve(\Illuminate\Database\Eloquent\Model|int|string|null $subject = null) * @method static \Spatie\Activitylog\CauserResolver resolveUsing(\Closure $callback) * @method static \Spatie\Activitylog\CauserResolver setCauser(\Illuminate\Database\Eloquent\Model|null $causer) * * @see \Spatie\Activitylog\CauserResolver */ class CauserResolver extends Facade { protected static function getFacadeAccessor(): string { return ActivitylogCauserResolver::class; } }
php
<?php namespace Spatie\Activitylog\Facades; use Illuminate\Support\Facades\Facade; use Spatie\Activitylog\LogBatch as ActivityLogBatch; /** * @method static string getUuid() * @method static mixed withinBatch(\Closure $callback) * @method static void startBatch() * @method static void setBatch(string $uuid): void * @method static bool isOpen() * @method static void endBatch() * * @see \Spatie\Activitylog\LogBatch */ class LogBatch extends Facade { protected static function getFacadeAccessor(): string { return ActivityLogBatch::class; } }
php
<?php namespace Spatie\Activitylog\Contracts; use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\MorphTo; use Illuminate\Support\Collection; interface Activity { public function subject(): MorphTo; public function causer(): MorphTo; public function getExtraProperty(string $propertyName, mixed $defaultValue): mixed; public function changes(): Collection; public function scopeInLog(Builder $query, ...$logNames): Builder; public function scopeCausedBy(Builder $query, Model $causer): Builder; public function scopeForEvent(Builder $query, string $event): Builder; public function scopeForSubject(Builder $query, Model $subject): Builder; }
php
<?php namespace Spatie\Activitylog\Contracts; use Closure; use Spatie\Activitylog\EventLogBag; interface LoggablePipe { public function handle(EventLogBag $event, Closure $next): EventLogBag; }
php
<?php namespace Spatie\Activitylog\Models; use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\MorphTo; use Illuminate\Support\Arr; use Illuminate\Support\Collection; use Spatie\Activitylog\Contracts\Activity as ActivityContract; /** * Spatie\Activitylog\Models\Activity. * * @property int $id * @property string|null $log_name * @property string $description * @property string|null $subject_type * @property int|null $subject_id * @property string|null $causer_type * @property int|null $causer_id * @property string|null $event * @property string|null $batch_uuid * @property \Illuminate\Support\Collection|null $properties * @property \Carbon\Carbon|null $created_at * @property \Carbon\Carbon|null $updated_at * @property-read \Illuminate\Database\Eloquent\Model|\Eloquent|null $causer * @property-read \Illuminate\Support\Collection $changes * @property-read \Illuminate\Database\Eloquent\Model|\Eloquent|null $subject * * @method static \Illuminate\Database\Eloquent\Builder|\Spatie\Activitylog\Models\Activity causedBy(\Illuminate\Database\Eloquent\Model $causer) * @method static \Illuminate\Database\Eloquent\Builder|\Spatie\Activitylog\Models\Activity forBatch(string $batchUuid) * @method static \Illuminate\Database\Eloquent\Builder|\Spatie\Activitylog\Models\Activity forEvent(string $event) * @method static \Illuminate\Database\Eloquent\Builder|\Spatie\Activitylog\Models\Activity forSubject(\Illuminate\Database\Eloquent\Model $subject) * @method static \Illuminate\Database\Eloquent\Builder|\Spatie\Activitylog\Models\Activity hasBatch() * @method static \Illuminate\Database\Eloquent\Builder|\Spatie\Activitylog\Models\Activity inLog($logNames) * @method static \Illuminate\Database\Eloquent\Builder|\Spatie\Activitylog\Models\Activity newModelQuery() * @method static \Illuminate\Database\Eloquent\Builder|\Spatie\Activitylog\Models\Activity newQuery() * @method static \Illuminate\Database\Eloquent\Builder|\Spatie\Activitylog\Models\Activity query() */ class Activity extends Model implements ActivityContract { public $guarded = []; protected $casts = [ 'properties' => 'collection', ]; public function __construct(array $attributes = []) { if (! isset($this->connection)) { $this->setConnection(config('activitylog.database_connection')); } if (! isset($this->table)) { $this->setTable(config('activitylog.table_name')); } parent::__construct($attributes); } /** * @return MorphTo<Model, $this> */ public function subject(): MorphTo { if (config('activitylog.subject_returns_soft_deleted_models')) { return $this->morphTo()->withTrashed(); } return $this->morphTo(); } /** * @return MorphTo<Model, $this> */ public function causer(): MorphTo { return $this->morphTo(); } public function getExtraProperty(string $propertyName, mixed $defaultValue = null): mixed { return Arr::get($this->properties->toArray(), $propertyName, $defaultValue); } public function changes(): Collection { if (! $this->properties instanceof Collection) { return new Collection(); } return $this->properties->only(['attributes', 'old']); } public function getChangesAttribute(): Collection { return $this->changes(); } public function scopeInLog(Builder $query, ...$logNames): Builder { if (is_array($logNames[0])) { $logNames = $logNames[0]; } return $query->whereIn('log_name', $logNames); } public function scopeCausedBy(Builder $query, Model $causer): Builder { return $query ->where('causer_type', $causer->getMorphClass()) ->where('causer_id', $causer->getKey()); } public function scopeForSubject(Builder $query, Model $subject): Builder { return $query ->where('subject_type', $subject->getMorphClass()) ->where('subject_id', $subject->getKey()); } public function scopeForEvent(Builder $query, string $event): Builder { return $query->where('event', $event); } public function scopeHasBatch(Builder $query): Builder { return $query->whereNotNull('batch_uuid'); } public function scopeForBatch(Builder $query, string $batchUuid): Builder { return $query->where('batch_uuid', $batchUuid); } }
php
<?php namespace Spatie\Activitylog\Exceptions; use Exception; class CouldNotLogActivity extends Exception { public static function couldNotDetermineUser($id): self { return new static("Could not determine a user with identifier `{$id}`."); } }
php
<?php namespace Spatie\Activitylog\Exceptions; use Exception; class CouldNotLogChanges extends Exception { public static function invalidAttribute($attribute): self { return new static("Cannot log attribute `{$attribute}`. Can only log attributes of a model or a directly related model."); } }
php
<?php namespace Spatie\Activitylog\Exceptions; use Exception; use Illuminate\Database\Eloquent\Model; use Spatie\Activitylog\Contracts\Activity; class InvalidConfiguration extends Exception { public static function modelIsNotValid(string $className): self { return new static("The given model class `{$className}` does not implement `".Activity::class.'` or it does not extend `'.Model::class.'`'); } }
php
<?php $uri = urldecode(parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH)); // This file allows us to emulate Apache's "mod_rewrite" functionality from the // built-in PHP web server. This provides a convenient way to test a Lumen // application without having installed a "real" server software here. if ($uri !== '/' && file_exists(__DIR__.'/public'.$uri)) { return false; } require_once __DIR__.'/public/index.php';
php
<?php use Illuminate\Database\Seeder; use Illuminate\Database\Eloquent\Model; class DatabaseSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { Model::unguard(); // $this->call('UserTableSeeder'); Model::reguard(); } }
php
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateClicksTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('clicks', function(Blueprint $table) { $table->engine = 'InnoDB'; $table->increments('id'); $table->string('ip'); $table->string('country')->nullable(); $table->string('referer')->nullable(); $table->string('referer_host')->nullable(); $table->text('user_agent')->nullable(); $table->integer('link_id')->unsigned(); $table->index('ip'); $table->index('referer_host'); $table->index('link_id'); $table->foreign('link_id')->references('id')->on('links')->onDelete('cascade'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('clicks'); } }
php
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateLinkTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('links', function(Blueprint $table) { $table->engine = 'InnoDB'; $table->increments('id'); $table->string('short_url'); $table->longText('long_url'); $table->string('ip'); $table->string('creator'); $table->string('clicks')->default(0); $table->string('secret_key'); $table->boolean('is_disabled')->default(0); $table->boolean('is_custom')->default(0); $table->boolean('is_api')->default(0); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('links'); } }
php
<?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class AddLinkTableIndexes extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::table('links', function (Blueprint $table) { // Add long_url hashes $table->unique('short_url'); $table->string('long_url_hash', 10)->nullable(); $table->index('long_url_hash', 'links_long_url_index'); }); // MySQL only statement // DB::statement("UPDATE links SET long_url_hash = crc32(long_url);"); DB::table('links')->select(['id', 'long_url_hash', 'long_url']) ->chunk(100, function($links) { foreach ($links as $link) { DB::table('links') ->where('id', $link->id) ->update([ 'long_url_hash' => sprintf('%u', crc32($link->long_url)) ]); } }); } public function down() { Schema::table('links', function (Blueprint $table) { $table->dropUnique('links_short_url_unique'); $table->dropIndex('links_long_url_index'); $table->dropColumn('long_url_hash'); }); } }
php
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateUsersTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('users', function(Blueprint $table) { $table->increments('id'); $table->string('username')->unique(); $table->string('password'); $table->string('email'); $table->text('ip'); $table->string('recovery_key'); $table->string('role'); $table->string('active'); $table->string('api_key')->nullable(); $table->boolean('api_active')->default(0); $table->string('api_quota')->default(60); $table->timestamps(); $table->softDeletes(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('users'); } }
php
<?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class AlterLinkClicksToInteger extends Migration { /** * Run the migrations. * Changes the "clicks" field in the link table to * an integer field rather than a string field. * * @return void */ public function up() { Schema::table('links', function (Blueprint $table) { $table->integer('clicks')->change(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('links', function (Blueprint $table) { $table->string('clicks')->change(); }); } }
php
<?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateApiQuotaIndex extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::table('links', function (Blueprint $table) { $table->index( ['created_at', 'creator', 'is_api'], 'api_quota_index' ); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('links', function (Blueprint $table) { $table->dropIndex('api_quota_index'); }); } }
php
<?php /* |-------------------------------------------------------------------------- | Model Factories |-------------------------------------------------------------------------- | | Here you may define all of your model factories. Model factories give | you a convenient way to create models for testing and seeding your | database. Just tell the factory how a default model should look. | */ $factory->define(App\User::class, function ($faker) { return [ 'name' => $faker->name, 'email' => $faker->email, 'password' => str_random(10), 'remember_token' => str_random(10), ]; });
php
<?php require_once __DIR__.'/../vendor/autoload.php'; Dotenv::load(__DIR__.'/../'); /* |-------------------------------------------------------------------------- | Create The Application |-------------------------------------------------------------------------- | | Here we will load the environment and create the application instance | that serves as the central piece of this framework. We'll use this | application as an "IoC" container and router for this framework. | */ $app = new Laravel\Lumen\Application( realpath(__DIR__.'/../') ); $app->withFacades(); $app->withEloquent(); $app->configure('geoip'); /* |-------------------------------------------------------------------------- | Register Container Bindings |-------------------------------------------------------------------------- | | Now we will register a few bindings in the service container. We will | register the exception handler and the console kernel. You may add | your own bindings here if you like or you can make another file. | */ $app->singleton( Illuminate\Contracts\Debug\ExceptionHandler::class, App\Exceptions\Handler::class ); $app->singleton( Illuminate\Contracts\Console\Kernel::class, App\Console\Kernel::class ); /* |-------------------------------------------------------------------------- | Register Middleware |-------------------------------------------------------------------------- | | Next, we will register the middleware with the application. These can | be global middleware that run before and after each request into a | route or middleware that'll be assigned to some specific routes. | */ $app->middleware([ Illuminate\Cookie\Middleware\EncryptCookies::class, // Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class, Illuminate\Session\Middleware\StartSession::class, Illuminate\View\Middleware\ShareErrorsFromSession::class, App\Http\Middleware\VerifyCsrfToken::class, ]); $app->routeMiddleware([ 'api' => App\Http\Middleware\ApiMiddleware::class, ]); /* |-------------------------------------------------------------------------- | Register Service Providers |-------------------------------------------------------------------------- | | Here we will register all of the application's service providers which | are used to bind services into the container. Service providers are | totally optional, so you are not required to uncomment this line. | */ $app->register(App\Providers\AppServiceProvider::class); $app->register(\Yajra\Datatables\DatatablesServiceProvider::class); $app->register(\Torann\GeoIP\GeoIPServiceProvider::class); // $app->register(App\Providers\EventServiceProvider::class); /* |-------------------------------------------------------------------------- | Load The Application Routes |-------------------------------------------------------------------------- | | Next we will include the routes file so that they can all be added to | the application. This will provide all of the URLs the application | can respond to, as well as the controllers that may handle them. | */ $app->group(['namespace' => 'App\Http\Controllers'], function ($app) { require __DIR__.'/../app/Http/routes.php'; }); return $app;
php
<?php use Illuminate\Foundation\Testing\DatabaseMigrations; use Illuminate\Foundation\Testing\DatabaseTransactions; class TestCase extends Laravel\Lumen\Testing\TestCase { /** * Creates the application. * * @return \Laravel\Lumen\Application */ use DatabaseTransactions; public function createApplication() { return require __DIR__.'/../bootstrap/app.php'; } }
php
<?php class LinkControllerTest extends TestCase { /** * Test LinkController * * @return void */ public function testRequestGetNotExistShortUrl() { $response = $this->call('GET', '/notexist'); $this->assertTrue($response->isRedirection()); $this->assertRedirectedTo(env('SETTING_INDEX_REDIRECT')); } }
php
<?php class AuthTest extends TestCase { /** * Test Authentication (sign up and sign in) * * @return void */ public function testLogin() { // $this->visit('/') // ->type('polrci', 'username') // ->type('polrci', 'password ') // ->press('Sign In') // ->dontSee('name="login" value="Sign In" />') // ->see('>Dashboard</a>'); } }
php
<?php use App\Helpers\LinkHelper; use App\Factories\LinkFactory; class LinkHelperTest extends TestCase { /** * Test LinkHelper * * @return void */ public function testLinkHelperAlreadyShortened() { $not_short = [ 'https://google.com', 'https://example.com/google', 'https://cydrobolt.com', 'http://github.com/cydrobolt/polr' ]; $shortened = [ 'https://polr.me/1', 'http://bit.ly/1PUf6Sw', 'http://'.env('APP_ADDRESS').'/1', 'https://goo.gl/2pSp9f' ]; foreach ($not_short as $u) { $this->assertEquals(false, LinkHelper::checkIfAlreadyShortened($u)); } foreach ($shortened as $u) { $this->assertEquals(true, LinkHelper::checkIfAlreadyShortened($u)); } } public function testLinkExists() { $link = LinkFactory::createLink('http://example.com/ci', true, null, '127.0.0.1', false, true); // assert that existent link ending returns true $this->assertNotEquals(LinkHelper::linkExists($link->short_url), false); // assert that nonexistent link ending returns false $this->assertEquals(LinkHelper::linkExists('nonexistent'), false); } }
php
<?php use App\Helpers\BaseHelper; class BaseHelperTest extends TestCase { /** * Test BaseHelper * * @return void */ private static function checkBaseGen($num) { $toBase32 = BaseHelper::toBase($num, 32); $toBase62 = BaseHelper::toBase($num, 62); $fromBase32 = BaseHelper::toBase10($toBase32, 32); $fromBase62 = BaseHelper::toBase10($toBase62, 62); if ($fromBase62 == $num && $fromBase32 == $num) { return true; } return false; } public function testLogin() { $nums = [ 523002, 1204, 23, 0, 1, 45 ]; foreach ($nums as $n) { $this->assertEquals(true, self::checkBaseGen($n)); } } }
php
<?php class IndexTest extends TestCase { /** * Test Index * * @return void */ public function testIndex() { $this->visit('/') ->see('<h1 class=\'title\'>'. env('APP_NAME') .'</h1>') // Ensure page loads correctly ->see('<meta name="csrf-token"') // Ensure CSRF protection is enabled ->see('>Sign In</a>') // Ensure log in buttons are shown when user is logged out ->dontSee('SQLSTATE'); // Ensure database connection is correct } }
php
<?php return [ /* |-------------------------------------------------------------------------- | Validation Language Lines |-------------------------------------------------------------------------- | | The following language lines contain the default error messages used by | the validator class. Some of these rules have multiple versions such | as the size rules. Feel free to tweak each of these messages here. | */ 'accepted' => 'The :attribute must be accepted.', 'active_url' => 'The :attribute is not a valid URL.', 'after' => 'The :attribute must be a date after :date.', 'alpha' => 'The :attribute may only contain letters.', 'alpha_dash' => 'The :attribute may only contain letters, numbers, and dashes.', 'alpha_num' => 'The :attribute may only contain letters and numbers.', 'array' => 'The :attribute must be an array.', 'before' => 'The :attribute must be a date before :date.', 'between' => [ 'numeric' => 'The :attribute must be between :min and :max.', 'file' => 'The :attribute must be between :min and :max kilobytes.', 'string' => 'The :attribute must be between :min and :max characters.', 'array' => 'The :attribute must have between :min and :max items.', ], 'boolean' => 'The :attribute field must be true or false.', 'confirmed' => 'The :attribute confirmation does not match.', 'date' => 'The :attribute is not a valid date.', 'date_format' => 'The :attribute does not match the format :format.', 'different' => 'The :attribute and :other must be different.', 'digits' => 'The :attribute must be :digits digits.', 'digits_between' => 'The :attribute must be between :min and :max digits.', 'email' => 'The :attribute must be a valid email address.', 'filled' => 'The :attribute field is required.', 'exists' => 'The selected :attribute is invalid.', 'image' => 'The :attribute must be an image.', 'in' => 'The selected :attribute is invalid.', 'integer' => 'The :attribute must be an integer.', 'ip' => 'The :attribute must be a valid IP address.', 'max' => [ 'numeric' => 'The :attribute may not be greater than :max.', 'file' => 'The :attribute may not be greater than :max kilobytes.', 'string' => 'The :attribute may not be greater than :max characters.', 'array' => 'The :attribute may not have more than :max items.', ], 'mimes' => 'The :attribute must be a file of type: :values.', 'min' => [ 'numeric' => 'The :attribute must be at least :min.', 'file' => 'The :attribute must be at least :min kilobytes.', 'string' => 'The :attribute must be at least :min characters.', 'array' => 'The :attribute must have at least :min items.', ], 'not_in' => 'The selected :attribute is invalid.', 'numeric' => 'The :attribute must be a number.', 'regex' => 'The :attribute format is invalid.', 'required' => 'The :attribute field is required.', 'required_if' => 'The :attribute field is required when :other is :value.', 'required_with' => 'The :attribute field is required when :values is present.', 'required_with_all' => 'The :attribute field is required when :values is present.', 'required_without' => 'The :attribute field is required when :values is not present.', 'required_without_all' => 'The :attribute field is required when none of :values are present.', 'same' => 'The :attribute and :other must match.', 'size' => [ 'numeric' => 'The :attribute must be :size.', 'file' => 'The :attribute must be :size kilobytes.', 'string' => 'The :attribute must be :size characters.', 'array' => 'The :attribute must contain :size items.', ], 'unique' => 'The :attribute has already been taken.', 'url' => 'The :attribute format is invalid.', 'timezone' => 'The :attribute must be a valid zone.', /* |-------------------------------------------------------------------------- | Custom Validation Language Lines |-------------------------------------------------------------------------- | | Here you may specify custom validation messages for attributes using the | convention "attribute.rule" to name the lines. This makes it quick to | specify a specific custom language line for a given attribute rule. | */ 'custom' => [ 'attribute-name' => [ 'rule-name' => 'custom-message', ], ], /* |-------------------------------------------------------------------------- | Custom Validation Attributes |-------------------------------------------------------------------------- | | The following language lines are used to swap attribute place-holders | with something more reader friendly such as E-Mail Address instead | of "email". This simply helps us make messages a little cleaner. | */ 'attributes' => [ 'link-url' => 'link URL' ], ];
php
<?php namespace App\Events; use Illuminate\Queue\SerializesModels; abstract class Event { use SerializesModels; }
php
<?php namespace App\Providers; use Illuminate\Support\ServiceProvider; class AppServiceProvider extends ServiceProvider { /** * Register any application services. * * @return void */ public function register() { // } }
php
<?php namespace App\Providers; use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider; class EventServiceProvider extends ServiceProvider { /** * The event listener mappings for the application. * * @var array */ protected $listen = [ 'App\Events\SomeEvent' => [ 'App\Listeners\EventListener', ], ]; }
php
<?php /* |-------------------------------------------------------------------------- | Application Routes |-------------------------------------------------------------------------- */ /* Optional endpoints */ if (env('POLR_ALLOW_ACCT_CREATION')) { $app->get('/signup', ['as' => 'signup', 'uses' => 'UserController@displaySignupPage']); $app->post('/signup', ['as' => 'psignup', 'uses' => 'UserController@performSignup']); } /* GET endpoints */ $app->get('/', ['as' => 'index', 'uses' => 'IndexController@showIndexPage']); $app->get('/logout', ['as' => 'logout', 'uses' => 'UserController@performLogoutUser']); $app->get('/login', ['as' => 'login', 'uses' => 'UserController@displayLoginPage']); $app->get('/about-polr', ['as' => 'about', 'uses' => 'StaticPageController@displayAbout']); $app->get('/lost_password', ['as' => 'lost_password', 'uses' => 'UserController@displayLostPasswordPage']); $app->get('/activate/{username}/{recovery_key}', ['as' => 'activate', 'uses' => 'UserController@performActivation']); $app->get('/reset_password/{username}/{recovery_key}', ['as' => 'reset_password', 'uses' => 'UserController@performPasswordReset']); $app->get('/admin', ['as' => 'admin', 'uses' => 'AdminController@displayAdminPage']); $app->get('/setup', ['as' => 'setup', 'uses' => 'SetupController@displaySetupPage']); $app->post('/setup', ['as' => 'psetup', 'uses' => 'SetupController@performSetup']); $app->get('/setup/finish', ['as' => 'setup_finish', 'uses' => 'SetupController@finishSetup']); $app->get('/{short_url}', ['uses' => 'LinkController@performRedirect']); $app->get('/{short_url}/{secret_key}', ['uses' => 'LinkController@performRedirect']); $app->get('/admin/stats/{short_url}', ['uses' => 'StatsController@displayStats']); /* POST endpoints */ $app->post('/login', ['as' => 'plogin', 'uses' => 'UserController@performLogin']); $app->post('/shorten', ['as' => 'pshorten', 'uses' => 'LinkController@performShorten']); $app->post('/lost_password', ['as' => 'plost_password', 'uses' => 'UserController@performSendPasswordResetCode']); $app->post('/reset_password/{username}/{recovery_key}', ['as' => 'preset_password', 'uses' => 'UserController@performPasswordReset']); $app->post('/admin/action/change_password', ['as' => 'change_password', 'uses' => 'AdminController@changePassword']); $app->group(['prefix' => '/api/v2', 'namespace' => 'App\Http\Controllers'], function ($app) { /* API internal endpoints */ $app->post('link_avail_check', ['as' => 'api_link_check', 'uses' => 'AjaxController@checkLinkAvailability']); $app->post('admin/toggle_api_active', ['as' => 'api_toggle_api_active', 'uses' => 'AjaxController@toggleAPIActive']); $app->post('admin/generate_new_api_key', ['as' => 'api_generate_new_api_key', 'uses' => 'AjaxController@generateNewAPIKey']); $app->post('admin/edit_api_quota', ['as' => 'api_edit_quota', 'uses' => 'AjaxController@editAPIQuota']); $app->post('admin/toggle_user_active', ['as' => 'api_toggle_user_active', 'uses' => 'AjaxController@toggleUserActive']); $app->post('admin/change_user_role', ['as' => 'api_change_user_role', 'uses' => 'AjaxController@changeUserRole']); $app->post('admin/add_new_user', ['as' => 'api_add_new_user', 'uses' => 'AjaxController@addNewUser']); $app->post('admin/delete_user', ['as' => 'api_delete_user', 'uses' => 'AjaxController@deleteUser']); $app->post('admin/toggle_link', ['as' => 'api_toggle_link', 'uses' => 'AjaxController@toggleLink']); $app->post('admin/delete_link', ['as' => 'api_delete_link', 'uses' => 'AjaxController@deleteLink']); $app->post('admin/edit_link_long_url', ['as' => 'api_edit_link_long_url', 'uses' => 'AjaxController@editLinkLongUrl']); $app->get('admin/get_admin_users', ['as' => 'api_get_admin_users', 'uses' => 'AdminPaginationController@paginateAdminUsers']); $app->get('admin/get_admin_links', ['as' => 'api_get_admin_links', 'uses' => 'AdminPaginationController@paginateAdminLinks']); $app->get('admin/get_user_links', ['as' => 'api_get_user_links', 'uses' => 'AdminPaginationController@paginateUserLinks']); }); $app->group(['prefix' => '/api/v2', 'namespace' => 'App\Http\Controllers\Api', 'middleware' => 'api'], function ($app) { /* API shorten endpoints */ $app->post('action/shorten', ['as' => 'api_shorten_url', 'uses' => 'ApiLinkController@shortenLink']); $app->get('action/shorten', ['as' => 'api_shorten_url', 'uses' => 'ApiLinkController@shortenLink']); $app->post('action/shorten_bulk', ['as' => 'api_shorten_url_bulk', 'uses' => 'ApiLinkController@shortenLinksBulk']); /* API lookup endpoints */ $app->post('action/lookup', ['as' => 'api_lookup_url', 'uses' => 'ApiLinkController@lookupLink']); $app->get('action/lookup', ['as' => 'api_lookup_url', 'uses' => 'ApiLinkController@lookupLink']); /* API data endpoints */ $app->get('data/link', ['as' => 'api_link_analytics', 'uses' => 'ApiAnalyticsController@lookupLinkStats']); $app->post('data/link', ['as' => 'api_link_analytics', 'uses' => 'ApiAnalyticsController@lookupLinkStats']); });
php
<?php namespace App\Http\Controllers; use Laravel\Lumen\Routing\Controller as BaseController; use Illuminate\Http\Request; use App\Http\Controllers\Controller; class Controller extends BaseController { protected static function currIsAdmin() { $role = session('role'); if ($role == 'admin') { return true; } else { return false; } } protected static function isLoggedIn() { $username = session('username'); if (!isset($username)) { return false; } else { return true; } } protected static function checkRequiredArgs($required_args=[]) { foreach($required_args as $arg) { if ($arg == NULL) { return false; } } return true; } protected static function ensureAdmin() { if (!self::currIsAdmin()) { abort(401, 'User not admin.'); } return true; } protected static function ensureLoggedIn() { if (!self::isLoggedIn()) { abort (401, 'User must be authenticated.'); } return true; } }
End of preview. Expand in Data Studio
YAML Metadata Warning: empty or missing yaml metadata in repo card (https://huggingface.co/docs/hub/datasets-cards)

Web Beast Dataset

The Web Beast Dataset is a large-scale, curated code dataset focused on modern backend and fullstack development. It includes high-quality source code files from open-source repositories, targeting:

  • PHP (Laravel)
  • Node.js (Express, TypeScript)
  • JavaScript (Frontend and Backend)
  • HTML & Tailwind CSS

πŸ’‘ Purpose

Designed for:

  • Training code generation & completion models
  • Building smart developer tools
  • Fine-tuning LLMs (e.g. DeepSeek, StarCoder, Codellama)

🌐 Website

Visit: web-beast.com

πŸ“ Dataset Structure

Each .jsonl file includes:

{
  "repo": "github.com/owner/repo",
  "path": "src/Controllers/AuthController.php",
  "language": "php",
  "framework": "laravel",
  "content": "class AuthController { ... }"
}
Downloads last month
19