From ae0024f33574a679978efe7dc3307e23075892f6 Mon Sep 17 00:00:00 2001 From: Oliver Davies Date: Wed, 7 Oct 2020 13:15:12 +0100 Subject: [PATCH] Return an empty Collection if there are no posts Return an empty Collection if there are no related posts for the given post. References #3 --- .../src/Repository/RelatedPostsRepository.php | 13 +++++++++++++ .../tests/src/Kernel/RelatedPostsTest.php | 19 +++++++++++++++++++ 2 files changed, 32 insertions(+) diff --git a/web/modules/custom/blog/src/Repository/RelatedPostsRepository.php b/web/modules/custom/blog/src/Repository/RelatedPostsRepository.php index c59e560..2328497 100644 --- a/web/modules/custom/blog/src/Repository/RelatedPostsRepository.php +++ b/web/modules/custom/blog/src/Repository/RelatedPostsRepository.php @@ -7,6 +7,7 @@ namespace Drupal\opdavies_blog\Repository; use Drupal\Core\Entity\EntityStorageInterface; use Drupal\Core\Entity\EntityTypeManagerInterface; use Drupal\opdavies_blog\Entity\Node\Post; +use Drupal\taxonomy\TermInterface; use Illuminate\Support\Collection; final class RelatedPostsRepository { @@ -20,11 +21,23 @@ final class RelatedPostsRepository { } public function getFor(Post $post): Collection { + $tags = $post->get('field_tags')->referencedEntities(); + + if (!$tags) { + return new Collection(); + } + + $tagIds = (new Collection($tags)) + ->map(fn(TermInterface $tag) => $tag->id()) + ->values(); + $query = $this->nodeStorage->getQuery(); // Ensure that the current node ID is not returned as a related post. $query->condition('nid', $post->id(), '!='); + $query->condition('field_tags', $tagIds->toArray(), 'IN'); + /** @var array $postIds */ $postIds = $query->execute(); diff --git a/web/modules/custom/blog/tests/src/Kernel/RelatedPostsTest.php b/web/modules/custom/blog/tests/src/Kernel/RelatedPostsTest.php index 6c5c6a5..080190e 100644 --- a/web/modules/custom/blog/tests/src/Kernel/RelatedPostsTest.php +++ b/web/modules/custom/blog/tests/src/Kernel/RelatedPostsTest.php @@ -33,6 +33,25 @@ final class RelatedPostsTest extends PostTestBase { $this->assertSame('Post B', $relatedPosts->first()->label()); } + /** @test */ + public function it_returns_an_empty_collection_if_there_are_no_related_posts(): void { + $postA = $this->postFactory + ->setTitle('Drupal 8 post') + ->withTags(['Drupal 8']) + ->create(); + $postA->save(); + + $postB = $this->postFactory + ->setTitle('Drupal 9 post') + ->withTags(['Drupal 9']) + ->create(); + $postB->save(); + + $relatedPosts = $this->relatedPostsRepository->getFor($postA); + + $this->assertEmpty($relatedPosts); + } + protected function setUp() { parent::setUp();