sites_group_overrides-1.x-dev/src/Entity/GroupRelationship.php
src/Entity/GroupRelationship.php
<?php
namespace Drupal\sites_group_overrides\Entity;
use Drupal\Core\Entity\ContentEntityBase;
use Drupal\Core\Entity\EntityStorageInterface;
use Drupal\group\Entity\GroupRelationship as OriginalGroupRelationship;
use Drupal\group\Entity\GroupRelationshipInterface;
use Drupal\group\Entity\Storage\GroupRoleStorageInterface;
/**
* Extends the GroupRelationship entity class.
*
* The original GroupRelationship saves the entity in postSave and postDelete.
* This causes overides to end up in the original entity - which we avoid here.
*/
class GroupRelationship extends OriginalGroupRelationship {
/**
* {@inheritdoc}
*/
public function postSave(EntityStorageInterface $storage, $update = TRUE) {
if ($update === FALSE) {
// We want to save the unchanged entity without overrides.
$entity = $this->entityTypeManager()->getStorage($this->getEntity()->getEntityTypeId())->loadUnchanged($this->getEntity()->id());
$entity->setSyncing(TRUE);
// See parent::postSave() why this is neccessary.
$entity->save();
}
return parent::postSave($storage);
}
/**
* {@inheritdoc}
*/
public static function postDelete(EntityStorageInterface $storage, array $entities) {
ContentEntityBase::postDelete($storage, $entities);
foreach ($entities as $group_relationship) {
assert($group_relationship instanceof GroupRelationshipInterface);
if ($entity = $group_relationship->getEntity()) {
// We want to save the unchanged entity without overrides.
$entity = \Drupal::entityTypeManager()->getStorage($entity->getEntityTypeId())->loadUnchanged($entity->id());
$entity->setSyncing(TRUE);
// See parent::postDelete() why this is neccessary.
$entity->save();
// If a membership gets deleted, we need to reset the internal group
// roles cache for the member in that group, but only if the user still
// exists. Otherwise, it doesn't matter as the user ID will become void.
if ($group_relationship->getPluginId() == 'group_membership') {
$role_storage = \Drupal::entityTypeManager()->getStorage('group_role');
assert($role_storage instanceof GroupRoleStorageInterface);
$role_storage->resetUserGroupRoleCache($group_relationship->getEntity(), $group_relationship->getGroup());
}
}
}
}
}
