You are here

function node_view_permissions_node_grants in Node View Permissions 8

Same name and namespace in other branches
  1. 7 node_view_permissions.module \node_view_permissions_node_grants()

Implements hook_node_grants().

File

./node_view_permissions.module, line 113
The node view permission module.

Code

function node_view_permissions_node_grants(AccountInterface $account, $op) {
  $grants = [];
  if ($op == 'view') {

    // Get current langcode.
    $node = \Drupal::routeMatch()
      ->getParameter('node');
    $language_manager = \Drupal::languageManager();
    $languages = \Drupal::languageManager()
      ->getLanguages();
    foreach ($languages as $langcode => $language) {
      foreach (NodeType::loadMultiple() as $type) {
        $type_id = $type
          ->id();
        if ($account
          ->hasPermission("view any {$type_id} content")) {
          $grants["view_any_{$type_id}_content"] = [
            1,
          ];

          // Also set grants for the current language.
          $grants["view_any_{$type_id}_{$langcode}_content"] = [
            1,
          ];
        }
        if ($account
          ->hasPermission("view own {$type_id} content")) {
          $grants["view_own_{$type_id}_content"] = [
            $account
              ->id(),
          ];

          // Also set grants for the current language.
          $grants["view_own_{$type_id}_{$langcode}_content"] = [
            $account
              ->id(),
          ];
        }

        // Add integration for Content Moderation.
        if ($account
          ->hasPermission("view any unpublished content") && $account
          ->hasPermission("view any {$type_id} content")) {
          $grants["view_any_unpublished_{$type_id}_content"] = [
            1,
          ];

          // Also set grants for the current language.
          $grants["view_any_unpublished_{$type_id}_{$langcode}_content"] = [
            1,
          ];
        }
        if ($account
          ->hasPermission("view own unpublished content") && $account
          ->hasPermission("view own {$type_id} content")) {
          $grants["view_own_unpublished_{$type_id}_content"] = [
            $account
              ->id(),
          ];

          // Also set grants for the current language.
          $grants["view_own_unpublished_{$type_id}_{$langcode}_content"] = [
            $account
              ->id(),
          ];
        }
      }
    }
  }
  return $grants;
}