From 94f95cf7ea6a07d5e885dbb8856ffa4175e2c102 Mon Sep 17 00:00:00 2001 From: Chris Rossi Date: Tue, 20 Aug 2024 11:43:29 +0930 Subject: [PATCH] Add support for callables in hasMedia filters * Update hasMedia to support both array and callable filters, as per getMedia() * Update test coverage --- src/InteractsWithMedia.php | 2 +- .../InteractsWithMedia/HasMediaTest.php | 31 +++++++++++++++++++ 2 files changed, 32 insertions(+), 1 deletion(-) diff --git a/src/InteractsWithMedia.php b/src/InteractsWithMedia.php index 6e7eb730e..44b4604bf 100644 --- a/src/InteractsWithMedia.php +++ b/src/InteractsWithMedia.php @@ -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; } diff --git a/tests/Feature/InteractsWithMedia/HasMediaTest.php b/tests/Feature/InteractsWithMedia/HasMediaTest.php index e5d5baf7f..fee5f83c9 100644 --- a/tests/Feature/InteractsWithMedia/HasMediaTest.php +++ b/tests/Feature/InteractsWithMedia/HasMediaTest.php @@ -1,5 +1,7 @@ testModel->hasMedia())->toBeFalse(); }); @@ -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(); +});