You are here

public static function ResourceIdentifier::toResourceIdentifier in Drupal 10

Same name and namespace in other branches
  1. 8 core/modules/jsonapi/src/JsonApiResource/ResourceIdentifier.php \Drupal\jsonapi\JsonApiResource\ResourceIdentifier::toResourceIdentifier()
  2. 9 core/modules/jsonapi/src/JsonApiResource/ResourceIdentifier.php \Drupal\jsonapi\JsonApiResource\ResourceIdentifier::toResourceIdentifier()

Creates a ResourceIdentifier object.

Parameters

\Drupal\Core\Field\Plugin\Field\FieldType\EntityReferenceItem $item: The entity reference field item from which to create the relationship.

int $arity: (optional) The arity of the relationship.

Return value

self A new ResourceIdentifier object.

File

core/modules/jsonapi/src/JsonApiResource/ResourceIdentifier.php, line 282

Class

ResourceIdentifier
Represents a JSON:API resource identifier object.

Namespace

Drupal\jsonapi\JsonApiResource

Code

public static function toResourceIdentifier(EntityReferenceItem $item, $arity = NULL) {
  $property_name = static::getDataReferencePropertyName($item);
  $target = $item
    ->get($property_name)
    ->getValue();
  if ($target === NULL) {
    return static::getVirtualOrMissingResourceIdentifier($item);
  }
  assert($target instanceof EntityInterface);

  /** @var \Drupal\jsonapi\ResourceType\ResourceTypeRepositoryInterface $resource_type_repository */
  $resource_type_repository = \Drupal::service('jsonapi.resource_type.repository');
  $resource_type = $resource_type_repository
    ->get($target
    ->getEntityTypeId(), $target
    ->bundle());

  // Remove unwanted properties from the meta value, usually 'entity'
  // and 'target_id'.
  $properties = TypedDataInternalPropertiesHelper::getNonInternalProperties($item);
  $main_property_name = $item
    ->getDataDefinition()
    ->getMainPropertyName();
  $meta = array_diff_key($properties, array_flip([
    $property_name,
    $main_property_name,
  ]));
  if (!is_null($arity)) {
    $meta[static::ARITY_KEY] = $arity;
  }
  $meta["drupal_internal__{$main_property_name}"] = $properties[$main_property_name];
  return new static($resource_type, $target
    ->uuid(), $meta);
}