2020-10-07 08:35:39 +01:00
|
|
|
<?php
|
|
|
|
|
|
|
|
declare(strict_types=1);
|
|
|
|
|
|
|
|
namespace Drupal\opdavies_blog\Repository;
|
|
|
|
|
|
|
|
use Drupal\Core\Entity\EntityStorageInterface;
|
|
|
|
use Drupal\Core\Entity\EntityTypeManagerInterface;
|
2020-10-07 13:16:58 +01:00
|
|
|
use Drupal\Core\Entity\Query\QueryInterface;
|
2021-01-13 08:52:51 +00:00
|
|
|
use Drupal\node\NodeInterface;
|
2020-10-07 08:35:39 +01:00
|
|
|
use Drupal\opdavies_blog\Entity\Node\Post;
|
2020-10-07 13:15:12 +01:00
|
|
|
use Drupal\taxonomy\TermInterface;
|
2021-04-23 08:58:14 +01:00
|
|
|
use Illuminate\Support\Collection;
|
2020-10-07 08:35:39 +01:00
|
|
|
|
|
|
|
final class RelatedPostsRepository {
|
|
|
|
|
|
|
|
private EntityStorageInterface $nodeStorage;
|
|
|
|
|
|
|
|
public function __construct(
|
|
|
|
EntityTypeManagerInterface $entityTypeManager
|
|
|
|
) {
|
|
|
|
$this->nodeStorage = $entityTypeManager->getStorage('node');
|
|
|
|
}
|
|
|
|
|
|
|
|
public function getFor(Post $post): Collection {
|
2020-10-07 13:15:12 +01:00
|
|
|
$tags = $post->get('field_tags')->referencedEntities();
|
|
|
|
|
|
|
|
if (!$tags) {
|
|
|
|
return new Collection();
|
|
|
|
}
|
|
|
|
|
|
|
|
$tagIds = (new Collection($tags))
|
|
|
|
->map(fn(TermInterface $tag) => $tag->id())
|
|
|
|
->values();
|
|
|
|
|
2020-10-07 13:16:58 +01:00
|
|
|
/** @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 {
|
2020-10-07 08:52:18 +01:00
|
|
|
$query = $this->nodeStorage->getQuery();
|
2020-10-07 08:35:39 +01:00
|
|
|
|
2020-10-07 08:52:18 +01:00
|
|
|
// Ensure that the current node ID is not returned as a related post.
|
|
|
|
$query->condition('nid', $post->id(), '!=');
|
|
|
|
|
2020-10-07 13:16:58 +01:00
|
|
|
// Only return posts with the same tags.
|
2020-10-07 13:15:12 +01:00
|
|
|
$query->condition('field_tags', $tagIds->toArray(), 'IN');
|
|
|
|
|
2021-01-13 08:52:51 +00:00
|
|
|
$query->condition('status', NodeInterface::PUBLISHED);
|
|
|
|
|
2020-10-07 13:16:58 +01:00
|
|
|
return $query;
|
2020-10-07 08:35:39 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
}
|