You are here

public static function ResourceIdentifier::toResourceIdentifier in Drupal 8

Same name and namespace in other branches
  1. 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.

1 call to ResourceIdentifier::toResourceIdentifier()
ResourceIdentifier::toResourceIdentifiers in core/modules/jsonapi/src/JsonApiResource/ResourceIdentifier.php
Creates an array of ResourceIdentifier objects.

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);
  $meta = array_diff_key($properties, array_flip([
    $property_name,
    $item
      ->getDataDefinition()
      ->getMainPropertyName(),
  ]));
  if (!is_null($arity)) {
    $meta[static::ARITY_KEY] = $arity;
  }
  return new static($resource_type, $target
    ->uuid(), $meta);
}