Skip to content

[5.x] Adds EntryRepository#findByIds() #11668

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

Open
wants to merge 1 commit into
base: 5.x
Choose a base branch
from
Open
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
2 changes: 2 additions & 0 deletions src/Contracts/Entries/EntryRepository.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ public function findOrFail($id);

public function findByUri(string $uri);

public function findByIds($ids);

public function make();

public function query();
Expand Down
13 changes: 13 additions & 0 deletions src/Stache/Repositories/EntryRepository.php
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,19 @@ public function findByUri(string $uri, ?string $site = null): ?Entry
: $entry;
}

public function findByIds($ids): EntryCollection
{
$entries = $this->query()->whereIn('id', $ids)->get();
$entriesById = $entries->keyBy->id();

$ordered = collect($ids)
->map(fn ($id) => $entriesById->get($id))
->filter()
->values();

return EntryCollection::make($ordered);
}

public function save($entry)
{
if (! $entry->id()) {
Expand Down
22 changes: 22 additions & 0 deletions tests/Stache/Repositories/EntryRepositoryTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
namespace Tests\Stache\Repositories;

use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\Attributes\Group;
use PHPUnit\Framework\Attributes\Test;
use Statamic\Contracts\Entries\Entry;
use Statamic\Entries\EntryCollection;
Expand Down Expand Up @@ -190,6 +191,27 @@ public function it_gets_entry_by_structure_uri()
$this->assertEquals('Directors', $entry->title());
}

#[Test, Group('EntryRepository#findByIds')]
#[DataProvider('entriesByIdsProvider')]
public function it_gets_entries_by_ids($ids, $expected)
{
$actual = $this->repo->findByIds($ids);

$this->assertInstanceOf(EntryCollection::class, $actual);
$this->assertEquals($expected, $actual->map->get('title')->all());
}

public static function entriesByIdsProvider()
{
return [
'no ids' => [[], []],
'single' => [['numeric-one'], ['One']],
'multiple' => [['numeric-one', 'numeric-two', 'numeric-three'], ['One', 'Two', 'Three']],
'missing' => [['numeric-one', 'unknown', 'numeric-three'], ['One', 'Three']],
'ordered' => [['numeric-three', 'numeric-one', 'numeric-two'], ['Three', 'One', 'Two']],
];
}

#[Test]
public function it_saves_an_entry_to_the_stache_and_to_a_file()
{
Expand Down