final class ExampleTokenEventSubscriber in Hook Event Dispatcher 8.2
Same name and namespace in other branches
- 3.x 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_dispatcherView 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
Name | Modifiers | Type | Description | Overrides |
---|---|---|---|---|
ExampleTokenEventSubscriber:: |
public static | function | Returns an array of event names this subscriber wants to listen to. | |
ExampleTokenEventSubscriber:: |
public | function | Provides new token types and tokens. | |
ExampleTokenEventSubscriber:: |
public | function | Replace tokens. |