summaryrefslogtreecommitdiffstats
path: root/core/modules/block/tests/modules/block_test/src/Plugin/Block/TestContextAwareBlock.php
blob: 70afd54ceafb3c238588f2384c81cf0e40541ec5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
<?php

namespace Drupal\block_test\Plugin\Block;

use Drupal\Core\Block\BlockBase;
use Drupal\Core\Messenger\MessengerTrait;
use Drupal\Core\Session\AccountInterface;
use Drupal\user\UserInterface;

/**
 * Provides a context-aware block.
 *
 * @Block(
 *   id = "test_context_aware",
 *   admin_label = @Translation("Test context-aware block"),
 *   context = {
 *     "user" = @ContextDefinition("entity:user", required = FALSE)
 *   }
 * )
 */
class TestContextAwareBlock extends BlockBase {

  use MessengerTrait;

  /**
   * {@inheritdoc}
   */
  public function build() {
    /** @var $user \Drupal\user\UserInterface */
    $user = $this->getContextValue('user');
    return [
      '#prefix' => '<div id="' . $this->getPluginId() . '--username">',
      '#suffix' => '</div>',
      '#markup' => $user ? $user->getUsername() : 'No context mapping selected.' ,
    ];
  }

  /**
   * {@inheritdoc}
   */
  protected function blockAccess(AccountInterface $account) {
    if ($this->getContextValue('user') instanceof UserInterface) {
      $this->messenger()->addStatus('User context found.');
    }

    return parent::blockAccess($account);
  }

}