You are here

final class ExampleTokenEventSubscriber in Hook Event Dispatcher 3.x

Same name and namespace in other branches
  1. 8.2 examples/ExampleTokenEventSubscriber.php \Drupal\hook_event_dispatcher\ExampleTokenEventSubscriber

Class ExampleTokenEventSubscriber.

Don't forget to define your class as a service and tag it as an "event_subscriber":

services: hook_event_dispatcher.example_token_subscribers: class: Drupal\hook_event_dispatcher\ExampleTokenEventSubscribers tags:

  • { name: event_subscriber }

Hierarchy

  • class \Drupal\hook_event_dispatcher\ExampleTokenEventSubscriber implements \Symfony\Component\EventDispatcher\EventSubscriberInterface

Expanded class hierarchy of ExampleTokenEventSubscriber

File

examples/ExampleTokenEventSubscriber.php, line 24

Namespace

Drupal\hook_event_dispatcher
View source
final class ExampleTokenEventSubscriber implements EventSubscriberInterface {

  /**
   * {@inheritdoc}
   */
  public static function getSubscribedEvents() : array {
    return [
      HookEventDispatcherInterface::TOKEN_REPLACEMENT => 'tokenReplacement',
      HookEventDispatcherInterface::TOKEN_INFO => 'tokenInfo',
    ];
  }

  /**
   * Provides new token types and tokens.
   *
   * @param \Drupal\core_event_dispatcher\Event\Token\TokensInfoEvent $event
   *   The token info event.
   *
   * @throws \UnexpectedValueException
   */
  public function tokenInfo(TokensInfoEvent $event) : void {

    // The node type already exists, but it's just an example how to add a type.
    $type = TokenType::create('node', 'Node')
      ->setDescription('Node tokens')
      ->setNeedsData('node');
    $event
      ->addTokenType($type);

    // Add node token.
    $name = new TranslatableMarkup('Serialized string of the node');
    $token = Token::create('node', 'serialized', $name)
      ->setDescription('Node serialized');
    $event
      ->addToken($token);
  }

  /**
   * Replace tokens.
   *
   * @param \Drupal\core_event_dispatcher\Event\Token\TokensReplacementEvent $event
   *   The token replacement event.
   *
   * @throws \UnexpectedValueException
   */
  public function tokenReplacement(TokensReplacementEvent $event) : void {
    if ($event
      ->forToken('node', 'serialized')) {
      $event
        ->setReplacementValue('node', 'serialized', serialize($event
        ->getData('node')));
    }
  }

}

Members

Namesort descending Modifiers Type Description Overrides
ExampleTokenEventSubscriber::getSubscribedEvents public static function
ExampleTokenEventSubscriber::tokenInfo public function Provides new token types and tokens.
ExampleTokenEventSubscriber::tokenReplacement public function Replace tokens.