You are here

testing_example.module in Examples for Developers 3.x

Module file for testing_example.

File

modules/testing_example/testing_example.module
View source
<?php

/**
 * @file
 * Module file for testing_example.
 */
use Drupal\Core\Access\AccessResult;
use Drupal\Core\Session\AccountInterface;
use Drupal\node\NodeInterface;

/**
 * @defgroup testing_example Example: Testing
 * @ingroup examples
 * @{
 * This example demonstrates Drupal 8 testing frameworks.
 *
 * This module creates a new node type called 'Testing Example Node Type,'
 * so that we can test it.
 *
 * This code was originally written to accompany the tutorial at
 * http://drupal.org/node/890654. That's a Drupal 7 example, but can still
 * teach you much.
 */

/**
 * Implements hook_node_access().
 *
 * Demonstrates a bug that we'll find in our test.
 */
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();
}

/**
 * @} End of "defgroup testing_example".
 */

Functions

Namesort descending Description
testing_example_node_access Implements hook_node_access().