knowledge-8.x-1.x-dev/src/Plugin/views/filter/KnowledgeLearners.php
src/Plugin/views/filter/KnowledgeLearners.php
<?php
namespace Drupal\knowledge\Plugin\views\filter;
use Drupal\Core\Entity\EntityStorageInterface;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\views\Plugin\views\display\DisplayPluginBase;
use Drupal\views\Plugin\views\filter\InOperator;
use Drupal\views\ViewExecutable;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Filters by given list of users.
*
* @ingroup views_filter_handlers
*
* @ViewsFilter("knowledge_learners")
*/
class KnowledgeLearners extends InOperator {
/**
* The user entity storage.
*
* @var \Drupal\Core\Entity\EntityStorageInterface
*/
protected $userStorage;
/**
* The current route match.
*
* @var \Drupal\Core\Routing\RouteMatchInterface
*/
protected RouteMatchInterface $routeMatch;
/**
* Constructs a knowledge_learners filter.
*
* @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\Entity\EntityStorageInterface $user_storage
* The entity storage class.
* @param \Drupal\Core\Routing\RouteMatchInterface $route_match
* Current route match service.
*/
public function __construct(array $configuration, $plugin_id, $plugin_definition, EntityStorageInterface $user_storage, RouteMatchInterface $route_match) {
parent::__construct($configuration, $plugin_id, $plugin_definition);
$this->userStorage = $user_storage;
$this->routeMatch = $route_match;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static(
$configuration,
$plugin_id,
$plugin_definition,
$container->get('entity_type.manager')->getStorage('user'),
$container->get('current_route_match')
);
}
/**
* {@inheritdoc}
*/
public function init(ViewExecutable $view, DisplayPluginBase $display, ?array &$options = NULL) {
parent::init($view, $display, $options);
$this->valueTitle = $this->t('Learners');
$this->definition['options callback'] = [$this, 'generateOptions'];
}
/**
* {@inheritdoc}
*/
public function generateOptions() {
$coach_uid = $this->routeMatch->getParameter('user');
$query = $this->userStorage->getQuery();
$user_ids = $query
->condition('knowledge_coach', $coach_uid)
->sort('field_fullname')
->accessCheck(FALSE)
->execute();
$users = $this->userStorage->loadMultiple($user_ids);
$options = [];
foreach ($users as $user) {
$options[$user->id()] = $user->label();
}
return $options;
}
}
