Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix detachMedia deleting all files #96

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 15 additions & 10 deletions src/MediaAlly.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

use Exception;
use CloudinaryLabs\CloudinaryLaravel\Model\Media;
use Illuminate\Support\Collection;

/**
* MediaAlly
Expand Down Expand Up @@ -77,22 +78,26 @@ public function fetchFirstMedia()
}

/**
* Delete all/one file(s) associated with a particular Model record
*/
public function detachMedia(Media $media = null)
* Delete all/one/multiple file(s) associated with a particular Model record
*
* @param Media|Collection|null $media
* @return void
*/
public function detachMedia(Media|Collection $media = null)
{

$items = $this->medially()->get();
if (is_null($media)) {
$items = $this->medially()->get();
} elseif ($media instanceof Media) {
$items = new Collection([$this->medially()->find($media->id)]);
} elseif ($media instanceof Collection) {
$items = $this->medially()->whereIn('id', $media->pluck('id'))->get();
}

foreach($items as $item) {
resolve(CloudinaryEngine::class)->destroy($item->getFileName());

if (!is_null($media) && $item->id == $media->id) {
return $item->delete();
}
$item->delete();
}

return $this->medially()->delete();
}

/**
Expand Down
17 changes: 13 additions & 4 deletions tests/DetachMediaTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -32,16 +32,25 @@ public function test_can_detach_one_media_or_all()

$model = MyModel::create([]);

$model->attachMedia(UploadedFile::fake()->image('file.jpg'));
$model->attachMedia(UploadedFile::fake()->image('file.jpg'));
for ($i = 0; $i < 10; $i++) {
$model->attachMedia(UploadedFile::fake()->image('file.jpg'));
}

$this->assertCount(2, $model->fetchAllMedia());
$this->assertCount(10, $model->fetchAllMedia());

// Delete one
$media1 = $model->fetchAllMedia()->first();
$model->detachMedia($media1);

$this->assertCount(1, $model->fetchAllMedia());
$this->assertCount(9, $model->fetchAllMedia());

// Delete multiple
$multiple_media = $model->fetchAllMedia()->slice(0, 4);
$model->detachMedia($multiple_media);

$this->assertCount(5, $model->fetchAllMedia());

// Delete all
$model->detachMedia();
$this->assertCount(0, $model->fetchAllMedia());
}
Expand Down