feat(blog): use the article repository

Use the `ArticleRepository` within `BlogPageController` to load and
retrieve article nodes.
This commit is contained in:
Oliver Davies 2023-08-08 12:00:00 +01:00
parent f09464f9f7
commit 7e3324b77f
3 changed files with 50 additions and 1 deletions

View file

@ -1,3 +1,6 @@
services:
Drupal\my_module\Controller\BlogPageController:
autowire: true
Drupal\my_module\Repository\ArticleRepository:
autowire: true

View file

@ -4,18 +4,47 @@ declare(strict_types=1);
namespace Drupal\my_module\Controller;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Entity\EntityViewBuilderInterface;
use Drupal\Core\Render\RendererInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\my_module\Repository\ArticleRepository;
final class BlogPageController {
use StringTranslationTrait;
private EntityViewBuilderInterface $nodeViewBuilder;
public function __construct(
private RendererInterface $renderer,
EntityTypeManagerInterface $entityTypeManager,
private ArticleRepository $articleRepository,
) {
$this->nodeViewBuilder = $entityTypeManager->getViewBuilder(entity_type_id: 'node');
}
/**
* @return array<string, mixed>
*/
public function __invoke(): array {
$articles = $this->articleRepository->getAll();
if ($articles === []) {
return ['#markup' => $this->t('Welcome to my blog!')];
}
$build = [];
foreach ($articles as $article) {
$build[] = $this->nodeViewBuilder->view(
entity: $article,
view_mode: 'teaser',
);
}
return [
'#markup' => $this->t('Welcome to my blog!'),
'#markup' => $this->renderer->render($build),
];
}

View file

@ -30,4 +30,21 @@ final class BlogPageTest extends BrowserTestBase {
$assert->pageTextContains('Welcome to my blog!');
}
/** @test */
public function it_shows_articles(): void {
$this->createContentType(['type' => 'article']);
$this->createNode([
'title' => 'This is a test article',
'type' => 'article',
]);
$this->drupalGet('/blog');
$assert = $this->assertSession();
$assert->statusCodeEquals(Response::HTTP_OK);
$assert->pageTextContains('This is a test article');
}
}