You are here

protected static function FieldResolver::getDataReferencePropertyName in JSON:API 8

Same name and namespace in other branches
  1. 8.2 src/Context/FieldResolver.php \Drupal\jsonapi\Context\FieldResolver::getDataReferencePropertyName()

Determines the reference property name from the given field definitions.

Parameters

\Drupal\Core\TypedData\ComplexDataDefinitionInterface[] $candidate_definitions: A list of targeted field item definitions specified by the path.

string[] $remaining_parts: The remaining path parts.

string[] $unresolved_path_parts: The unresolved path parts.

Return value

string The reference name.

1 call to FieldResolver::getDataReferencePropertyName()
FieldResolver::resolveInternalEntityQueryPath in src/Context/FieldResolver.php
Resolves external field expressions into entity query compatible paths.

File

src/Context/FieldResolver.php, line 540

Class

FieldResolver
A service that evaluates external path expressions against Drupal fields.

Namespace

Drupal\jsonapi\Context

Code

protected static function getDataReferencePropertyName(array $candidate_definitions, array $remaining_parts, array $unresolved_path_parts) {
  $reference_property_names = array_reduce($candidate_definitions, function (array $reference_property_names, ComplexDataDefinitionInterface $definition) {
    $property_definitions = $definition
      ->getPropertyDefinitions();
    foreach ($property_definitions as $property_name => $property_definition) {
      if ($property_definition instanceof DataReferenceDefinitionInterface) {
        $target_definition = $property_definition
          ->getTargetDefinition();
        assert($target_definition instanceof EntityDataDefinitionInterface, 'Entity reference fields should only be able to reference entities.');
        $reference_property_names[] = $property_name . ':' . $target_definition
          ->getEntityTypeId();
      }
    }
    return $reference_property_names;
  }, []);
  $unique_reference_names = array_unique($reference_property_names);
  if (count($unique_reference_names) > 1) {
    $choices = array_map(function ($reference_name) use ($unresolved_path_parts, $remaining_parts) {
      $prior_parts = array_slice($unresolved_path_parts, 0, count($unresolved_path_parts) - count($remaining_parts));
      return implode('.', array_merge($prior_parts, [
        $reference_name,
      ], $remaining_parts));
    }, $unique_reference_names);

    // @todo Add test coverage for this in https://www.drupal.org/project/jsonapi/issues/2971281
    $message = sprintf('Ambiguous path. Try one of the following: %s, in place of the given path: %s', implode(', ', $choices), implode('.', $unresolved_path_parts));
    throw new BadRequestHttpException($message);
  }
  return $unique_reference_names[0];
}