You are here

class OgRole in Organic groups 8

Defines the OG user role entity class.

Plugin annotation


@ConfigEntityType(
  id = "og_role",
  label = @Translation("OG role"),
  static_cache = TRUE,
  entity_keys = {
    "id" = "id",
    "label" = "label",
    "weight" = "weight"
  },
  config_export = {
    "id",
    "label",
    "weight",
    "is_admin",
    "group_type",
    "group_bundle",
    "group_id",
    "permissions",
    "role_type"
  }
)

Hierarchy

Expanded class hierarchy of OgRole

See also

\Drupal\user\Entity\Role

33 files declare their use of OgRole
AccessByOgMembershipTest.php in tests/src/Kernel/Access/AccessByOgMembershipTest.php
ActionTestBase.php in tests/src/Kernel/Action/ActionTestBase.php
AddSingleOgMembershipRole.php in src/Plugin/Action/AddSingleOgMembershipRole.php
AddSingleOgMembershipRoleActionTest.php in tests/src/Kernel/Action/AddSingleOgMembershipRoleActionTest.php
ChangeSingleOgMembershipRoleBase.php in src/Plugin/Action/ChangeSingleOgMembershipRoleBase.php

... See full list

File

src/Entity/OgRole.php, line 40

Namespace

Drupal\og\Entity
View source
class OgRole extends Role implements OgRoleInterface {

  /**
   * The role name.
   *
   * @var string
   */
  protected $name;

  /**
   * Whether or not the parent entity we depend on is being removed.
   *
   * @var bool
   *   TRUE if the entity is being removed.
   */
  protected $parentEntityIsBeingRemoved = FALSE;

  /**
   * Constructs an OgRole object.
   *
   * @param array $values
   *   An array of values to set, keyed by property name.
   */
  public function __construct(array $values) {
    parent::__construct($values, 'og_role');
  }

