UserBlock.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. <?php
  2. namespace Drupal\materio_user\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. $build['#cache'] = [
  47. 'max-age' => 0,
  48. ];
  49. // dpm($this->user);
  50. if($this->user->id()){
  51. $user_url = Url::fromRoute('entity.user.canonical', ['user' => $this->user->id()]);
  52. $build['user-link'] = array(
  53. '#title' => $this->user->getEmail(),
  54. '#type' => 'link',
  55. '#url' => $user_url,
  56. '#options'=>array(
  57. 'attributes' => array(
  58. 'data-drupal-link-system-path' => $user_url->getInternalPath(),
  59. 'alt' => t('User account'),
  60. )
  61. )
  62. );
  63. $logout_url = Url::fromRoute('user.logout');
  64. $build['user-logout'] = array(
  65. '#title' => t('Logout'),
  66. '#type' => 'link',
  67. '#url' => $logout_url,
  68. '#options'=>array(
  69. 'attributes' => array(
  70. 'data-drupal-link-system-path' => $logout_url->getInternalPath(),
  71. 'alt' => t('Logout'),
  72. )
  73. )
  74. );
  75. }
  76. return $build;
  77. }
  78. }