diff --git a/web/modules/custom/my_module/my_module.services.yml b/web/modules/custom/my_module/my_module.services.yml index 23aee82..a97d210 100644 --- a/web/modules/custom/my_module/my_module.services.yml +++ b/web/modules/custom/my_module/my_module.services.yml @@ -1,3 +1,6 @@ services: + Drupal\my_module\Controller\BlogPageController: + autowire: true + Drupal\my_module\Repository\ArticleRepository: autowire: true diff --git a/web/modules/custom/my_module/src/Controller/BlogPageController.php b/web/modules/custom/my_module/src/Controller/BlogPageController.php index ae4d46a..59b6599 100644 --- a/web/modules/custom/my_module/src/Controller/BlogPageController.php +++ b/web/modules/custom/my_module/src/Controller/BlogPageController.php @@ -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 */ 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), ]; } diff --git a/web/modules/custom/my_module/tests/src/Functional/BlogPageTest.php b/web/modules/custom/my_module/tests/src/Functional/BlogPageTest.php index 1405f0e..f1c9764 100644 --- a/web/modules/custom/my_module/tests/src/Functional/BlogPageTest.php +++ b/web/modules/custom/my_module/tests/src/Functional/BlogPageTest.php @@ -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'); + } + }