computed_field-8.x-2.x-dev/tests/modules/test_computed_field_plugins/src/Plugin/ComputedField/TestCurrentUser.php
tests/modules/test_computed_field_plugins/src/Plugin/ComputedField/TestCurrentUser.php
<?php
namespace Drupal\test_computed_field_plugins\Plugin\ComputedField;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\computed_field\Attribute\ComputedField;
use Drupal\computed_field\Field\ComputedFieldDefinitionWithValuePluginInterface;
use Drupal\computed_field\Plugin\ComputedField\ComputedFieldBase;
use Drupal\computed_field\Plugin\ComputedField\SingleValueTrait;
use Drupal\Core\Cache\CacheableMetadata;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\Core\Session\AccountProxyInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Computed field which shows the current user's name.
*/
#[ComputedField(
id: 'test_current_user',
label: new TranslatableMarkup('Test current user'),
field_type: 'string',
)]
class TestCurrentUser extends ComputedFieldBase implements ContainerFactoryPluginInterface {
/**
* The current active user.
*
* @var \Drupal\Core\Session\AccountProxyInterface
*/
protected $currentUser;
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static(
$configuration,
$plugin_id,
$plugin_definition,
$container->get('current_user'),
);
}
/**
* Creates a TestCurrentUser instance.
*
* @param array $configuration
* A configuration array containing information about the plugin instance.
* @param string $plugin_id
* The plugin_id for the plugin instance.
* @param mixed $plugin_definition
* The plugin implementation definition.
* @param \Drupal\Core\Session\AccountProxyInterface $current_user
* The current active user.
*/
public function __construct(
array $configuration,
$plugin_id,
$plugin_definition,
AccountProxyInterface $current_user
) {
parent::__construct($configuration, $plugin_id, $plugin_definition);
$this->currentUser = $current_user;
}
use SingleValueTrait;
/**
* {@inheritdoc}
*/
public function singleComputeValue(EntityInterface $host_entity, ComputedFieldDefinitionWithValuePluginInterface $computed_field_definition): mixed {
return \Drupal::currentUser()->getDisplayName();
}
/**
* {@inheritdoc}
*/
public function getCacheability(EntityInterface $host_entity, ComputedFieldDefinitionWithValuePluginInterface $computed_field_definition): ?CacheableMetadata {
$cacheability = new CacheableMetadata();
$cacheability->setCacheContexts(['user']);
$cacheability->setCacheTags(['user:' . \Drupal::currentUser()->id()]);
return $cacheability;
}
}