  /**
   * {@inheritdoc}
   */
  public function setId($id) {
    $this
      ->set('id', $id);
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public function getLabel() {
    return $this
      ->get('label');
  }

  /**
   * {@inheritdoc}
   */
  public function setLabel($label) {
    $this
      ->set('label', $label);
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public function getGroupType() {
    return $this
      ->get('group_type');
  }

  /**
   * {@inheritdoc}
   */
  public function setGroupType($group_type) {
    $this
      ->set('group_type', $group_type);
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public function getGroupBundle() {
    return $this
      ->get('group_bundle');
  }

  /**
   * {@inheritdoc}
   */
  public function setGroupBundle($group_bundle) {
    $this
      ->set('group_bundle', $group_bundle);
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public function getRoleType() {
    return $this
      ->get('role_type') ?: OgRoleInterface::ROLE_TYPE_STANDARD;
  }

  /**
   * {@inheritdoc}
   */
  public function setRoleType($role_type) {
    if (!in_array($role_type, [
      self::ROLE_TYPE_REQUIRED,
      self::ROLE_TYPE_STANDARD,
    ])) {
      throw new \InvalidArgumentException("'{$role_type}' is not a valid role type.");
    }
    return $this
      ->set('role_type', $role_type);
  }

  /**
   * {@inheritdoc}
   */
  public function getName() {

    // If the name is not set yet, try to derive it from the ID.
    if (empty($this->name) && $this
      ->id() && $this
      ->getGroupType() && $this
      ->getGroupBundle()) {

      // Check if the ID matches the pattern '{entity type}-{bundle}-{name}'.
      $pattern = preg_quote("{$this->getGroupType()}-{$this->getGroupBundle()}-");
      preg_match("/{$pattern}(.+)/", $this
        ->id(), $matches);
      if (!empty($matches[1])) {
        $this
          ->setName($matches[1]);
      }
    }
    return $this
      ->get('name');
  }

  /**
   * {@inheritdoc}
   */
  public function setName($name) {
    $this->name = $name;
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public static function loadByGroupAndName(EntityInterface $group, $name) {
    $role_id = "{$group->getEntityTypeId()}-{$group->bundle()}-{$name}";
    return self::load($role_id);
  }

  /**
   * {@inheritdoc}
   */
  public static function loadByGroupType($group_entity_type_id, $group_bundle_id) {
    $properties = [
      'group_type' => $group_entity_type_id,
      'group_bundle' => $group_bundle_id,
    ];
    return \Drupal::entityTypeManager()
      ->getStorage('og_role')
      ->loadByProperties($properties);
  }

  /**
   * {@inheritdoc}
   */
  public function save() {

    // The ID of a new OgRole has to consist of the entity type ID, bundle ID
    // and role name, separated by dashes.
    if ($this
      ->isNew() && $this
      ->id()) {
      $pattern = preg_quote("{$this->getGroupType()}-{$this->getGroupBundle()}-{$this->getName()}");
      if (!preg_match("/{$pattern}/", $this
        ->id())) {
        throw new ConfigValueException('The ID should consist of the group entity type ID, group bundle ID and role name, separated by dashes.');
      }
    }

    // If a new OgRole is saved and the ID is not set, construct the ID from
    // the entity type ID, bundle ID and role name.
    if ($this
      ->isNew() && !$this
      ->id()) {
      if (!$this
        ->getGroupType()) {
        throw new ConfigValueException('The group type can not be empty.');
      }
      if (!$this
        ->getGroupBundle()) {
        throw new ConfigValueException('The group bundle can not be empty.');
      }
      if (!$this
        ->getName()) {
        throw new ConfigValueException('The role name can not be empty.');
      }

      // When assigning a role to group we need to add a prefix to the ID in
      // order to prevent duplicate IDs.
      $prefix = $this
        ->getGroupType() . '-' . $this
        ->getGroupBundle() . '-';
      $this
        ->setId($prefix . $this
        ->getName());
    }
    parent::save();
  }

  /**
   * {@inheritdoc}
   */
  public function set($property_name, $value) {

    // Prevent the ID, role type, group ID, group entity type or bundle from
    // being changed once they are set. These properties are required and
    // shouldn't be tampered with.
    $is_locked_property = in_array($property_name, [
      'id',
      'role_type',
      'group_id',
      'group_type',
      'group_bundle',
    ]);
    if (!$is_locked_property || $this
      ->isNew()) {
      return parent::set($property_name, $value);
    }
    if ($this
      ->get($property_name) == $value) {

      // Locked property hasn't changed, so we can return early.
      return $this;
    }
    throw new OgRoleException("The {$property_name} cannot be changed.");
  }

  /**
   * {@inheritdoc}
   */
  public function delete() {

    // The default roles are required. Prevent them from being deleted for as
    // long as the group still exists, unless the group itself is in the process
    // of being removed.
    if (!$this->parentEntityIsBeingRemoved && $this
      ->isRequired() && $this
      ->groupTypeManager()
      ->isGroup($this
      ->getGroupType(), $this
      ->getGroupBundle())) {
      throw new OgRoleException('The default roles "non-member" and "member" cannot be deleted.');
    }
    parent::delete();
  }

  /**
   * {@inheritdoc}
   */
  public function isRequired() {
    return static::getRoleTypeByName($this
      ->getName()) === OgRoleInterface::ROLE_TYPE_REQUIRED;
  }

  /**
   * Maps role names to role types.
   *
   * The 'anonymous' and 'authenticated' roles should not be changed or deleted.
   * All others are standard roles.
   *
   * @param string $role_name
   *   The role name for which to return the type.
   *
   * @return string
   *   The role type, either OgRoleInterface::ROLE_TYPE_REQUIRED or
   *   OgRoleInterface::ROLE_TYPE_STANDARD.
   */
  public static function getRoleTypeByName($role_name) {
    return in_array($role_name, [
      OgRoleInterface::ANONYMOUS,
      OgRoleInterface::AUTHENTICATED,
    ]) ? OgRoleInterface::ROLE_TYPE_REQUIRED : OgRoleInterface::ROLE_TYPE_STANDARD;
  }

  /**
   * {@inheritdoc}
   */
  public static function getRole($entity_type_id, $bundle, $role_name) {
    return self::load($entity_type_id . '-' . $bundle . '-' . $role_name);
  }

  /**
   * Gets the group manager.
   *
   * @return \Drupal\og\GroupTypeManagerInterface
   *   The group manager.
   */
  protected function groupTypeManager() {

    // Returning the group manager by calling the global factory method might
    // seem less than ideal, but Entity classes are not designed to work with
    // proper dependency injection. The ::create() method only accepts a $values
    // array, which is not compatible with ContainerInjectionInterface.
    // See for example Entity::uuidGenerator() in the base Entity class, it
    // also uses this pattern.
    return \Drupal::service('og.group_type_manager');
  }

  /**
   * Gets the OG access service.
   *
   * @return \Drupal\og\OgAccessInterface
   *   The OG access service.
   */
  protected function ogAccess() {
    return \Drupal::service('og.access');
  }

  /**
   * {@inheritdoc}
   */
  public function calculateDependencies() {
    parent::calculateDependencies();

    // Create a dependency on the group bundle.
    $bundle_config_dependency = \Drupal::entityTypeManager()
      ->getDefinition($this
      ->getGroupType())
      ->getBundleConfigDependency($this
      ->getGroupBundle());
    $this
      ->addDependency($bundle_config_dependency['type'], $bundle_config_dependency['name']);
  }

  /**
   * {@inheritdoc}
   */
  public function onDependencyRemoval(array $dependencies) {

    // The parent entity we depend on is being removed. Set a flag so we can
    // allow removal of required roles.
    $this->parentEntityIsBeingRemoved = TRUE;
    return parent::onDependencyRemoval($dependencies);
  }

}

Members

Namesort descending Modifiers Type Description Overrides
CacheableDependencyTrait::$cacheContexts protected property Cache contexts.
CacheableDependencyTrait::$cacheMaxAge protected property Cache max-age.
CacheableDependencyTrait::$cacheTags protected property Cache tags.
CacheableDependencyTrait::setCacheability protected function Sets cacheability; useful for value object constructors.
ConfigEntityBase::$isUninstalling private property Whether the config is being deleted by the uninstall process.
ConfigEntityBase::$langcode protected property The language code of the entity's default language.
ConfigEntityBase::$originalId protected property The original ID of the configuration entity.
ConfigEntityBase::$status protected property The enabled/disabled status of the configuration entity. 4
ConfigEntityBase::$third_party_settings protected property Third party entity settings.
ConfigEntityBase::$trustedData protected property Trust supplied data and not use configuration schema on save.
ConfigEntityBase::$uuid protected property The UUID for this entity.
ConfigEntityBase::$_core protected property Information maintained by Drupal core about configuration.
ConfigEntityBase::addDependency protected function Overrides \Drupal\Core\Entity\DependencyTrait:addDependency().
ConfigEntityBase::createDuplicate public function Creates a duplicate of the entity. Overrides EntityBase::createDuplicate 1
ConfigEntityBase::disable public function Disables the configuration entity. Overrides ConfigEntityInterface::disable 1
ConfigEntityBase::enable public function Enables the configuration entity. Overrides ConfigEntityInterface::enable
ConfigEntityBase::get public function Returns the value of a property. Overrides ConfigEntityInterface::get
ConfigEntityBase::getCacheTagsToInvalidate public function Returns the cache tags that should be used to invalidate caches. Overrides EntityBase::getCacheTagsToInvalidate 1
ConfigEntityBase::getConfigDependencyName public function Gets the configuration dependency name. Overrides EntityBase::getConfigDependencyName
ConfigEntityBase::getConfigManager protected static function Gets the configuration manager.
ConfigEntityBase::getConfigTarget public function Gets the configuration target identifier for the entity. Overrides EntityBase::getConfigTarget
ConfigEntityBase::getDependencies public function Gets the configuration dependencies. Overrides ConfigEntityInterface::getDependencies
ConfigEntityBase::getOriginalId public function Gets the original ID. Overrides EntityBase::getOriginalId
ConfigEntityBase::getThirdPartyProviders public function Gets the list of third parties that store information. Overrides ThirdPartySettingsInterface::getThirdPartyProviders
ConfigEntityBase::getThirdPartySetting public function Gets the value of a third-party setting. Overrides ThirdPartySettingsInterface::getThirdPartySetting
ConfigEntityBase::getThirdPartySettings public function Gets all third-party settings of a given module. Overrides ThirdPartySettingsInterface::getThirdPartySettings
ConfigEntityBase::getTypedConfig protected function Gets the typed config manager.
ConfigEntityBase::hasTrustedData public function Gets whether on not the data is trusted. Overrides ConfigEntityInterface::hasTrustedData
ConfigEntityBase::invalidateTagsOnDelete protected static function Override to never invalidate the individual entities' cache tags; the config system already invalidates them. Overrides EntityBase::invalidateTagsOnDelete
ConfigEntityBase::invalidateTagsOnSave protected function Override to never invalidate the entity's cache tag; the config system already invalidates it. Overrides EntityBase::invalidateTagsOnSave
ConfigEntityBase::isInstallable public function Checks whether this entity is installable. Overrides ConfigEntityInterface::isInstallable 2
ConfigEntityBase::isNew public function Overrides Entity::isNew(). Overrides EntityBase::isNew
ConfigEntityBase::isUninstalling public function Returns whether this entity is being changed during the uninstall process. Overrides ConfigEntityInterface::isUninstalling
ConfigEntityBase::link public function Deprecated way of generating a link to the entity. See toLink(). Overrides EntityBase::link
ConfigEntityBase::preDelete public static function Acts on entities before they are deleted and before hooks are invoked. Overrides EntityBase::preDelete 8
ConfigEntityBase::setOriginalId public function Sets the original ID. Overrides EntityBase::setOriginalId
ConfigEntityBase::setStatus public function Sets the status of the configuration entity. Overrides ConfigEntityInterface::setStatus
ConfigEntityBase::setThirdPartySetting public function Sets the value of a third-party setting. Overrides ThirdPartySettingsInterface::setThirdPartySetting
ConfigEntityBase::setUninstalling public function
ConfigEntityBase::sort public static function Helper callback for uasort() to sort configuration entities by weight and label. 6
ConfigEntityBase::status public function Returns whether the configuration entity is enabled. Overrides ConfigEntityInterface::status 4
ConfigEntityBase::toArray public function Gets an array of all property values. Overrides EntityBase::toArray 2
ConfigEntityBase::toUrl public function Gets the URL object for the entity. Overrides EntityBase::toUrl
ConfigEntityBase::trustData public function Sets that the data should be trusted. Overrides ConfigEntityInterface::trustData
ConfigEntityBase::unsetThirdPartySetting public function Unsets a third-party setting. Overrides ThirdPartySettingsInterface::unsetThirdPartySetting
ConfigEntityBase::url public function Gets the public URL for this entity. Overrides EntityBase::url
ConfigEntityBase::urlInfo public function Gets the URL object for the entity. Overrides EntityBase::urlInfo
ConfigEntityBase::__sleep public function Overrides EntityBase::__sleep 4
DependencySerializationTrait::$_entityStorages protected property An array of entity type IDs keyed by the property name of their storages.
DependencySerializationTrait::$_serviceIds protected property An array of service IDs keyed by property name used for serialization.
DependencySerializationTrait::__sleep public function Aliased as: traitSleep 1
DependencySerializationTrait::__wakeup public function 2
DependencyTrait::$dependencies protected property The object's dependencies.
DependencyTrait::addDependencies protected function Adds multiple dependencies.
DependencyTrait::addDependency protected function Adds a dependency. Aliased as: addDependencyTrait
EntityBase::$enforceIsNew protected property Boolean indicating whether the entity should be forced to be new.
EntityBase::$entityTypeId protected property The entity type.
EntityBase::$typedData protected property A typed data object wrapping this entity.
EntityBase::access public function Checks data value access. Overrides AccessibleInterface::access 1
EntityBase::bundle public function Gets the bundle of the entity. Overrides EntityInterface::bundle 1
EntityBase::create public static function Constructs a new entity object, without permanently saving it. Overrides EntityInterface::create
EntityBase::enforceIsNew public function Enforces an entity to be new. Overrides EntityInterface::enforceIsNew
EntityBase::entityManager Deprecated protected function Gets the entity manager.
EntityBase::entityTypeBundleInfo protected function Gets the entity type bundle info service.
EntityBase::entityTypeManager protected function Gets the entity type manager.
EntityBase::getCacheContexts public function The cache contexts associated with this object. Overrides CacheableDependencyTrait::getCacheContexts
EntityBase::getCacheMaxAge public function The maximum age for which this object may be cached. Overrides CacheableDependencyTrait::getCacheMaxAge
EntityBase::getCacheTags public function The cache tags associated with this object. Overrides CacheableDependencyTrait::getCacheTags
EntityBase::getConfigDependencyKey public function Gets the key that is used to store configuration dependencies. Overrides EntityInterface::getConfigDependencyKey
EntityBase::getEntityType public function Gets the entity type definition. Overrides EntityInterface::getEntityType
EntityBase::getEntityTypeId public function Gets the ID of the type of the entity. Overrides EntityInterface::getEntityTypeId
EntityBase::getListCacheTagsToInvalidate protected function The list cache tags to invalidate for this entity.
EntityBase::getTypedData public function Gets a typed data object for this entity object. Overrides EntityInterface::getTypedData
EntityBase::hasLinkTemplate public function Indicates if a link template exists for a given key. Overrides EntityInterface::hasLinkTemplate
EntityBase::id public function Gets the identifier. Overrides EntityInterface::id 11
EntityBase::label public function Gets the label of the entity. Overrides EntityInterface::label 6
EntityBase::language public function Gets the language of the entity. Overrides EntityInterface::language 1
EntityBase::languageManager protected function Gets the language manager.
EntityBase::linkTemplates protected function Gets an array link templates. 1
EntityBase::load public static function Loads an entity. Overrides EntityInterface::load
EntityBase::loadMultiple public static function Loads one or more entities. Overrides EntityInterface::loadMultiple
EntityBase::postCreate public function Acts on a created entity before hooks are invoked. Overrides EntityInterface::postCreate 4
EntityBase::postDelete public static function Acts on deleted entities before the delete hook is invoked. Overrides EntityInterface::postDelete 16
EntityBase::postSave public function Acts on a saved entity before the insert or update hook is invoked. Overrides EntityInterface::postSave 14
EntityBase::preCreate public static function Changes the values of an entity before it is created. Overrides EntityInterface::preCreate 5
EntityBase::referencedEntities public function Gets a list of entities referenced by this entity. Overrides EntityInterface::referencedEntities 1
EntityBase::toLink public function Generates the HTML for a link to this entity. Overrides EntityInterface::toLink
EntityBase::uriRelationships public function Gets a list of URI relationships supported by this entity. Overrides EntityInterface::uriRelationships
EntityBase::urlRouteParameters protected function Gets an array of placeholders for this entity. 2
EntityBase::uuid public function Gets the entity UUID (Universally Unique Identifier). Overrides EntityInterface::uuid 1
EntityBase::uuidGenerator protected function Gets the UUID generator.
OgRole::$name protected property The role name.
OgRole::$parentEntityIsBeingRemoved protected property Whether or not the parent entity we depend on is being removed.
OgRole::calculateDependencies public function Calculates dependencies and stores them in the dependency property. Overrides ConfigEntityBase::calculateDependencies
OgRole::delete public function Deletes an entity permanently. Overrides EntityBase::delete
OgRole::getGroupBundle public function Returns the group bundle. Overrides OgRoleInterface::getGroupBundle
OgRole::getGroupType public function Returns the group type. Overrides OgRoleInterface::getGroupType
OgRole::getLabel public function Returns the label. Overrides OgRoleInterface::getLabel
OgRole::getName public function Returns the role name. Overrides OgRoleInterface::getName
OgRole::getRole public static function Get a role by the group's bundle and role name. Overrides OgRoleInterface::getRole
OgRole::getRoleType public function Returns the role type. Overrides OgRoleInterface::getRoleType
OgRole::getRoleTypeByName public static function Maps role names to role types.
OgRole::groupTypeManager protected function Gets the group manager.
OgRole::isRequired public function Returns if this is a default role which is required and cannot be deleted. Overrides OgRoleInterface::isRequired
OgRole::loadByGroupAndName public static function Returns the role represented by the given group and role name. Overrides OgRoleInterface::loadByGroupAndName
OgRole::loadByGroupType public static function Returns the roles that are associated with the given group type and bundle. Overrides OgRoleInterface::loadByGroupType
OgRole::ogAccess protected function Gets the OG access service.
OgRole::onDependencyRemoval public function Informs the entity that entities it depends on will be deleted. Overrides ConfigEntityBase::onDependencyRemoval
OgRole::save public function Saves an entity permanently. Overrides ConfigEntityBase::save
OgRole::set public function Sets the value of a property. Overrides ConfigEntityBase::set
OgRole::setGroupBundle public function Sets the group bundle. Overrides OgRoleInterface::setGroupBundle
OgRole::setGroupType public function Sets the group type. Overrides OgRoleInterface::setGroupType
OgRole::setId public function Sets the ID of the role. Overrides OgRoleInterface::setId
OgRole::setLabel public function Sets the label. Overrides OgRoleInterface::setLabel
OgRole::setName public function Sets the role name. Overrides OgRoleInterface::setName
OgRole::setRoleType public function Sets the role type. Overrides OgRoleInterface::setRoleType
OgRole::__construct public function Constructs an OgRole object. Overrides ConfigEntityBase::__construct
OgRoleInterface::ADMINISTRATOR constant The role name of the group administrator.
OgRoleInterface::ANONYMOUS constant The role name of the group non-member.
OgRoleInterface::AUTHENTICATED constant The role name of the group member.
OgRoleInterface::ROLE_TYPE_REQUIRED constant Role type for required roles.
OgRoleInterface::ROLE_TYPE_STANDARD constant Role type for standard roles that are editable and deletable.
PluginDependencyTrait::calculatePluginDependencies protected function Calculates and adds dependencies of a specific plugin instance. 1
PluginDependencyTrait::getPluginDependencies protected function Calculates and returns dependencies of a specific plugin instance.
PluginDependencyTrait::moduleHandler protected function Wraps the module handler. 1
PluginDependencyTrait::themeHandler protected function Wraps the theme handler. 1
RefinableCacheableDependencyTrait::addCacheableDependency public function 1
RefinableCacheableDependencyTrait::addCacheContexts public function
RefinableCacheableDependencyTrait::addCacheTags public function
RefinableCacheableDependencyTrait::mergeCacheMaxAge public function
Role::$id protected property The machine name of this role.
Role::$is_admin protected property An indicator whether the role has all permissions.
Role::$label protected property The human-readable label of this role.
Role::$permissions protected property The permissions belonging to this role.
Role::$weight protected property The weight of this role in administrative listings.
Role::getPermissions public function Returns a list of permissions assigned to the role. Overrides RoleInterface::getPermissions
Role::getWeight public function Returns the weight. Overrides RoleInterface::getWeight
Role::grantPermission public function Grant permissions to the role. Overrides RoleInterface::grantPermission
Role::hasPermission public function Checks if the role has a permission. Overrides RoleInterface::hasPermission
Role::isAdmin public function Indicates that a role has all available permissions. Overrides RoleInterface::isAdmin
Role::postLoad public static function Acts on loaded entities. Overrides EntityBase::postLoad
Role::preSave public function Acts on an entity before the presave hook is invoked. Overrides ConfigEntityBase::preSave
Role::revokePermission public function Revokes a permissions from the user role. Overrides RoleInterface::revokePermission
Role::setIsAdmin public function Sets the role to be an admin role. Overrides RoleInterface::setIsAdmin
Role::setWeight public function Sets the weight to the given value. Overrides RoleInterface::setWeight
RoleInterface::ANONYMOUS_ID constant Role ID for anonymous users; should match the 'role' entity ID.
RoleInterface::AUTHENTICATED_ID constant Role ID for authenticated users; should match the 'role' entity ID.
SynchronizableEntityTrait::$isSyncing protected property Whether this entity is being created, updated or deleted through a synchronization process.
SynchronizableEntityTrait::isSyncing public function
SynchronizableEntityTrait::setSyncing public function