From d7f3d8c482cf457064af0c59f904221e768cdf54 Mon Sep 17 00:00:00 2001 From: Oliver Davies Date: Wed, 7 Oct 2020 08:35:39 +0100 Subject: [PATCH] Return related posts for a specified blog post Add the initial code for specifying a blog post and returning related posts. This includes adding a repository for related posts, and adding it as a service within the `opdavies_blog` module. References #3 --- .../custom/blog/opdavies_blog.services.yml | 3 ++ .../src/Repository/RelatedPostsRepository.php | 32 ++++++++++++++++ .../tests/src/Kernel/RelatedPostsTest.php | 38 +++++++++++++++++++ 3 files changed, 73 insertions(+) create mode 100644 web/modules/custom/blog/src/Repository/RelatedPostsRepository.php create mode 100644 web/modules/custom/blog/tests/src/Kernel/RelatedPostsTest.php diff --git a/web/modules/custom/blog/opdavies_blog.services.yml b/web/modules/custom/blog/opdavies_blog.services.yml index 85dc656..fb2dc2d 100644 --- a/web/modules/custom/blog/opdavies_blog.services.yml +++ b/web/modules/custom/blog/opdavies_blog.services.yml @@ -19,3 +19,6 @@ services: Drupal\opdavies_blog\Service\PostPusher\PostPusher: alias: Drupal\opdavies_blog\Service\PostPusher\IftttPostPusher + + Drupal\opdavies_blog\Repository\RelatedPostsRepository: + autowire: true diff --git a/web/modules/custom/blog/src/Repository/RelatedPostsRepository.php b/web/modules/custom/blog/src/Repository/RelatedPostsRepository.php new file mode 100644 index 0000000..3051ba6 --- /dev/null +++ b/web/modules/custom/blog/src/Repository/RelatedPostsRepository.php @@ -0,0 +1,32 @@ +nodeStorage = $entityTypeManager->getStorage('node'); + } + + public function getFor(Post $post): Collection { + $posts = $this->nodeStorage->loadByProperties([ + 'type' => 'post', + ]); + + return (new Collection($posts)) + ->filter(fn(Post $relatedPost) => $relatedPost->id() != $post->id()) + ->values(); + } + +} diff --git a/web/modules/custom/blog/tests/src/Kernel/RelatedPostsTest.php b/web/modules/custom/blog/tests/src/Kernel/RelatedPostsTest.php new file mode 100644 index 0000000..02555f8 --- /dev/null +++ b/web/modules/custom/blog/tests/src/Kernel/RelatedPostsTest.php @@ -0,0 +1,38 @@ +setTitle('Post A') + ->withTags(['Drupal 8']) + ->create(); + $postA->save(); + + $postB = (new PostFactory())->setTitle('Post B') + ->withTags(['Drupal 8']) + ->create(); + $postB->save(); + + $relatedPosts = $this->relatedPostsRepository->getFor($postA); + + $this->assertCount(1, $relatedPosts); + $this->assertSame('Post B', $relatedPosts->first()->label()); + } + + protected function setUp() { + parent::setUp(); + + $this->relatedPostsRepository = $this->container->get(RelatedPostsRepository::class); + } + +}