ToolbarLinkBuilder.php 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. <?php
  2. namespace Drupal\user;
  3. use Drupal\Core\Session\AccountProxyInterface;
  4. use Drupal\Core\StringTranslation\StringTranslationTrait;
  5. use Drupal\Core\Url;
  6. /**
  7. * ToolbarLinkBuilder fills out the placeholders generated in user_toolbar().
  8. */
  9. class ToolbarLinkBuilder {
  10. use StringTranslationTrait;
  11. /**
  12. * The current user.
  13. *
  14. * @var \Drupal\Core\Session\AccountProxyInterface
  15. */
  16. protected $account;
  17. /**
  18. * ToolbarHandler constructor.
  19. *
  20. * @param \Drupal\Core\Session\AccountProxyInterface $account
  21. * The current user.
  22. */
  23. public function __construct(AccountProxyInterface $account) {
  24. $this->account = $account;
  25. }
  26. /**
  27. * Lazy builder callback for rendering toolbar links.
  28. *
  29. * @return array
  30. * A renderable array as expected by the renderer service.
  31. */
  32. public function renderToolbarLinks() {
  33. $links = [
  34. 'account' => [
  35. 'title' => $this->t('View profile'),
  36. 'url' => Url::fromRoute('user.page'),
  37. 'attributes' => [
  38. 'title' => $this->t('User account'),
  39. ],
  40. ],
  41. 'account_edit' => [
  42. 'title' => $this->t('Edit profile'),
  43. 'url' => Url::fromRoute('entity.user.edit_form', ['user' => $this->account->id()]),
  44. 'attributes' => [
  45. 'title' => $this->t('Edit user account'),
  46. ],
  47. ],
  48. 'logout' => [
  49. 'title' => $this->t('Log out'),
  50. 'url' => Url::fromRoute('user.logout'),
  51. ],
  52. ];
  53. $build = [
  54. '#theme' => 'links__toolbar_user',
  55. '#links' => $links,
  56. '#attributes' => [
  57. 'class' => ['toolbar-menu'],
  58. ],
  59. '#cache' => [
  60. 'contexts' => ['user'],
  61. ],
  62. ];
  63. return $build;
  64. }
  65. /**
  66. * Lazy builder callback for rendering the username.
  67. *
  68. * @return array
  69. * A renderable array as expected by the renderer service.
  70. */
  71. public function renderDisplayName() {
  72. return [
  73. '#markup' => $this->account->getDisplayName(),
  74. ];
  75. }
  76. }