Skip to content

Commit fb208e9

Browse files
committed
Adds the observer example
1 parent e1a35bc commit fb208e9

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed

tests/RichTextModelTest.php

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
namespace Tonysm\RichTextLaravel\Tests;
44

5+
use Illuminate\Database\Eloquent\Attributes\ObservedBy;
56
use Illuminate\Support\Facades\DB;
67
use Illuminate\Support\Facades\Storage;
78
use Tonysm\RichTextLaravel\Content;
@@ -252,6 +253,35 @@ public function can_delete_attachments(): void
252253
Storage::disk('public')->assertMissing($secondImage);
253254
}
254255

256+
#[\PHPUnit\Framework\Attributes\Test]
257+
public function can_delete_via_observers(): void
258+
{
259+
Storage::fake('public');
260+
261+
$firstImage = '/images/attachments/post-01.png';
262+
$secondImage = '/images/attachments/post-02.png';
263+
264+
Storage::disk('public')->put($firstImage, '');
265+
Storage::disk('public')->put($secondImage, '');
266+
267+
$encodeImage = fn (string $imageUrl) => e($imageUrl);
268+
269+
$post = PostForDeletingViaObserver::create([
270+
'title' => 'Has attachments',
271+
'body' => <<<HTML
272+
<div>
273+
<figure data-trix-attachment='{"contentType":"image\/jpeg","url":"{$encodeImage($firstImage)}","href":"{$encodeImage($firstImage)}","filename":"first-image.jpg","filesize":47665,"width":880,"height":660}' data-trix-attributes='{"presentation":"gallery","caption":"First Image"}'></figure>
274+
<figure data-trix-attachment='{"contentType":"image\/jpeg","url":"{$encodeImage($secondImage)}","href":"{$encodeImage($secondImage)}","filename":"first-image.jpg","filesize":47665,"width":880,"height":660}' data-trix-attributes='{"presentation":"gallery","caption":"First Image"}'></figure>
275+
</div>
276+
HTML,
277+
]);
278+
279+
$post->delete();
280+
281+
Storage::disk('public')->assertMissing($firstImage);
282+
Storage::disk('public')->assertMissing($secondImage);
283+
}
284+
255285
private function createPost(?string $body = null, ?string $notes = null): PostWithNotes
256286
{
257287
return PostWithNotes::create(PostFactory::new()->raw([
@@ -296,3 +326,23 @@ public static function booted(): void
296326
});
297327
}
298328
}
329+
330+
#[ObservedBy([DeleteAttachmentsObserver::class])]
331+
class PostForDeletingViaObserver extends Post
332+
{
333+
protected $table = 'posts';
334+
335+
protected $richTextAttributes = [
336+
'body',
337+
];
338+
}
339+
340+
class DeleteAttachmentsObserver
341+
{
342+
public function deleted($model): void
343+
{
344+
foreach ($model->body->attachments() as $attachment) {
345+
Storage::disk('public')->delete($attachment->attachable->url);
346+
}
347+
}
348+
}

0 commit comments

Comments
 (0)