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
This commit is contained in:
Oliver Davies 2020-10-07 08:35:39 +01:00
parent 62424d5b04
commit d7f3d8c482
3 changed files with 73 additions and 0 deletions

View file

@ -0,0 +1,32 @@
<?php
declare(strict_types=1);
namespace Drupal\opdavies_blog\Repository;
use Drupal\Core\Entity\EntityStorageInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\opdavies_blog\Entity\Node\Post;
use Illuminate\Support\Collection;
final class RelatedPostsRepository {
private EntityStorageInterface $nodeStorage;
public function __construct(
EntityTypeManagerInterface $entityTypeManager
) {
$this->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();
}
}