Display a list of related post titles

References #3
This commit is contained in:
Oliver Davies 2021-01-11 00:58:54 +00:00
parent 1f82a07226
commit 105405e7f9
2 changed files with 65 additions and 3 deletions

View file

@ -3,6 +3,13 @@
namespace Drupal\opdavies_blog\Plugin\Block;
use Drupal\Core\Block\BlockBase;
use Drupal\Core\Link;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\Core\Routing\CurrentRouteMatch;
use Drupal\opdavies_blog\Entity\Node\Post;
use Drupal\opdavies_blog\Repository\RelatedPostsRepository;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Tightenco\Collect\Support\Collection;
/**
* @Block(
@ -11,14 +18,69 @@ use Drupal\Core\Block\BlockBase;
* category = @Translation("Blog")
* )
*/
class RelatedPostsBlock extends BlockBase {
class RelatedPostsBlock extends BlockBase implements ContainerFactoryPluginInterface {
private CurrentRouteMatch $currentRouteMatch;
private RelatedPostsRepository $relatedPostsRepository;
public function __construct(
array $configuration,
string $pluginId,
array $pluginDefinition,
CurrentRouteMatch $currentRouteMatch,
RelatedPostsRepository $relatedPostsRepository
) {
parent::__construct($configuration, $pluginId, $pluginDefinition);
$this->currentRouteMatch = $currentRouteMatch;
$this->relatedPostsRepository = $relatedPostsRepository;
}
public static function create(
ContainerInterface $container,
array $configuration,
$pluginId,
$pluginDefinition
): self {
// @phpstan-ignore-next-line
return new self(
$configuration,
$pluginId,
$pluginDefinition,
$container->get('current_route_match'),
$container->get(RelatedPostsRepository::class)
);
}
public function build(): array {
$currentPost = $this->currentRouteMatch->getParameter('node');
/** @var Collection|Post[] $relatedPosts */
$relatedPosts = $this->relatedPostsRepository->getFor($currentPost);
if ($relatedPosts->isEmpty()) {
return [];
}
$build['content'] = [
'#markup' => $this->t('It works!'),
'#theme' => 'item_list',
'#items' => $relatedPosts
->sortByDesc(fn(Post $post) => $post->getCreatedTime())
->map(fn(Post $post) => $this->generateLinkToPost($post))
->slice(0, 3)
->toArray(),
];
return $build;
}
private function generateLinkToPost(Post $post): Link {
return Link::createFromRoute(
$post->getTitle(),
'entity.node.canonical',
['node' => $post->id()]
);
}
}

View file

@ -9,7 +9,7 @@ use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Entity\Query\QueryInterface;
use Drupal\opdavies_blog\Entity\Node\Post;
use Drupal\taxonomy\TermInterface;
use Illuminate\Support\Collection;
use Tightenco\Collect\Support\Collection;
final class RelatedPostsRepository {