You are here

rac_pa.module in Role Access Control 8

Module providing role base access for paragraphs.

File

contrib/rac_pa/rac_pa.module
View source
<?php

/**
 * @file
 * Module providing role base access for paragraphs.
 */
use Drupal\paragraphs\ParagraphInterface;
use Drupal\Core\Session\AccountInterface;

/**
 * Implements hook_paragraphs_access_grants().
 */
function rac_pa_paragraphs_access_grants($op, AccountInterface $account) {
  $grants = [];

  // With RAC, update permission should also grant view.
  if ($op === 'view' && ($g = rac_pa_paragraphs_access_grants('update', $account))) {
    $grants = $g;
  }
  $access = $op === 'view' ? 1 : 2;
  $userRoles = _rac_get_account_roles($op, $account);
  foreach ($userRoles as $role) {
    $grants["rac_" . $role
      ->id()][] = $access;
  }
  if (count($grants)) {
    return $grants;
  }
}

/**
 * Implements hook_paragraph_access_records().
 */
function rac_pa_paragraphs_access_records(ParagraphInterface $paragraph) {
  $entityRoles = _rac_get_entity_reference_roles($paragraph);
  if (count($entityRoles)) {

    // If we're here, the node has roles associated with it which restrict
    // access to the node.
    $grants = [];
    $roles = user_roles();
    foreach ($entityRoles as $role) {
      if (!isset($roles[$role])) {
        continue;
      }
      $grant = [
        'realm' => "rac_" . $roles[$role]
          ->id(),
        'gid' => 1,
        'grant_view' => 1,
        'grant_update' => 0,
        'grant_delete' => 0,
        'priority' => 0,
      ];
      $grant2 = [
        'realm' => "rac_" . $roles[$role]
          ->id(),
        'gid' => 2,
        'grant_view' => 1,
        'grant_update' => 1,
        'grant_delete' => 1,
        'priority' => 0,
      ];
      $grants[] = $grant;
      $grants[] = $grant2;
    }
    return $grants;
  }
}

/**
 * Implements hook_paragraph_access_restriction_message_alter().
 */
function rac_pa_paragraphs_access_restriction_message_alter(ParagraphInterface $paragraph, $op, &$message) {
  $entityRoles = _rac_get_entity_reference_roles($paragraph);
  if (count($entityRoles)) {

    // If entity has roles, then update text to reflex them.
    if (count($entityRoles) > 1) {

      // If there are multiple roles, construct proper english message.
      $last = array_pop($entityRoles);
      $list = implode(", ", $entityRoles) . " or " . $last;
      $message["#markup"] = "Users with the roles " . $list . " may edit this item.";
    }
    elseif (count($entityRoles) > 0) {
      $message["#markup"] = "Users with the role " . $entityRoles[0] . " may edit this item.";
    }
  }
}

Functions

Namesort descending Description
rac_pa_paragraphs_access_grants Implements hook_paragraphs_access_grants().
rac_pa_paragraphs_access_records Implements hook_paragraph_access_records().
rac_pa_paragraphs_access_restriction_message_alter Implements hook_paragraph_access_restriction_message_alter().