You are here

function vapn_node_access in View access per node 8

Implements hook_node_access().

File

./vapn.module, line 94
Contains vapn.module.

Code

function vapn_node_access(\Drupal\node\NodeInterface $node, $op, \Drupal\Core\Session\AccountInterface $account) {

  // Only concerned with viewing.
  if ($op != 'view') {

    // Ignore if any other op.
    return AccessResult::neutral();
  }

  // Make sure there's a node id.
  if (empty($node->nid)) {

    // Should never happen but ignore if no nid.
    return AccessResult::neutral();
  }
  $configEnabled = \Drupal::config('vapn.vapnconfig')
    ->get('vapn_node_list');

  // Check if it's a valid VAPN content type.
  if (empty($node
    ->getType()) || !in_array($node
    ->getType(), $configEnabled, TRUE)) {

    // Not a VAPN node type, we don't care.
    return AccessResult::neutral();
  }

  // Get the records for this node.
  $records = \Drupal::database()
    ->select('vapn')
    ->fields('vapn', array(
    'rid',
  ))
    ->condition('nid', $node
    ->id())
    ->execute();

  // Check that there is a record for this node.
  if (!($allowed_roles = $records
    ->fetchCol())) {

    // No record.
    return AccessResult::neutral();
  }

  // Make sure the user has one of the allowed roles.
  $ret = count(array_intersect($allowed_roles, $account
    ->getRoles())) ? AccessResult::allowed() : AccessResult::forbidden();
  return $ret;
}