|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace Drupal\graphql\Plugin\GraphQL\DataProducer\User; |
| 4 | + |
| 5 | +use Drupal\Core\Plugin\ContainerFactoryPluginInterface; |
| 6 | +use Drupal\Core\Session\AccountInterface; |
| 7 | +use Drupal\graphql\GraphQL\Execution\FieldContext; |
| 8 | +use Drupal\graphql\Plugin\GraphQL\DataProducer\DataProducerPluginBase; |
| 9 | +use Symfony\Component\DependencyInjection\ContainerInterface; |
| 10 | + |
| 11 | +/** |
| 12 | + * Gets the current user. |
| 13 | + * |
| 14 | + * @DataProducer( |
| 15 | + * id = "current_user", |
| 16 | + * name = @Translation("Current user"), |
| 17 | + * description = @Translation("Current logged in user."), |
| 18 | + * produces = @ContextDefinition("any", |
| 19 | + * label = @Translation("Current user") |
| 20 | + * ) |
| 21 | + * ) |
| 22 | + */ |
| 23 | +class CurrentUser extends DataProducerPluginBase implements ContainerFactoryPluginInterface { |
| 24 | + |
| 25 | + /** |
| 26 | + * The current user. |
| 27 | + * |
| 28 | + * @var \Drupal\Core\Session\AccountInterface |
| 29 | + */ |
| 30 | + protected $currentUser; |
| 31 | + |
| 32 | + /** |
| 33 | + * {@inheritdoc} |
| 34 | + */ |
| 35 | + public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) { |
| 36 | + return new static( |
| 37 | + $configuration, |
| 38 | + $plugin_id, |
| 39 | + $plugin_definition, |
| 40 | + $container->get('current_user') |
| 41 | + ); |
| 42 | + } |
| 43 | + |
| 44 | + /** |
| 45 | + * CurrentUser constructor. |
| 46 | + * |
| 47 | + * @param array $configuration |
| 48 | + * A configuration array containing information about the plugin instance. |
| 49 | + * @param string $plugin_id |
| 50 | + * The plugin_id for the plugin instance. |
| 51 | + * @param array $plugin_definition |
| 52 | + * The plugin implementation definition. |
| 53 | + * @param \Drupal\Core\Session\AccountInterface $current_user |
| 54 | + * The current user. |
| 55 | + */ |
| 56 | + public function __construct(array $configuration, string $plugin_id, array $plugin_definition, AccountInterface $current_user) { |
| 57 | + parent::__construct($configuration, $plugin_id, $plugin_definition); |
| 58 | + $this->currentUser = $current_user; |
| 59 | + } |
| 60 | + |
| 61 | + /** |
| 62 | + * Returns current user. |
| 63 | + * |
| 64 | + * @param \Drupal\graphql\GraphQL\Execution\FieldContext $field_context |
| 65 | + * Field context. |
| 66 | + * |
| 67 | + * @return \Drupal\Core\Session\AccountInterface |
| 68 | + * The current user. |
| 69 | + */ |
| 70 | + public function resolve(FieldContext $field_context): AccountInterface { |
| 71 | + // Response must be cached based on current user as a cache context, |
| 72 | + // otherwise a new user would became a previous user. |
| 73 | + $field_context->addCacheableDependency($this->currentUser); |
| 74 | + return $this->currentUser; |
| 75 | + } |
| 76 | + |
| 77 | +} |
0 commit comments