You are here

public function Js::getToken in JS Callback Handler 8.3

Generate a unique token for JS callbacks.

Parameters

string $callback: A callback object to retrieve the token for.

Return value

string|array If $module and $callback are provided the unique token belonging to it is returned, otherwise all current tokens set are returned.

1 call to Js::getToken()
Js::preRenderJsCallback in src/Js.php
Pre-render callback for #js_callback and #js_get properties.

File

src/Js.php, line 505

Class

Js
JS Callback Handler service.

Namespace

Drupal\js

Code

public function getToken($callback = NULL) {

  // Use the advanced drupal_static() pattern, since this has the potential to
  // be called quite often on a single page request.
  static $drupal_static_fast;
  if (!isset($drupal_static_fast)) {
    $drupal_static_fast['tokens'] =& drupal_static(__METHOD__, []);
  }
  $tokens =& $drupal_static_fast['tokens'];

  // Return a specific token for a module callback.
  if ($callback) {

    // Only authenticated users should be allowed to generate tokens.
    if (!\Drupal::currentUser()
      ->isAnonymous()) {
      return $tokens[$callback] = $this->tokenGenerator
        ->get("js.callback:{$callback}");
    }
    else {
      return FALSE;
    }
  }

  // Otherwise return all tokens.
  return $tokens;
}