DomainTokenBlock.php 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. <?php
  2. namespace Drupal\domain\Plugin\Block;
  3. use Drupal\Core\Access\AccessResult;
  4. use Drupal\Core\Session\AccountInterface;
  5. use Drupal\domain\DomainInterface;
  6. /**
  7. * Provides a token information block for a domain request.
  8. *
  9. * @Block(
  10. * id = "domain_token_block",
  11. * admin_label = @Translation("Domain token information")
  12. * )
  13. */
  14. class DomainTokenBlock extends DomainBlockBase {
  15. /**
  16. * Overrides \Drupal\block\BlockBase::access().
  17. */
  18. public function access(AccountInterface $account, $return_as_object = FALSE) {
  19. $access = AccessResult::allowedIfHasPermissions($account, ['administer domains', 'view domain information'], 'OR');
  20. return $return_as_object ? $access : $access->isAllowed();
  21. }
  22. /**
  23. * Build the output.
  24. */
  25. public function build() {
  26. /** @var \Drupal\domain\DomainInterface $domain */
  27. $domain = \Drupal::service('domain.negotiator')->getActiveDomain();
  28. if (!$domain) {
  29. return [
  30. '#markup' => $this->t('No domain record could be loaded.'),
  31. ];
  32. }
  33. $header = [$this->t('Token'), $this->t('Value')];
  34. return [
  35. '#theme' => 'table',
  36. '#rows' => $this->renderTokens($domain),
  37. '#header' => $header,
  38. ];
  39. }
  40. /**
  41. * Generates available tokens for printing.
  42. *
  43. * @param \Drupal\domain\DomainInterface $domain
  44. * The active domain request.
  45. *
  46. * @return array
  47. * An array keyed by token name, with value of replacement value.
  48. */
  49. private function renderTokens(DomainInterface $domain) {
  50. $rows = [];
  51. $token = \Drupal::token();
  52. $tokens = $token->getInfo();
  53. // The 'domain' token is supported by core. The others by Token module,
  54. // so we cannot assume that Token module is present.
  55. $domain_tokens = ['domain', 'current-domain', 'default-domain'];
  56. foreach ($domain_tokens as $key) {
  57. if (isset($tokens['tokens'][$key])) {
  58. $data = [];
  59. // Pass domain data to the default handler.
  60. if ($key == 'domain') {
  61. $data['domain'] = $domain;
  62. }
  63. foreach ($tokens['tokens'][$key] as $name => $info) {
  64. $string = "[$key:$name]";
  65. $rows[] = [
  66. $string,
  67. $token->replace($string, $data),
  68. ];
  69. }
  70. }
  71. }
  72. return $rows;
  73. }
  74. }