|
2 | 2 |
|
3 | 3 | namespace Tonysm\RichTextLaravel\Tests; |
4 | 4 |
|
| 5 | +use Illuminate\Database\Eloquent\Attributes\ObservedBy; |
5 | 6 | use Illuminate\Support\Facades\DB; |
6 | 7 | use Illuminate\Support\Facades\Storage; |
7 | 8 | use Tonysm\RichTextLaravel\Content; |
@@ -252,6 +253,35 @@ public function can_delete_attachments(): void |
252 | 253 | Storage::disk('public')->assertMissing($secondImage); |
253 | 254 | } |
254 | 255 |
|
| 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 | + |
255 | 285 | private function createPost(?string $body = null, ?string $notes = null): PostWithNotes |
256 | 286 | { |
257 | 287 | return PostWithNotes::create(PostFactory::new()->raw([ |
@@ -296,3 +326,23 @@ public static function booted(): void |
296 | 326 | }); |
297 | 327 | } |
298 | 328 | } |
| 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