ReferenceFinder.php in Term reference change 8
File
src/ReferenceFinder.php
View source
<?php
namespace Drupal\term_reference_change;
use Drupal\Core\Entity\EntityFieldManagerInterface;
use Drupal\Core\Entity\EntityTypeBundleInfoInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Entity\FieldableEntityInterface;
use Drupal\taxonomy\TermInterface;
class ReferenceFinder implements ReferenceFinderInterface {
private $entityTypeManager;
private $entityFieldManager;
private $entityTypeBundleInfo;
public function __construct(EntityTypeManagerInterface $entityTypeManager, EntityTypeBundleInfoInterface $entityTypeBundleInfo, EntityFieldManagerInterface $entityFieldManager) {
$this->entityTypeManager = $entityTypeManager;
$this->entityTypeBundleInfo = $entityTypeBundleInfo;
$this->entityFieldManager = $entityFieldManager;
}
public function findReferencesFor(TermInterface $term) {
return $this
->loadReferencingEntities($term);
}
private function loadReferencingEntities(TermInterface $term) {
$referenceFields = $this
->findTermReferenceFields();
$referencingEntities = [];
foreach ($referenceFields as $entityType => $bundles) {
$entitiesOfType = $this
->loadReferencingEntitiesOfType($term, $bundles, $entityType);
if (empty($entitiesOfType)) {
continue;
}
$referencingEntities[$entityType] = $entitiesOfType;
}
return $referencingEntities;
}
private function loadReferencingEntitiesOfType(TermInterface $term, array $bundles, $entityType) {
$referencingEntities = [];
foreach ($bundles as $bundle) {
foreach ($bundle as $fieldName) {
$entities = $this->entityTypeManager
->getStorage($entityType)
->loadByProperties([
$fieldName => $term
->id(),
]);
$referencingEntities = array_merge($referencingEntities, $entities);
}
}
return $referencingEntities;
}
public function findTermReferenceFields() {
$termReferenceFields = [];
$entityTypes = $this->entityTypeManager
->getDefinitions();
foreach ($entityTypes as $entityType) {
if (!$entityType
->entityClassImplements(FieldableEntityInterface::class)) {
continue;
}
$referenceFields = $this
->findTermReferenceFieldsForEntityType($entityType
->id());
if (empty($referenceFields)) {
continue;
}
$termReferenceFields[$entityType
->id()] = $referenceFields;
}
return $termReferenceFields;
}
private function findTermReferenceFieldsForEntityType($entityType) {
$bundleNames = array_keys($this->entityTypeBundleInfo
->getBundleInfo($entityType));
$referenceFields = [];
foreach ($bundleNames as $bundleName) {
$fieldDefinitions = $this->entityFieldManager
->getFieldDefinitions($entityType, $bundleName);
foreach ($fieldDefinitions as $fieldDefinition) {
if ($fieldDefinition
->getType() !== 'entity_reference') {
continue;
}
if ($fieldDefinition
->getSetting('target_type') !== 'taxonomy_term') {
continue;
}
if ($fieldDefinition
->isComputed()) {
continue;
}
if ($fieldDefinition
->getName() === 'parent') {
continue;
}
$referenceFields[$bundleName][] = $fieldDefinition
->getName();
}
}
return $referenceFields;
}
}