OgGroupAudienceHelper.php in Organic groups 8
File
src/OgGroupAudienceHelper.php
View source
<?php
declare (strict_types=1);
namespace Drupal\og;
use Drupal\Core\Entity\EntityFieldManagerInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Entity\FieldableEntityInterface;
use Drupal\Core\Field\FieldDefinitionInterface;
class OgGroupAudienceHelper implements OgGroupAudienceHelperInterface {
protected $entityTypeManager;
protected $entityFieldManager;
public function __construct(EntityTypeManagerInterface $entity_type_manager, EntityFieldManagerInterface $entity_field_manager) {
$this->entityTypeManager = $entity_type_manager;
$this->entityFieldManager = $entity_field_manager;
}
public function hasGroupAudienceField($entity_type_id, $bundle_id) {
return (bool) $this
->getAllGroupAudienceFields($entity_type_id, $bundle_id);
}
public static function isGroupAudienceField(FieldDefinitionInterface $field_definition) {
return $field_definition
->getType() == OgGroupAudienceHelperInterface::GROUP_REFERENCE;
}
public function getAllGroupAudienceFields($group_content_entity_type_id, $group_content_bundle_id, $group_entity_type_id = NULL, $group_bundle_id = NULL) {
$return = [];
$entity_type = $this->entityTypeManager
->getDefinition($group_content_entity_type_id);
if (!$entity_type
->entityClassImplements(FieldableEntityInterface::class)) {
return [];
}
$field_definitions = $this->entityFieldManager
->getFieldDefinitions($group_content_entity_type_id, $group_content_bundle_id);
foreach ($field_definitions as $field_definition) {
if (!$this
->isGroupAudienceField($field_definition)) {
continue;
}
$target_type = $field_definition
->getFieldStorageDefinition()
->getSetting('target_type');
if (isset($group_entity_type_id) && $target_type != $group_entity_type_id) {
continue;
}
$handler_settings = $field_definition
->getSetting('handler_settings');
if (isset($group_bundle_id) && !empty($handler_settings['target_bundles']) && !in_array($group_bundle_id, $handler_settings['target_bundles'])) {
continue;
}
$field_name = $field_definition
->getName();
$return[$field_name] = $field_definition;
}
return $return;
}
}