Refactor to use an entity query

Refactor from using `loadByProperties` to using an entity query.

`loadByProperties` doesn't allow for passing multiple values for a
single property such as multiple tags to compare against, and also means
that removing the current node can be done in the query rather than
filtering it out of the Collection.

This might also be a more performant solution if we can do the grouping
and sorting of the results in the query rather than needing to perform
additional steps on the result.

References #3
This commit is contained in:
Oliver Davies 2020-10-07 08:52:18 +01:00
parent d7f3d8c482
commit b90ca42e87

View file

@ -20,13 +20,17 @@ final class RelatedPostsRepository {
}
public function getFor(Post $post): Collection {
$posts = $this->nodeStorage->loadByProperties([
'type' => 'post',
]);
$query = $this->nodeStorage->getQuery();
return (new Collection($posts))
->filter(fn(Post $relatedPost) => $relatedPost->id() != $post->id())
->values();
// Ensure that the current node ID is not returned as a related post.
$query->condition('nid', $post->id(), '!=');
/** @var array $postIds */
$postIds = $query->execute();
$posts = $this->nodeStorage->loadMultiple($postIds);
return (new Collection($posts))->values();
}
}