Skip to content

Commit

Permalink
Merge pull request #3 from ensi-platform/dev-1
Browse files Browse the repository at this point in the history
Audit extra.
  • Loading branch information
zix2 authored Dec 6, 2021
2 parents 1cd5aa0 + 99d96e4 commit 4e7a6d5
Show file tree
Hide file tree
Showing 9 changed files with 122 additions and 10 deletions.
1 change: 1 addition & 0 deletions database/migrations/audits.stub
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ class CreateAuditsTable extends Migration
$table->uuid('transaction_uid')->nullable();
$table->timestamp('transaction_time', 6)->nullable();
$table->string('user_id')->nullable();
$table->jsonb('extra')->nullable();

$table->index(['subject_id', 'subject_type']);
$table->index(['transaction_uid', 'created_at']);
Expand Down
7 changes: 6 additions & 1 deletion src/Audit.php
Original file line number Diff line number Diff line change
Expand Up @@ -85,11 +85,16 @@ public function resolveData(): array
'subject_type' => $this->getAttribute('subject_type'),
'transaction_uid' => $this->getAttribute('transaction_uid'),
'transaction_time' => $this->serializeDate($this->transaction_time ?? now()),
'user_id' => $this->user_id,
'extra' => $this->extra,
];

if ($this->subject && ($this->subject instanceof Principal)) {
$this->data['subject_name'] = $this->subject->getName();
$this->data['user_id'] = $this->subject->getUserIdentifier();

if (!isset($this->data['user_id'])) {
$this->data['user_id'] = $this->subject->getUserIdentifier();
}
}

$this->metadata = array_keys($this->data);
Expand Down
7 changes: 7 additions & 0 deletions src/Contracts/Auditable.php
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,13 @@ public function transformAudit(array $data): array;
*/
public function generateTags(): array;

/**
* Return extra information.
*
* @return array|null
*/
public function getAuditExtra(): ?array;

/**
* Transition to another model state from an Audit.
*
Expand Down
2 changes: 2 additions & 0 deletions src/Models/Audit.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
* @property string $subject_type
* @property int $subject_id Субъект доступа
* @property string|null $user_id Идентификатор пользователя
* @property array|null $extra Дополнительная информация
*
* @property \Carbon\CarbonInterface $created_at
* @property \Carbon\CarbonInterface $updated_at
Expand Down Expand Up @@ -53,6 +54,7 @@ class Audit extends Model implements \Ensi\LaravelAuditing\Contracts\Audit
'new_values' => 'json',
// Note: Please do not add 'auditable_id' in here, as it will break non-integer PK models
'state' => 'json',
'extra' => 'json',
];

protected $dates = ['transaction_time'];
Expand Down
6 changes: 6 additions & 0 deletions src/SupportsAudit.php
Original file line number Diff line number Diff line change
Expand Up @@ -308,6 +308,7 @@ public function toAudit(): array
'user_agent' => $this->resolveUserAgent(),
'user_id' => $this->resolveUser(),
'tags' => empty($tags) ? null : $tags,
'extra' => $this->getAuditExtra(),
]);
}

Expand All @@ -328,6 +329,11 @@ public function transformAudit(array $data): array
return $data;
}

public function getAuditExtra(): ?array
{
return null;
}

/**
* Resolve the Subject.
*
Expand Down
11 changes: 11 additions & 0 deletions tests/Models/Article.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,16 @@

namespace Ensi\LaravelAuditing\Tests\Models;

use Carbon\CarbonInterface;
use Ensi\LaravelAuditing\Database\Factories\ArticleFactory;
use Ensi\LaravelAuditing\SupportsAudit;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Ensi\LaravelAuditing\Contracts\Auditable;

/**
* @property CarbonInterface|null $published_at
*/
class Article extends Model implements Auditable
{
use SupportsAudit;
Expand Down Expand Up @@ -49,6 +53,13 @@ public function getTitleAttribute(string $value): string
return strtoupper($value);
}

public function getAuditExtra(): ?array
{
return $this->published_at
? ['year' => $this->published_at->year]
: null;
}

