33namespace Tonysm \RichTextLaravel \Tests ;
44
55use Illuminate \Support \Facades \DB ;
6+ use Illuminate \Support \Facades \Storage ;
67use Tonysm \RichTextLaravel \Content ;
78use Tonysm \RichTextLaravel \Exceptions \RichTextException ;
89use Tonysm \RichTextLaravel \Models \RichText ;
@@ -222,6 +223,35 @@ public function can_update_content(): void
222223 HTML, "{$ post ->body }" );
223224 }
224225
226+ #[\PHPUnit \Framework \Attributes \Test]
227+ public function can_delete_attachments (): void
228+ {
229+ Storage::fake ('public ' );
230+
231+ $ firstImage = '/images/attachments/post-01.png ' ;
232+ $ secondImage = '/images/attachments/post-02.png ' ;
233+
234+ Storage::disk ('public ' )->put ($ firstImage , '' );
235+ Storage::disk ('public ' )->put ($ secondImage , '' );
236+
237+ $ encodeImage = fn (string $ imageUrl ) => e ($ imageUrl );
238+
239+ $ post = PostForDeleting::create ([
240+ 'title ' => 'Has attachments ' ,
241+ 'body ' => <<<HTML
242+ <div>
243+ <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>
244+ <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>
245+ </div>
246+ HTML ,
247+ ]);
248+
249+ $ post ->delete ();
250+
251+ Storage::disk ('public ' )->assertMissing ($ firstImage );
252+ Storage::disk ('public ' )->assertMissing ($ secondImage );
253+ }
254+
225255 private function createPost (?string $ body = null , ?string $ notes = null ): PostWithNotes
226256 {
227257 return PostWithNotes::create (PostFactory::new ()->raw ([
@@ -248,3 +278,21 @@ class PostWithNotes extends Post
248278 'notes ' ,
249279 ];
250280}
281+
282+ class PostForDeleting extends Post
283+ {
284+ protected $ table = 'posts ' ;
285+
286+ protected $ richTextAttributes = [
287+ 'body ' ,
288+ ];
289+
290+ public static function booted (): void
291+ {
292+ static ::deleted (function (Post $ post ) {
293+ foreach ($ post ->body ->attachments () as $ attachment ) {
294+ Storage::disk ('public ' )->delete ($ attachment ->attachable ->url );
295+ }
296+ });
297+ }
298+ }
0 commit comments