You are here

public function WorkbenchAccessTokens::getTokens in Workbench Access 8

Implements hook_tokens().

File

src/WorkbenchAccessTokens.php, line 105

Class

WorkbenchAccessTokens
Token handler for Workbench Access.

Namespace

Drupal\workbench_access

Code

public function getTokens($type, $tokens, array $data, array $options, BubbleableMetadata $bubbleable_metadata) {
  $replacements = [];

  // User tokens.
  if ($type === 'user' && !empty($data['user'])) {

    /** @var \Drupal\user\UserInterface $user */
    $user = $data['user'];
    foreach ($tokens as $name => $original) {
      switch ($name) {
        case 'workbench-access-sections':
          if ($sections = $this
            ->getUserSectionNames($user, $bubbleable_metadata)) {
            if (function_exists('token_render_array')) {
              $replacements[$original] = token_render_array($sections, $options);
            }
            else {
              $replacements[$original] = implode(', ', $sections);
            }
          }
          break;
      }
    }

    // Chained token relationships.
    if ($section_tokens = $this->tokenService
      ->findWithPrefix($tokens, 'workbench-access-sections')) {
      if ($sections = $this
        ->getUserSectionNames($user, $bubbleable_metadata)) {
        $replacements += $this->tokenService
          ->generate('array', $section_tokens, [
          'array' => $sections,
        ], $options, $bubbleable_metadata);
      }
    }
  }

  // Node tokens.
  if ($type === 'node' && !empty($data['node'])) {

    /** @var \Drupal\node\NodeInterface $node */
    $node = $data['node'];
    foreach ($tokens as $name => $original) {
      switch ($name) {
        case 'workbench-access-sections':
          if ($sections = $this
            ->getNodeSectionNames($node, $bubbleable_metadata)) {
            if (function_exists('token_render_array')) {
              $replacements[$original] = token_render_array($sections, $options);
            }
            else {
              $replacements[$original] = implode(', ', $sections);
            }
          }
          break;
      }
    }

    // Chained token relationships.
    if ($section_tokens = $this->tokenService
      ->findWithPrefix($tokens, 'workbench-access-sections')) {
      if ($sections = $this
        ->getNodeSectionNames($node, $bubbleable_metadata)) {
        $replacements += $this->tokenService
          ->generate('array', $section_tokens, [
          'array' => $sections,
        ], $options, $bubbleable_metadata);
      }
    }
  }
  return $replacements;
}