You are here

final class ExampleTokenEventSubscriber in Hook Event Dispatcher 8

Class ExampleTokenEventSubscriber.

Hierarchy

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

Expanded class hierarchy of ExampleTokenEventSubscriber

File

src/Example/ExampleTokenEventSubscriber.php, line 15

Namespace

Drupal\hook_event_dispatcher\Example
View source
final class ExampleTokenEventSubscriber implements EventSubscriberInterface {

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

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

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

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

  /**
   * Replace tokens.
   *
   * @param \Drupal\hook_event_dispatcher\Event\Token\TokensReplacementEvent $event
   *   The token replacement event.
   */
  public function tokenReplacement(TokensReplacementEvent $event) {
    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 Returns an array of event names this subscriber wants to listen to.
ExampleTokenEventSubscriber::tokenInfo public function Provides new token types and tokens.
ExampleTokenEventSubscriber::tokenReplacement public function Replace tokens.