From 434e627edd13d19ea139f5e0dfed55e5b480cf9e Mon Sep 17 00:00:00 2001 From: Thomas Nadin Date: Sat, 5 Apr 2025 15:30:19 +0100 Subject: [PATCH] Adds EntryRepository#findByIds() --- src/Contracts/Entries/EntryRepository.php | 2 ++ src/Stache/Repositories/EntryRepository.php | 13 +++++++++++ .../Repositories/EntryRepositoryTest.php | 22 +++++++++++++++++++ 3 files changed, 37 insertions(+) diff --git a/src/Contracts/Entries/EntryRepository.php b/src/Contracts/Entries/EntryRepository.php index c306eba1a5..66d128b8ff 100644 --- a/src/Contracts/Entries/EntryRepository.php +++ b/src/Contracts/Entries/EntryRepository.php @@ -16,6 +16,8 @@ public function findOrFail($id); public function findByUri(string $uri); + public function findByIds($ids); + public function make(); public function query(); diff --git a/src/Stache/Repositories/EntryRepository.php b/src/Stache/Repositories/EntryRepository.php index 1aac62567b..2a61e54800 100644 --- a/src/Stache/Repositories/EntryRepository.php +++ b/src/Stache/Repositories/EntryRepository.php @@ -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()) { diff --git a/tests/Stache/Repositories/EntryRepositoryTest.php b/tests/Stache/Repositories/EntryRepositoryTest.php index 965933fc68..ac9973bf2d 100644 --- a/tests/Stache/Repositories/EntryRepositoryTest.php +++ b/tests/Stache/Repositories/EntryRepositoryTest.php @@ -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; @@ -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() {