You are here

function opigno_class_views_query_alter in Opigno class 8

Same name and namespace in other branches
  1. 3.x opigno_class.module \opigno_class_views_query_alter()

Implements hook_views_query_alter().

File

./opigno_class.module, line 105
Contains opigno_class.module.

Code

function opigno_class_views_query_alter(ViewExecutable $view, QueryPluginBase $query) {
  $user = \Drupal::currentUser();

  // Show classes where user has role 'opigno_class-class_manager'.
  if ($view
    ->id() === 'opigno_classes' && !$user
    ->hasPermission('manage group members in any group')) {
    $uid = $user
      ->id();
    $connection = Database::getConnection();
    $query_c = $connection
      ->select('group_content_field_data', 'g_c_f_d')
      ->fields('g_c_f_d', [
      'gid',
    ]);
    $query_c
      ->leftJoin('group_content__group_roles', 'g_c_g_r', 'g_c_f_d.id = g_c_g_r.entity_id');
    $query_c
      ->condition('g_c_g_r.group_roles_target_id', 'opigno_class-class_manager');
    $query_c
      ->condition('g_c_f_d.entity_id', $uid);
    $query_c
      ->condition('g_c_f_d.type', 'opigno_class-group_membership');
    $classes = $query_c
      ->execute()
      ->fetchAllAssoc('gid');
    $class_ids = [];
    foreach ($classes as $class) {
      $class_ids[] = $class->gid;
    }
    if (!empty($class_ids)) {
      $group_and = $query
        ->setWhereGroup('AND');
      $query
        ->addWhere($group_and, 'groups_field_data.id', $class_ids, 'IN');
    }
    else {
      $group_and = $query
        ->setWhereGroup('AND');
      $query
        ->addWhere($group_and, 'groups_field_data.id', -1);
    }
  }
}