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
36 lines
896 B
PHP
36 lines
896 B
PHP
<?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 {
|
|
$query = $this->nodeStorage->getQuery();
|
|
|
|
// 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();
|
|
}
|
|
|
|
}
|