Skip to content

Commit

Permalink
增加 disableVersioning/enableVersioning
Browse files Browse the repository at this point in the history
  • Loading branch information
overtrue committed Jan 22, 2021
1 parent a457c61 commit 6663022
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 5 deletions.
27 changes: 22 additions & 5 deletions src/Versionable.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,21 +26,21 @@ trait Versionable
public static function bootVersionable()
{
static::saved(function (Model $model) {
self::createVersionForModel($model);
static::createVersionForModel($model);
});

static::deleted(function (Model $model) {
if ($model->forceDeleting) {
$model->forceRemoveAllVersions();
} else {
self::createVersionForModel($model);
static::createVersionForModel($model);
}
});
}

private static function createVersionForModel(Model $model): void
{
if (self::$versioning && $model->shouldVersioning()) {
if (static::$versioning && $model->shouldVersioning()) {
Version::createForModel($model);
$model->removeOldVersions($model->getKeepVersionsCount());
}
Expand Down Expand Up @@ -288,15 +288,32 @@ public function versionableFromArray(array $attributes): array
return $attributes;
}

public static function getVersioning()
{
return static::$versioning;
}

/**
* @param callable $callback
*/
public static function withoutVersion(callable $callback)
{
self::$versioning = false;
$lastState = static::$versioning;

static::disableVersioning();

\call_user_func($callback);

self::$versioning = true;
static::$versioning = $lastState;
}

public static function disableVersioning()
{
static::$versioning = false;
}

public static function enableVersioning()
{
static::$versioning = true;
}
}
14 changes: 14 additions & 0 deletions tests/FeatureTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ protected function setUp(): void
{
parent::setUp();

Post::enableVersioning();

config(['auth.providers.users.model' => User::class]);

$this->user = User::create(['name' => 'overtrue']);
Expand Down Expand Up @@ -150,13 +152,25 @@ public function user_can_disable_version_control()
$post->refresh();
$this->assertCount(1, $post->versions);

$this->assertTrue(Post::getVersioning());

Post::withoutVersion(function () use ($post) {
$post->update(['title' => 'version2']);
});

$this->assertTrue(Post::getVersioning());
$post->refresh();

$this->assertCount(1, $post->versions);
$this->assertSame(['title' => 'version1', 'content' => 'version1 content'], $post->lastVersion->contents);

Post::disableVersioning();
Post::withoutVersion(function () use ($post) {
$post->update(['title' => 'version2']);
});

$this->assertFalse(Post::getVersioning());
$post->refresh();
}

/**
Expand Down

0 comments on commit 6663022

Please sign in to comment.