pm-4.1.x-dev/src/Service/PmHierarchy.php
src/Service/PmHierarchy.php
<?php
declare(strict_types=1);
namespace Drupal\pm\Service;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
/**
* Helper service to work with hierarchy of PM Entities.
*/
final class PmHierarchy {
/**
* Constructs a PmHierarchy object.
*/
public function __construct(
private readonly PmConfig $pmConfig,
private readonly EntityTypeManagerInterface $entityTypeManager,
) {}
/**
* Get child entities based on hierarchy.
*
* @param \Drupal\Core\Entity\EntityInterface $entity
* The entity for which the child item needs to be found.
*
* @return array
* The child entities.
*/
public function getChildren(EntityInterface $entity): array {
$entity_type = $entity->getEntityTypeId();
$bundle = $entity->bundle();
$children_ref_field = $this->pmConfig->getChildReferenceFieldName($entity_type, $bundle);
return $entity->{$children_ref_field}?->referencedEntities() ?: [];
}
/**
* Get parent of current entity based on hierarchy.
*
* @param \Drupal\Core\Entity\EntityInterface $entity
* The entity for which the parent item needs to be found.
*
* @return \Drupal\Core\Entity\EntityInterface|null
* The parent entity
*/
public function getParent(EntityInterface $entity): ?EntityInterface {
$entity_type = $entity->getEntityTypeId();
$parent_ref_field = $this->pmConfig->getParentReferenceFieldName($entity_type);
return $entity->{$parent_ref_field}?->entity;
}
}
