BlockFieldTestAuthenticatedBlock.php in Block field 8
File
tests/modules/block_field_test/src/Plugin/Block/BlockFieldTestAuthenticatedBlock.php
View source
<?php
namespace Drupal\block_field_test\Plugin\Block;
use Drupal\Core\Access\AccessResult;
use Drupal\Core\Block\BlockBase;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Session\AccountProxyInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
class BlockFieldTestAuthenticatedBlock extends BlockBase implements ContainerFactoryPluginInterface {
protected $currentUser;
public function __construct(array $configuration, $plugin_id, $plugin_definition, AccountProxyInterface $current_user) {
parent::__construct($configuration, $plugin_id, $plugin_definition);
$this->currentUser = $current_user;
}
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static($configuration, $plugin_id, $plugin_definition, $container
->get('current_user'));
}
public function build() {
return [
'#theme' => 'username',
'#account' => $this->currentUser
->getAccount(),
'#prefix' => '<p>',
'#suffix' => '</p>',
];
}
protected function blockAccess(AccountInterface $account) {
return AccessResult::allowedIf($account
->isAuthenticated());
}
public function getCacheContexts() {
return [
'user',
];
}
public function getCacheTags() {
return [
'user:' . $this->currentUser
->id(),
];
}
}