Skip to content

Commit

Permalink
Add countMedia
Browse files Browse the repository at this point in the history
  • Loading branch information
salamwaddah committed Feb 1, 2024
1 parent a1ab078 commit 0f3bfe2
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 1 deletion.
10 changes: 9 additions & 1 deletion src/InteractsWithMedia.php
Original file line number Diff line number Diff line change
Expand Up @@ -240,12 +240,20 @@ public function copyMedia(string|UploadedFile $file): FileAdder
return $this->addMedia($file)->preservingOriginal();
}

/*
* Count media in the given collection.
*/
public function countMedia(string $collectionName = 'default', array $filters = []): int
{
return count($this->getMedia($collectionName, $filters));
}

/*
* Determine if there is media in the given collection.
*/
public function hasMedia(string $collectionName = 'default', array $filters = []): bool
{
return count($this->getMedia($collectionName, $filters)) ? true : false;
return $this->countMedia($collectionName, $filters) ? true : false;
}

/**
Expand Down
46 changes: 46 additions & 0 deletions tests/Feature/InteractsWithMedia/CountMediaTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
<?php

it('returns zero for an empty collection', function () {
expect($this->testModel->countMedia())->toEqual(0);
});

it('returns count for a non empty collection', function () {
$this->testModel->addMedia($this->getTestJpg())->toMediaCollection();
$this->testModel->addMedia($this->getTestPng())->toMediaCollection();

expect($this->testModel->countMedia())->toEqual(2);
});

it('returns count for a non empty collection in an unsaved model', function () {
$this->testUnsavedModel->addMedia($this->getTestJpg())->toMediaCollection();

expect($this->testUnsavedModel->countMedia())->toEqual(1);
});

it('returns count if any collection is not empty', function () {
$this->testModel->addMedia($this->getTestJpg())->toMediaCollection('images');

expect($this->testModel->countMedia('images'))->toEqual(1);
});

it('returns zero for an empty named collection', function () {
expect($this->testModel->countMedia('images'))->toEqual(0);
});

it('returns count for a non empty named collection', function () {
$this->testModel->addMedia($this->getTestJpg())->toMediaCollection('images');

expect($this->testModel->countMedia('images'))->toEqual(1);
expect($this->testModel->countMedia('downloads'))->toEqual(0);
});

it('returns count for a filtered collection', function () {
$this->testModel
->addMedia($this->getTestJpg())
->withCustomProperties(['test' => true])
->toMediaCollection();

expect($this->testModel->countMedia('default'))->toEqual(1);
expect($this->testModel->countMedia('default', ['test' => true]))->toEqual(1);
expect($this->testModel->countMedia('default', ['test' => false]))->toEqual(0);
});

0 comments on commit 0f3bfe2

Please sign in to comment.