From 3546ac427a27268276d06833183edca6f9d2af56 Mon Sep 17 00:00:00 2001 From: Oliver Davies Date: Wed, 7 Oct 2020 13:16:58 +0100 Subject: [PATCH] Extract a method to contain the query logic Group all of the query logic into one method, as this will make it more readable and this logic is likely to grow. References #3 --- .../src/Repository/RelatedPostsRepository.php | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) diff --git a/web/modules/custom/blog/src/Repository/RelatedPostsRepository.php b/web/modules/custom/blog/src/Repository/RelatedPostsRepository.php index 2328497..add8998 100644 --- a/web/modules/custom/blog/src/Repository/RelatedPostsRepository.php +++ b/web/modules/custom/blog/src/Repository/RelatedPostsRepository.php @@ -6,6 +6,7 @@ namespace Drupal\opdavies_blog\Repository; use Drupal\Core\Entity\EntityStorageInterface; use Drupal\Core\Entity\EntityTypeManagerInterface; +use Drupal\Core\Entity\Query\QueryInterface; use Drupal\opdavies_blog\Entity\Node\Post; use Drupal\taxonomy\TermInterface; use Illuminate\Support\Collection; @@ -31,19 +32,24 @@ final class RelatedPostsRepository { ->map(fn(TermInterface $tag) => $tag->id()) ->values(); + /** @var array $postIds */ + $postIds = $this->query($post, $tagIds)->execute(); + + $posts = $this->nodeStorage->loadMultiple($postIds); + + return new Collection(array_values($posts)); + } + + private function query(Post $post, Collection $tagIds): QueryInterface { $query = $this->nodeStorage->getQuery(); // Ensure that the current node ID is not returned as a related post. $query->condition('nid', $post->id(), '!='); + // Only return posts with the same tags. $query->condition('field_tags', $tagIds->toArray(), 'IN'); - /** @var array $postIds */ - $postIds = $query->execute(); - - $posts = $this->nodeStorage->loadMultiple($postIds); - - return (new Collection($posts))->values(); + return $query; } }