You are here

function testing_example_node_access in Examples for Developers 8

Same name and namespace in other branches
  1. 3.x modules/testing_example/testing_example.module \testing_example_node_access()

Implements hook_node_access().

Demonstrates a bug that we'll find in our test.

Related topics

File

testing_example/testing_example.module, line 31
Module file for testing_example.

Code

function testing_example_node_access(NodeInterface $node, $op, AccountInterface $account) {

  // Gather the node type.
  $type = $node
    ->getType();

  // If it's not a testing_example node, or if it's not operations we care
  // about, then just ignore.
  if ($type != 'testing_example' || $op != 'update' && $op != 'delete') {
    return AccessResult::neutral();
  }

  // This code has a BUG that we'll find in testing.
  //
  // This is the incorrect version we'll use to demonstrate test failure.
  // The correct version should have ($op == 'update' || $op == 'delete').
  // The author had mistakenly always tested with User 1 so it always
  // allowed access and the bug wasn't noticed!
  if ($op == 'delete' && ($account
    ->hasPermission('extra special edit any testing_example') && $account
    ->id() == $node
    ->getAuthorId())) {
    return AccessResult::allowed();
  }
  return AccessResult::forbidden();
}