improvements-2.x-dev/modules/improvements_views/src/Plugin/views/sort/IsCurrentUser.php
modules/improvements_views/src/Plugin/views/sort/IsCurrentUser.php
<?php namespace Drupal\improvements_views\Plugin\views\sort; use Drupal\Core\Cache\Cache; use Drupal\Core\Session\AccountProxyInterface; use Drupal\views\Attribute\ViewsSort; use Drupal\views\Plugin\views\sort\SortPluginBase; use Symfony\Component\DependencyInjection\ContainerInterface; #[ViewsSort('is_current_user')] class IsCurrentUser extends SortPluginBase { protected AccountProxyInterface $currentUser; /** * Class constructor. */ public function __construct(array $configuration, $plugin_id, $plugin_definition, AccountProxyInterface $current_user) { parent::__construct($configuration, $plugin_id, $plugin_definition); $this->currentUser = $current_user; } /** * {@inheritdoc} */ public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition): static { return new static( $configuration, $plugin_id, $plugin_definition, $container->get('current_user'), ); } /** * {@inheritDoc} */ public function query(): void { if ($current_user_id = $this->currentUser->id()) { $this->ensureMyTable(); $query = $this->query; /** @var \Drupal\views\Plugin\views\query\Sql $query */ $sort_alias = $this->realField . '_is_current_user'; $query->addOrderBy(NULL, "IF ($this->tableAlias.$this->realField = $current_user_id, 1, 0)", $this->options['order'], $sort_alias); } } /** * {@inheritdoc} */ public function getCacheContexts(): array { return Cache::mergeContexts(parent::getCacheContexts(), ['user']); } }