public static function factory(): ArticleFactory
{
return ArticleFactory::new();
Expand Down
54 changes: 46 additions & 8 deletions tests/Unit/AuditTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
use Ensi\LaravelAuditing\Tests\AuditingTestCase;
use Ensi\LaravelAuditing\Tests\Models\Article;
use Ensi\LaravelAuditing\Tests\Models\User;
use Ensi\LaravelAuditing\Tests\Models\VirtualUser;
use Illuminate\Foundation\Testing\Concerns\InteractsWithTime;
use Illuminate\Support\Facades\DB;
use Illuminate\Testing\Assert;
Expand All @@ -19,6 +20,9 @@ class AuditTest extends AuditingTestCase
{
use InteractsWithTime;

private const AUDIT_FIELDS_COUNT = 20;
private const AUDIT_META_FIELDS_COUNT = 16;

/**
* @group Audit::resolveData
* @test
Expand All @@ -37,7 +41,7 @@ public function itResolvesAuditData()

$audit = $article->audits()->first();

$this->assertCount(18, $resolvedData = $audit->resolveData());
$this->assertCount(self::AUDIT_FIELDS_COUNT, $resolvedData = $audit->resolveData());

Assert::assertArraySubset([
'audit_id' => 1,
Expand All @@ -52,6 +56,7 @@ public function itResolvesAuditData()
'new_content' => 'First step: install the laravel-auditing package.',
'new_published_at' => $now->toDateTimeString(),
'new_reviewed' => 1,
'extra' => ['year' => $now->year],
], $resolvedData, true);
}

Expand Down Expand Up @@ -81,7 +86,7 @@ public function itResolvesAuditDataIncludingSubjectAttributes()

$audit = $article->audits()->first();

$this->assertCount(20, $resolvedData = $audit->resolveData());
$this->assertCount(self::AUDIT_FIELDS_COUNT + 1, $resolvedData = $audit->resolveData());

Assert::assertArraySubset([
'audit_id' => 2,
Expand All @@ -100,6 +105,36 @@ public function itResolvesAuditDataIncludingSubjectAttributes()
], $resolvedData, true);
}

/**
* @test
*/
public function itResolvesAuditDataIncludingUserId()
{
$this->actingAs(new VirtualUser(), 'api');

$article = Article::factory()->create();

$audit = $article->audits()->first();

Assert::assertArraySubset([
'user_id' => VirtualUser::ID,
], $audit->resolveData(), true);
}

/**
* @test
*/
public function itResolvesAuditDataIncludingDefaultExtra()
{
$article = Article::factory()->create();

$audit = $article->audits()->first();

Assert::assertArraySubset([
'extra' => null,
], $audit->resolveData(), true);
}

/**
* @group Audit::resolveData
* @group Audit::getDataValue
Expand All @@ -122,7 +157,7 @@ public function itReturnsTheAppropriateAuditableDataValues()
])->audits()->first();

// Resolve data, making it available to the getDataValue() method
$this->assertCount(18, $audit->resolveData());
$this->assertCount(self::AUDIT_FIELDS_COUNT, $audit->resolveData());

// Mutate value
$this->assertSame('HOW TO AUDIT ELOQUENT MODELS', $audit->getDataValue('new_title'));
Expand All @@ -148,7 +183,7 @@ public function itReturnsAuditMetadataAsArray()
{
$audit = Article::factory()->create()->audits()->first();

$this->assertCount(14, $metadata = $audit->getMetadata());
$this->assertCount(self::AUDIT_META_FIELDS_COUNT, $metadata = $audit->getMetadata());

Assert::assertArraySubset([
'audit_id' => 1,
Expand Down Expand Up @@ -179,7 +214,7 @@ public function itReturnsAuditMetadataIncludingSubjectAttributesAsArray()

$audit = Article::factory()->create()->audits()->first();

$this->assertCount(16, $metadata = $audit->getMetadata());
$this->assertCount(self::AUDIT_META_FIELDS_COUNT + 1, $metadata = $audit->getMetadata());

Assert::assertArraySubset([
'audit_id' => 2,
Expand Down Expand Up @@ -222,7 +257,9 @@ public function itReturnsAuditMetadataAsJsonString()
"subject_id": null,
"subject_type": null,
"transaction_uid": null,
"transaction_time": "$now"
"transaction_time": "$now",
"user_id": null,
"extra": null
}
EOF;

Expand Down Expand Up @@ -268,8 +305,9 @@ public function itReturnsAuditMetadataIncludingSubjectAttributesAsJsonString()
"subject_type": "Ensi\\\\LaravelAuditing\\\\Tests\\\\Models\\\\User",
"transaction_uid": null,
"transaction_time": "$now",
"subject_name": "Rick",
"user_id": $userId
"user_id": $userId,
"extra": null,
"subject_name": "Rick"
}
EOF;

Expand Down
43 changes: 42 additions & 1 deletion tests/Unit/AuditableTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@

class AuditableTest extends AuditingTestCase
{
private const AUDIT_FIELDS_COUNT = 13;
private const AUDIT_FIELDS_COUNT = 14;

/**
* {@inheritdoc}
Expand Down Expand Up @@ -566,6 +566,47 @@ public function itReturnsTheAuditDataIncludingVirtualUserId()
], $auditData, true);
}

/**
* @test
*/
public function itReturnsTheAuditDataIncludingExtra()
{
$now = Carbon::now();

$model = Article::factory()->make([
'title' => 'How To Audit Eloquent Models',
'content' => 'First step: install the laravel-auditing package.',
'reviewed' => 1,
'published_at' => $now,
]);

$model->setAuditEvent('created');

$this->assertCount(self::AUDIT_FIELDS_COUNT, $auditData = $model->toAudit());

Assert::assertArraySubset([
'extra' => [
'year' => $now->year,
],
'event' => 'created',
'auditable_id' => null,
'auditable_type' => Article::class,
], $auditData, true);
}

/**
* @test
*/
public function itReturnsTheDefaultExtra()
{
$model = Article::factory()->make();
$model->setAuditEvent('created');

Assert::assertArraySubset([
'extra' => null,
], $model->toAudit(), true);
}

/**
* @group Auditable::setAuditEvent
* @group Auditable::toAudit
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ public function up()
$table->uuid('transaction_uid')->nullable();
$table->timestamp('transaction_time', 6)->nullable();
$table->string('user_id')->nullable();
$table->jsonb('extra')->nullable();

$table->index(['subject_id', 'subject_type']);
$table->index(['transaction_uid', 'created_at']);
Expand Down

0 comments on commit 4e7a6d5

Please sign in to comment.