Skip to content

Commit

Permalink
Add support for callables in hasMedia filters
Browse files Browse the repository at this point in the history
* Update hasMedia to support both array and callable filters, as per getMedia()
* Update test coverage
  • Loading branch information
crossiatlas committed Aug 20, 2024
1 parent 5d17547 commit 94f95cf
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 1 deletion.
2 changes: 1 addition & 1 deletion src/InteractsWithMedia.php
Original file line number Diff line number Diff line change
Expand Up @@ -242,7 +242,7 @@ public function copyMedia(string|UploadedFile $file): FileAdder
/*
* Determine if there is media in the given collection.
*/
public function hasMedia(string $collectionName = 'default', array $filters = []): bool
public function hasMedia(string $collectionName = 'default', array|callable $filters = []): bool
{
return count($this->getMedia($collectionName, $filters)) ? true : false;
}
Expand Down
31 changes: 31 additions & 0 deletions tests/Feature/InteractsWithMedia/HasMediaTest.php
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
<?php

use Spatie\MediaLibrary\MediaCollections\Models\Media;

it('returns false for an empty collection', function () {
expect($this->testModel->hasMedia())->toBeFalse();
});
Expand Down Expand Up @@ -43,3 +45,32 @@
expect($this->testModel->hasMedia('default', ['test' => true]))->toBeTrue();
expect($this->testModel->hasMedia('default', ['test' => false]))->toBeFalse();
});

it('returns true using a filter callback', function () {
$media1 = $this->testModel
->addMedia($this->getTestJpg())
->preservingOriginal()
->withCustomProperties(['filter1' => 'value1'])
->toMediaCollection();

$media2 = $this->testModel
->addMedia($this->getTestJpg())
->preservingOriginal()
->withCustomProperties(['filter1' => 'value2'])
->toMediaCollection('images');

$media3 = $this->testModel
->addMedia($this->getTestJpg())
->preservingOriginal()
->withCustomProperties(['filter2' => 'value1'])
->toMediaCollection('images');

$media4 = $this->testModel
->addMedia($this->getTestJpg())
->preservingOriginal()
->withCustomProperties(['filter2' => 'value2'])
->toMediaCollection('images');

expect($this->testModel->hasMedia('images', fn (Media $media) => isset($media->custom_properties['filter1'])))->toBeTrue();
expect($this->testModel->hasMedia('images', fn (Media $media) => isset($media->custom_properties['filter3'])))->toBeFalse();
});

0 comments on commit 94f95cf

Please sign in to comment.