You are here

BookAccessHelper.php in Book access 1.x

Namespace

Drupal\book_access

File

src/BookAccessHelper.php
View source
<?php

namespace Drupal\book_access;

use Drupal\book_access\Entity\BookAccessDefaultsInterface;
use Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException;
use Drupal\Component\Plugin\Exception\PluginNotFoundException;
use Drupal\Core\Entity\EntityStorageException;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\user\RoleInterface;
use Psr\Log\LoggerInterface;

/**
 * Helper functions for book_access.
 */
class BookAccessHelper {
  use StringTranslationTrait;

  /**
   * The EntityTypeManager service.
   *
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected $entityTypeManager;

  /**
   * The logger service.
   *
   * @var \Psr\Log\LoggerInterface
   */
  protected $logger;

  /**
   * Constructs a new ContentUninstallValidator.
   *
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   *   The entity type manager service.
   * @param \Psr\Log\LoggerInterface $logger
   *   The logger service.
   */
  public function __construct(EntityTypeManagerInterface $entity_type_manager, LoggerInterface $logger) {
    $this->entityTypeManager = $entity_type_manager;
    $this->logger = $logger;
  }

  /**
   * Returns the grant IDs implemented by the module.
   */
  public function grantIds() {
    return [
      'grant_view',
      'grant_update',
      'grant_delete',
      'grant_admin_access',
      'grant_add_child',
      'grant_edit_outline',
    ];
  }

  /**
   * Returns the default access permissions.
   *
   * @param string $grant_type
   *   The type of grant to get defaults for.
   *
   * @return array
   *   An array of grants.
   */
  public function defaultGrants(string $grant_type) {
    switch ($grant_type) {
      case '__author__':
        return [
          'grant_view' => TRUE,
          'grant_update' => TRUE,
          'grant_delete' => TRUE,
          'grant_admin_access' => FALSE,
          'grant_add_child' => TRUE,
          'grant_edit_outline' => TRUE,
        ];
      case 'administrator':
        return [
          'grant_view' => TRUE,
          'grant_update' => TRUE,
          'grant_delete' => TRUE,
          'grant_admin_access' => TRUE,
          'grant_add_child' => TRUE,
          'grant_edit_outline' => TRUE,
        ];
      default:
        return [
          'grant_view' => TRUE,
          'grant_update' => FALSE,
          'grant_delete' => FALSE,
          'grant_admin_access' => FALSE,
          'grant_add_child' => FALSE,
          'grant_edit_outline' => FALSE,
        ];
    }
  }

  /**
   * Set defaults for newly created roles.
   *
   * See hook_ENTITY_TYPE_create() in book.module.
   *
   * @param \Drupal\user\RoleInterface $role
   *   The role to set the default for.
   *
   *   Based on the role name, this initializes the default grants for the role
   *   id.  This is only intended to be used during hook_init() or when
   *   creating a brand new role.
   */
  public function setDefaultForRole(RoleInterface $role) {
    $role_id = $role
      ->id();
    if ($role_id == 'administrator') {
      $defaultToUse = $this
        ->defaultGrants('administrator');
    }
    elseif ($role_id == '__author__') {
      $this->logger
        ->error($this
        ->t("Could not set default book_access grants for role: @rid", [
        '@rid' => $role_id,
      ]));
      return;
    }
    else {
      $defaultToUse = $this
        ->defaultGrants($role_id);
    }
    $values = [
      'id' => $role_id,
      'label' => $this
        ->t('%role_label role default grants', [
        '%role_label' => $role
          ->label(),
      ]),
      'grant_type' => 'role',
      'role_id' => $role_id,
      'grants' => $defaultToUse,
    ];
    try {
      $this->entityTypeManager
        ->getStorage('book_access_defaults')
        ->create($values)
        ->save();
    } catch (InvalidPluginDefinitionException $e) {
      $this->logger
        ->error($this
        ->t("Could not set default book_access grants for role: @rid", [
        '@rid' => $role_id,
      ]));
    } catch (PluginNotFoundException $e) {
      $this->logger
        ->error($this
        ->t("Could not set default book_access grants for role: @rid", [
        '@rid' => $role_id,
      ]));
    } catch (EntityStorageException $e) {
      $this->logger
        ->error($this
        ->t("Could not set default book_access grants for role: @rid", [
        '@rid' => $role_id,
      ]));
    }
  }

  /**
   * Get the author saved defaults.
   */
  public function getAuthorBookAccessDefaults() : ?BookAccessDefaultsInterface {
    return $this->entityTypeManager
      ->getStorage('book_access_defaults')
      ->load('book_access_author_defaults');
  }

  /**
   * Get the saved defaults for every role sorted by role weight.
   */
  public function getRoleBookAccessDefaults() : array {
    $results = [];

    // Get the roles by weight.
    $query = $this->entityTypeManager
      ->getStorage('user_role')
      ->getQuery();
    $role_results = $query
      ->sort('weight', 'ASC')
      ->execute();
    $roles = $this->entityTypeManager
      ->getStorage('user_role')
      ->loadMultiple(array_keys($role_results));

    // Get all the book access defaults entities.
    $query = $this->entityTypeManager
      ->getStorage('book_access_defaults')
      ->getQuery();
    $defaults_ids = $query
      ->execute();
    $defaults = $this->entityTypeManager
      ->getStorage('book_access_defaults')
      ->loadMultiple(array_keys($defaults_ids));
    foreach ($roles as $role) {
      $results[$role
        ->id()] = [
        'label' => $role
          ->label(),
        'default_grants' => $defaults[$role
          ->id()] ?? $this
          ->setDefaultForRole($role),
      ];
    }
    return $results;
  }

  /**
   * Update defaults from book_admin_settings form.
   *
   * @param array $book_access_defaults
   *   The book_access_defaults value.
   *
   * @return bool
   *   Whether the update succeeded or not.
   */
  public function updateDefaultsSettings(array $book_access_defaults) : bool {
    $result = TRUE;
    foreach ($book_access_defaults as $id => $book_access_default) {
      $grant_values = [];
      foreach ($book_access_default as $key => $item) {
        $grant_values[$key] = boolval($item);
      }
      try {

        /** @var \Drupal\book_access\Entity\BookAccessDefaultsInterface $accessDefault */
        $accessDefault = $this->entityTypeManager
          ->getStorage('book_access_defaults')
          ->load($id);
        $accessDefault
          ->set('grants', $grant_values)
          ->save();
      } catch (EntityStorageException|InvalidPluginDefinitionException|PluginNotFoundException $e) {
        $result = FALSE;
        break;
      }
    }
    return $result;
  }

}

Classes

Namesort descending Description
BookAccessHelper Helper functions for book_access.