UserBlock.php 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. <?php
  2. namespace Drupal\user_block\Plugin\Block;
  3. use Drupal\Core\Session\AccountProxy;
  4. use Drupal\Core\Session\AccountProxyInterface;
  5. use Drupal\Core\Block\BlockBase;
  6. use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
  7. use Symfony\Component\DependencyInjection\ContainerInterface;
  8. use Drupal\Core\Url;
  9. /**
  10. * Provides a 'UserBlock' block.
  11. *
  12. * @Block(
  13. * id = "user_block",
  14. * admin_label = @Translation("User block"),
  15. * )
  16. */
  17. class UserBlock extends BlockBase implements ContainerFactoryPluginInterface{
  18. protected $user;
  19. /**
  20. * {@inheritdoc}
  21. */
  22. public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
  23. // Instantiates this form class.
  24. return new static(
  25. $configuration,
  26. $plugin_id,
  27. $plugin_definition,
  28. $container->get('current_user')
  29. );
  30. }
  31. /**
  32. * @param array $configuration
  33. * @param string $plugin_id
  34. * @param mixed $plugin_definition
  35. * @param \Drupal\Core\Session\AccountProxyInterface $account
  36. */
  37. public function __construct(array $configuration, $plugin_id, $plugin_definition, AccountProxyInterface $account) {
  38. parent::__construct($configuration, $plugin_id, $plugin_definition);
  39. $this->user = $account;
  40. }
  41. /**
  42. * {@inheritdoc}
  43. */
  44. public function build() {
  45. $build = [];
  46. // dpm($this->user);
  47. if($this->user->id()){
  48. $user_url = Url::fromRoute('entity.user.canonical', ['user' => $this->user->id()]);
  49. $build['user-link'] = array(
  50. '#title' => $this->user->getEmail(),
  51. '#type' => 'link',
  52. '#url' => $user_url,
  53. '#options'=>array(
  54. 'attributes' => array(
  55. 'data-drupal-link-system-path' => $user_url->getInternalPath(),
  56. 'alt' => t('User account'),
  57. )
  58. )
  59. );
  60. $logout_url = Url::fromRoute('user.logout');
  61. $build['user-logout'] = array(
  62. '#title' => t('Logout'),
  63. '#type' => 'link',
  64. '#url' => $logout_url,
  65. '#options'=>array(
  66. 'attributes' => array(
  67. 'data-drupal-link-system-path' => $logout_url->getInternalPath(),
  68. 'alt' => t('Logout'),
  69. )
  70. )
  71. );
  72. }
  73. return $build;
  74. }
  75. }