diff --git a/src/Plugin/Block/LoginBlock.php b/src/Plugin/Block/LoginBlock.php new file mode 100644 index 00000000..934d1681 --- /dev/null +++ b/src/Plugin/Block/LoginBlock.php @@ -0,0 +1,77 @@ +currentUser = $current_user; + } + + /** + * {@inheritdoc} + */ + public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) { + return new static( + $configuration, + $plugin_id, + $plugin_definition, + $container->get('current_user') + ); + } + + /** + * {@inheritdoc} + */ + public function build() { + if ($this->currentUser->isAnonymous()) { + return [ + '#type' => 'link', + '#title' => $this->t('Log in'), + '#url' => Url::fromRoute('user.login'), + ]; + } + + return [ + '#type' => 'link', + '#title' => $this->t('Log out'), + '#url' => Url::fromRoute('user.logout'), + ]; + } + + /** + * {@inheritdoc} + */ + public function getCacheContexts() { + return Cache::mergeContexts(parent::getCacheContexts(), ['user.roles:anonymous']); + } + +} diff --git a/tests/Kernel/LoginBlockTest.php b/tests/Kernel/LoginBlockTest.php new file mode 100644 index 00000000..28b0b77e --- /dev/null +++ b/tests/Kernel/LoginBlockTest.php @@ -0,0 +1,83 @@ +installConfig(['system', 'block', 'user']); + $this->installEntitySchema('user'); + $this->installSchema('system', ['sequences']); + } + + /** + * Test login block rendering. + */ + public function testLoginBlockRendering(): void { + + // Setup and render login block. + $block_manager = $this->container->get('plugin.manager.block'); + $renderer = $this->container->get('renderer'); + + /** @var \Drupal\oe_authentication\Plugin\Block\LoginBlock $plugin_block */ + $plugin_block = $block_manager->createInstance('oe_authentication_login_block'); + $build = $plugin_block->build(); + $block = (string) $renderer->renderRoot($build); + + $crawler = new Crawler($block); + + // Make sure the login link is present. + $link = $crawler->filter('a'); + $this->assertEquals(t('Log in'), $link->text()); + $this->assertEquals(Url::fromRoute('user.login')->toString(), $link->attr('href')); + + // Create a user to login. + $user1 = User::create([ + 'name' => 'oe_user1', + 'mail' => 'oe_user1@example.com', + ]); + + $user1->activate(); + $user1->save(); + + // Simulate a login of this user. + $this->container->get('current_user')->setAccount($user1); + + // Render the block again. + $build = $plugin_block->build(); + $block = (string) $renderer->renderRoot($build); + + // Asserts if the text changed, and log out text is now present. + $crawler = new Crawler($block); + $link = $crawler->filter('a'); + $this->assertEquals(t('Log out'), $link->text()); + $this->assertEquals(Url::fromRoute('user.logout')->toString(), $link->attr('href')); + } + +}