51f60b473af5f94ec447fdc8b5534dbaec09e6c6
[yaffs-website] / web / core / modules / block / tests / modules / block_test / src / Plugin / Block / TestContextAwareBlock.php
1 <?php
2
3 namespace Drupal\block_test\Plugin\Block;
4
5 use Drupal\Core\Block\BlockBase;
6 use Drupal\Core\Session\AccountInterface;
7 use Drupal\user\UserInterface;
8
9 /**
10  * Provides a context-aware block.
11  *
12  * @Block(
13  *   id = "test_context_aware",
14  *   admin_label = @Translation("Test context-aware block"),
15  *   context = {
16  *     "user" = @ContextDefinition("entity:user", required = FALSE)
17  *   }
18  * )
19  */
20 class TestContextAwareBlock extends BlockBase {
21
22   /**
23    * {@inheritdoc}
24    */
25   public function build() {
26     /** @var $user \Drupal\user\UserInterface */
27     $user = $this->getContextValue('user');
28     return [
29       '#prefix' => '<div id="' . $this->getPluginId() . '--username">',
30       '#suffix' => '</div>',
31       '#markup' => $user ? $user->getUsername() : 'No context mapping selected.' ,
32     ];
33   }
34
35   /**
36    * {@inheritdoc}
37    */
38   protected function blockAccess(AccountInterface $account) {
39     if ($this->getContextValue('user') instanceof UserInterface) {
40       $this->messenger()->addStatus('User context found.');
41     }
42
43     return parent::blockAccess($account);
44   }
45
46 }