component_library-1.0.x-dev/src/EventSubscriber/VariablesPlaceholderCurrentUser.php
src/EventSubscriber/VariablesPlaceholderCurrentUser.php
<?php
declare(strict_types=1);
namespace Drupal\component_library\EventSubscriber;
use Drupal\component_library\Event\AddVariablesPlaceholderEvent;
use Drupal\component_library\Event\ReplaceVariablesPlaceholderEvent;
use Drupal\Core\Session\AccountProxyInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
/**
* Override mode current user variable placeholders.
*/
final class VariablesPlaceholderCurrentUser implements EventSubscriberInterface {
private AccountProxyInterface $currentUser;
public function __construct(AccountProxyInterface $current_user) {
$this->currentUser = $current_user;
}
/**
* {@inheritdoc}
*/
public static function getSubscribedEvents(): array {
$events = [];
$events[AddVariablesPlaceholderEvent::class][] = ['onAddVariablesPlaceholder'];
$events[ReplaceVariablesPlaceholderEvent::class][] = ['onReplaceVariablesPlaceholderEvent'];
return $events;
}
public function onAddVariablesPlaceholder(AddVariablesPlaceholderEvent $event): void {
$item = $event->getItem();
if ($item instanceof AccountProxyInterface) {
$event->setPlaceholder([
'#override_mode' => [
'#type' => 'override_current_user',
],
]);
}
}
public function onReplaceVariablesPlaceholderEvent(ReplaceVariablesPlaceholderEvent $event): void {
$config = $event->getConfig();
if (isset($config['#type']) && $config['#type'] === 'current_user') {
$event->setReplacement($this->currentUser);
}
}
}
