You are here

function block_content_permissions_views_query_alter in Block Content Permissions 8

Implements hook_views_query_alter().

File

./block_content_permissions.module, line 87
Block content permissions module.

Code

function block_content_permissions_views_query_alter(ViewExecutable $view, QueryPluginBase $query) {

  // If user cannot "view restricted block content", filter block_content view
  // to only include block content the user can create, edit or delete.
  if ($view
    ->id() == 'block_content') {
    $account = $view
      ->getUser();

    // Check if user cannot view restricted block content.
    if (!$account
      ->hasPermission('view restricted block content')) {

      // Get block content types.
      $allowedBlockContentTypes = \Drupal::entityQuery('block_content_type')
        ->execute();

      // Remove block content types based on user's permissions.
      foreach ($allowedBlockContentTypes as $type) {
        $edit = "update any {$type} block content";
        $delete = "delete any {$type} block content";
        $create = "create {$type} block content";
        if (!($account
          ->hasPermission($edit) || $account
          ->hasPermission($delete) || $account
          ->hasPermission($create))) {
          unset($allowedBlockContentTypes[$type]);
        }
      }

      // Restrict query to allowed block content types.
      if (!empty($allowedBlockContentTypes)) {
        $query
          ->addWhere('1', 'type', $allowedBlockContentTypes, 'IN');
      }
      else {
        $query
          ->addWhere('1', 'type', '', '=');
      }

      // Restrict exposed "type" field options to allowed block content types.
      if (!empty($view->exposed_widgets['type']['#options'])) {
        foreach ($view->exposed_widgets['type']['#options'] as $key => $value) {
          if ($key != 'All' && !in_array($key, $allowedBlockContentTypes)) {
            unset($view->exposed_widgets['type']['#options'][$key]);
          }
        }
      }
    }
  }
}