og-8.x-1.x-dev/src/Plugin/Field/OgEntityReferenceFieldItemList.php
src/Plugin/Field/OgEntityReferenceFieldItemList.php
<?php
namespace Drupal\og\Plugin\Field;
use Drupal\Core\Entity\FieldableEntityInterface;
use Drupal\Core\Field\EntityReferenceFieldItemListInterface;
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Field\FieldItemList;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Session\AccountProxyInterface;
use Drupal\Core\TypedData\TraversableTypedDataInterface;
use Drupal\og\OgAccessInterface;
use Drupal\og\OgGroupAudienceHelperInterface;
/**
* Defines an item list class for entity reference fields.
*/
class OgEntityReferenceFieldItemList extends FieldItemList implements EntityReferenceFieldItemListInterface {
/**
* Helper to identify OG audience fields.
*/
protected OgGroupAudienceHelperInterface $groupAudienceHelper;
/**
* OG access checker.
*/
protected OgAccessInterface $ogAccess;
/**
* Current user proxy.
*/
protected AccountProxyInterface $currentUser;
/**
* {@inheritdoc}
*/
public static function createInstance($definition, $name = NULL, ?TraversableTypedDataInterface $parent = NULL) {
$instance = new static($definition, $name, $parent);
$container = \Drupal::getContainer();
$instance->groupAudienceHelper = $container->get('og.group_audience_helper');
$instance->ogAccess = $container->get('og.access');
$instance->currentUser = $container->get('current_user');
return $instance;
}
/**
* {@inheritdoc}
*/
public function getConstraints() {
$constraints = parent::getConstraints();
// Add the ValidOgMembershipReference constraint at the field list level.
// This ensures that group membership and access checks are validated when
// the field is submitted.
$constraint_manager = \Drupal::typedDataManager()->getValidationConstraintManager();
$constraints[] = $constraint_manager->create('ValidOgMembershipReference', []);
return $constraints;
}
/**
* {@inheritdoc}
*/
public function referencedEntities() {
if ($this->isEmpty()) {
return [];
}
// Collect the IDs of existing entities to load, and keep any
// entities already populated on the field items.
$target_entities = $ids = [];
foreach ($this->list as $delta => $item) {
if ($item->target_id !== NULL) {
$ids[$delta] = $item->target_id;
}
elseif ($item->hasNewEntity()) {
$target_entities[$delta] = $item->entity;
}
}
// Load and add the existing entities.
if ($ids) {
$target_type = $this->getFieldDefinition()->getSetting('target_type');
$entities = \Drupal::entityTypeManager()->getStorage($target_type)->loadMultiple($ids);
foreach ($ids as $delta => $target_id) {
if (isset($entities[$target_id])) {
$target_entities[$delta] = $entities[$target_id];
}
}
// Ensure the returned array is ordered by deltas.
ksort($target_entities);
}
return $this->filterAudienceDefaults($target_entities);
}
/**
* {@inheritdoc}
*/
public static function processDefaultValue($default_value, FieldableEntityInterface $entity, FieldDefinitionInterface $definition) {
$default_value = parent::processDefaultValue($default_value, $entity, $definition);
if ($default_value) {
// Convert UUIDs to numeric IDs.
$uuids = [];
foreach ($default_value as $delta => $properties) {
if (isset($properties['target_uuid'])) {
$uuids[$delta] = $properties['target_uuid'];
}
}
if ($uuids) {
$target_type = $definition->getSetting('target_type');
$entity_ids = \Drupal::entityQuery($target_type)
->accessCheck(TRUE)
->condition('uuid', $uuids, 'IN')
->execute();
$entities = \Drupal::entityTypeManager()
->getStorage($target_type)
->loadMultiple($entity_ids);
$entity_uuids = [];
foreach ($entities as $id => $entity) {
$entity_uuids[$entity->uuid()] = $id;
}
foreach ($uuids as $delta => $uuid) {
if (isset($entity_uuids[$uuid])) {
$default_value[$delta]['target_id'] = $entity_uuids[$uuid];
unset($default_value[$delta]['target_uuid']);
}
else {
unset($default_value[$delta]);
}
}
}
// Ensure we return consecutive deltas, in case we removed unknown UUIDs.
$default_value = array_values($default_value);
}
return $default_value;
}
/**
* Filters audience defaults based on access to the referenced groups.
*
* Removes any referenced groups the current user may not select while
* editing, preventing hidden groups from being exposed by default values.
*
* @param \Drupal\Core\Entity\EntityInterface[] $target_entities
* The referenced entities.
*
* @return \Drupal\Core\Entity\EntityInterface[]
* The filtered referenced entities.
*/
protected function filterAudienceDefaults(array $target_entities): array {
// Nothing to hide.
if (empty($target_entities)) {
return $target_entities;
}
// Double check this is a group audience field or we aren't filtering.
$field_definition = $this->getFieldDefinition();
if (!$this->groupAudienceHelper->isGroupAudienceField($field_definition)) {
return $target_entities;
}
// Bypass filtering for OG admin.
$account = $this->currentUser->getAccount();
if ($account->hasPermission('administer organic groups')) {
return $target_entities;
}
// Hide group values for groups the user can't post in.
$group_content_entity = $this->getEntity();
foreach ($target_entities as $delta => $group) {
$access = $this->ogAccess->userAccessGroupContentEntityOperation('create', $group, $group_content_entity, $account);
if (!$access->isAllowed()) {
unset($target_entities[$delta]);
}
}
return array_values($target_entities);
}
/**
* {@inheritdoc}
*/
public function defaultValuesFormSubmit(array $element, array &$form, FormStateInterface $form_state) {
$default_value = parent::defaultValuesFormSubmit($element, $form, $form_state);
// Convert numeric IDs to UUIDs to ensure config deployability.
$ids = [];
foreach ($default_value as $delta => $properties) {
$ids[] = $default_value[$delta]['target_id'];
}
$entities = \Drupal::entityTypeManager()
->getStorage($this->getSetting('target_type'))
->loadMultiple($ids);
foreach ($default_value as $delta => $properties) {
unset($default_value[$delta]['target_id']);
$default_value[$delta]['target_uuid'] = $entities[$properties['target_id']]->uuid();
}
return $default_value;
}
}
