TestContextAwareBlock.php in Drupal 8
File
core/modules/block/tests/modules/block_test/src/Plugin/Block/TestContextAwareBlock.php
View source
<?php
namespace Drupal\block_test\Plugin\Block;
use Drupal\Core\Block\BlockBase;
use Drupal\Core\Session\AccountInterface;
use Drupal\user\UserInterface;
class TestContextAwareBlock extends BlockBase {
public function build() {
$user = $this
->getContextValue('user');
return [
'#prefix' => '<div id="' . $this
->getPluginId() . '--username">',
'#suffix' => '</div>',
'#markup' => $user ? $user
->getAccountName() : 'No context mapping selected.',
];
}
protected function blockAccess(AccountInterface $account) {
if ($this
->getContextValue('user') instanceof UserInterface) {
$this
->messenger()
->addStatus('User context found.');
}
return parent::blockAccess($account);
}
}