You are here

public function Link::getTargetEntities in Entity Usage 8.3

Same name and namespace in other branches
  1. 8.2 src/Plugin/EntityUsage/Track/Link.php \Drupal\entity_usage\Plugin\EntityUsage\Track\Link::getTargetEntities()

Retrieve the target entity(ies) from a field item value.

Parameters

\Drupal\Core\Field\FieldItemInterface $item: The field item to get the target entity(ies) from.

Return value

string[] An indexed array of strings where each target entity type and ID are concatenated with a "|" character. Will return an empty array if no target entity could be retrieved from the received field item value.

Overrides EntityUsageTrackInterface::getTargetEntities

File

src/Plugin/EntityUsage/Track/Link.php, line 23

Class

Link
Tracks usage of entities related in Link fields.

Namespace

Drupal\entity_usage\Plugin\EntityUsage\Track

Code

public function getTargetEntities(FieldItemInterface $link) {

  /** @var \Drupal\link\LinkItemInterface $link */

  // Check if the link is referencing an entity.
  $url = $link
    ->getUrl();
  if (!$url
    ->isRouted() || !preg_match('/^entity\\./', $url
    ->getRouteName())) {
    return [];
  }

  // Ge the target entity type and ID.
  $route_parameters = $url
    ->getRouteParameters();
  $target_type = array_keys($route_parameters)[0];
  $target_id = $route_parameters[$target_type];

  // Only return a valid result if the target entity exists.
  if (!$this->entityTypeManager
    ->getStorage($target_type)
    ->load($target_id)) {
    return [];
  }
  return [
    $target_type . '|' . $target_id,
  ];
}