You are here

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;

/**
 * Provides a 'Block field test authenticated' block.
 *
 * @Block(
 *   id = "block_field_test_authenticated",
 *   admin_label = @Translation("You are logged in as..."),
 *   category = @Translation("Block field test")
 * )
 */
class BlockFieldTestAuthenticatedBlock extends BlockBase implements ContainerFactoryPluginInterface {

  /**
   * Drupal\Core\Session\AccountProxy definition.
   *
   * @var \Drupal\Core\Session\AccountProxy
   */
  protected $currentUser;

  /**
   * {@inheritdoc}
   */
  public function __construct(array $configuration, $plugin_id, $plugin_definition, AccountProxyInterface $current_user) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);
    $this->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() {
    return [
      '#theme' => 'username',
      '#account' => $this->currentUser
        ->getAccount(),
      '#prefix' => '<p>',
      '#suffix' => '</p>',
    ];
  }

  /**
   * {@inheritdoc}
   */
  protected function blockAccess(AccountInterface $account) {
    return AccessResult::allowedIf($account
      ->isAuthenticated());
  }

  /**
   * {@inheritdoc}
   */
  public function getCacheContexts() {
    return [
      'user',
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function getCacheTags() {
    return [
      'user:' . $this->currentUser
        ->id(),
    ];
  }

}

Classes

Namesort descending Description
BlockFieldTestAuthenticatedBlock Provides a 'Block field test authenticated' block.