Skip to content

Instantly share code, notes, and snippets.

@amitaibu
Created September 25, 2016 12:01
Show Gist options
  • Save amitaibu/11888096fe705b077cdd5f692c1529a7 to your computer and use it in GitHub Desktop.
Save amitaibu/11888096fe705b077cdd5f692c1529a7 to your computer and use it in GitHub Desktop.
<?php
/**
* Get the parent groups of an entity.
*
* @param \Drupal\Core\Entity\EntityInterface $entity
* The entity objects.
* @param array $groups
* Array of group entities passed by reference.
*
* @return array
* Array of group entities.
*/
protected function getParentGroups(EntityInterface $entity, &$groups = []) {
$fields = OgGroupAudienceHelper::getAllGroupAudienceFields($entity->getEntityTypeId(), $entity->bundle());
if (Og::isGroup($entity->getEntityTypeId(), $entity->bundle())) {
$groups[] = $entity;
}
if (!$fields) {
// We have reached the top level group, that doesn't have audience fields.
return $groups;
}
foreach ($fields as $field) {
$field_name = $field->getName();
$group = $entity->{$field_name}->entity;
self::getParentGroups($group, $groups);
}
return $groups;
}
/**
* Determine if user access based on atleast one group.
*
* @param \Drupal\Core\Entity\EntityInterface $entity
* The group contnt entity.
*
* @return bool
* TRUE if user has access, FALSE otherwise.
*/
protected function hasAccessByGroupParents(EntityInterface $entity) {
$groups = $this->getParentGroups($entity);
/** @var \Drupal\og\OgAccessInterface $og_access */
$og_access = \Drupal::service('og.access');
// Check access of a user.
foreach ($groups as $group) {
$access = $og_access->userAccess($group, 'some permission');
if ($access->isAllowed()) {
return TRUE;
}
}
return FALSE;
}
@pwolanin
Copy link

Should return $access here?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment