You are here

og_test.module in Organic groups 8

File

tests/modules/og_test/og_test.module
View source
<?php

/**
 * @file
 * Main functions and hook implementations of the OG Test module.
 */
declare (strict_types=1);
use Drupal\Core\Access\AccessResultAllowed;
use Drupal\Core\Access\AccessResultInterface;
use Drupal\Core\Cache\CacheableMetadata;
use Drupal\Core\Entity\EntityInterface;
use Drupal\og\Entity\OgRole;
use Drupal\og\Og;

/**
 * Implements hook_module_implements_alter().
 */
function og_test_module_implements_alter(&$implementations, $hook) {
  if ($hook == 'entity_insert') {

    // Move our implementation of hook_entity_insert() to the top of the list so
    // that it will run before og_entity_insert().
    $implementation = $implementations['og_test'];
    unset($implementations['og_test']);
    $implementations = [
      'og_test' => $implementation,
    ] + $implementations;
  }
}

/**
 * Implements hook_entity_insert().
 */
function og_test_entity_insert(EntityInterface $entity) {

  // In order to test if it is possible to use an hook_entity_insert()
  // implementation to override the user membership that is automatically
  // created in og_entity_insert() we will create our own membership here, if
  // the entity's label matches the one created in the test.
  // @see \Drupal\Tests\og\Kernel\GroupManagerSubscriptionTest
  if ($entity
    ->label() === 'membership is overridden') {

    // Create a membership for the group owner that also has been granted the
    // custom 'moderator' role.
    $membership = Og::createMembership($entity, $entity
      ->getOwner());
    $membership
      ->addRole(OgRole::loadByGroupAndName($entity, 'moderator'));
    $membership
      ->save();
  }
}

/**
 * Implements hook_og_user_access_entity_operation_alter().
 */
function og_test_og_user_access_entity_operation_alter(AccessResultInterface &$access_result, CacheableMetadata $cacheable_metadata, $context) : void {
  if (\Drupal::state()
    ->get('og_test_group_content_entity_operation_access_alter', FALSE)) {

    // Moderators should have access to edit and delete all comments in all
    // groups.

    /** @var \Drupal\Core\Session\AccountProxyInterface $user */
    $user = $context['user'];
    $group_content = $context['group_content'];
    $is_comment = $group_content
      ->getEntityTypeId() === 'comment';
    $user_can_moderate_comments = $user
      ->hasPermission('edit and delete comments in all groups');
    if ($is_comment && $user_can_moderate_comments) {
      $access_result = new AccessResultAllowed();
    }
  }
}

Functions

Namesort descending Description
og_test_entity_insert Implements hook_entity_insert().
og_test_module_implements_alter Implements hook_module_implements_alter().
og_test_og_user_access_entity_operation_alter Implements hook_og_user_access_entity_operation_alter().