Skip to content

Commit

Permalink
Merge pull request #49 from tonysm/tm/fix-shouldnt-touch-when-ignorin…
Browse files Browse the repository at this point in the history
…g-touching

Fix should not touch records timestamp when touching is disabled
  • Loading branch information
tonysm authored Mar 3, 2024
2 parents d20a4dd + 932a1da commit cd77595
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 4 deletions.
10 changes: 6 additions & 4 deletions src/Models/Traits/HasRichText.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,11 +20,13 @@ protected static function bootHasRichText()
}

static::saving(function (Model $model) {
foreach ($model->getRichTextFields() as $field => $_options) {
$relationship = static::fieldToRichTextRelationship($field);
if (! $model::isIgnoringTouch()) {
foreach ($model->getRichTextFields() as $field => $_options) {
$relationship = static::fieldToRichTextRelationship($field);

if ($model->relationLoaded($relationship) && $model->{$field}->isDirty() && $model->timestamps) {
$model->updateTimestamps();
if ($model->relationLoaded($relationship) && $model->{$field}->isDirty() && $model->timestamps) {
$model->updateTimestamps();
}
}
}
});
Expand Down
38 changes: 38 additions & 0 deletions tests/ModelTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

namespace Tonysm\RichTextLaravel\Tests;

use Illuminate\Database\Eloquent\Model;
use Workbench\App\Models\Post;
use Workbench\Database\Factories\PostFactory;

class ModelTest extends TestCase
Expand Down Expand Up @@ -117,4 +119,40 @@ public function doesnt_touch_record_when_rich_text_isnt_updated()

$this->assertTrue($post->created_at->eq($post->updated_at), 'Record timestamps were touched, but it shouldnt.');
}

/** @test */
public function doesnt_touch_record_when_touching_is_disabled_on_the_specific_model()
{
$this->freezeTime();

$post = PostFactory::new()->create([
'body' => '<h1>Old Value</h1>',
])->fresh();

$this->travel(5)->minutes();

Post::withoutTouching(fn () => $post->update([
'body' => '<h1>New Value</h1>',
]));

$this->assertTrue($post->refresh()->created_at->eq($post->refresh()->updated_at), 'Record timestamps were touched, but it shouldnt.');
}

/** @test */
public function doesnt_touch_record_when_touching_is_disabled_globally()
{
$this->freezeTime();

$post = PostFactory::new()->create([
'body' => '<h1>Old Value</h1>',
])->fresh();

$this->travel(5)->minutes();

Model::withoutTouching(fn () => $post->update([
'body' => '<h1>New Value</h1>',
]));

$this->assertTrue($post->refresh()->created_at->eq($post->refresh()->updated_at), 'Record timestamps were touched, but it shouldnt.');
}
}

0 comments on commit cd77595

Please sign in to comment.