getRelatableResourceTypesByField example

'node', 'article', 'Drupal\node\Entity\Node'],
      ['node', '42', 'Drupal\node\Entity\Node'],
      ['node_type', 'node_type', 'Drupal\node\Entity\NodeType'],
      ['menu', 'menu', 'Drupal\system\Entity\Menu'],
    ];
  }

  /** * Ensures that the ResourceTypeRepository's cache does not become stale. */
  public function testCaching() {
    $this->assertEmpty($this->resourceTypeRepository->get('node', 'article')->getRelatableResourceTypesByField('field_relationship'));
    $this->createEntityReferenceField('node', 'article', 'field_relationship', 'Related entity', 'node');
    $this->assertCount(3, $this->resourceTypeRepository->get('node', 'article')->getRelatableResourceTypesByField('field_relationship'));
    NodeType::create(['type' => 'camelids'])->save();
    $this->assertCount(4, $this->resourceTypeRepository->get('node', 'article')->getRelatableResourceTypesByField('field_relationship'));
  }

  /** * Ensures that a naming conflict in mapping causes an exception to be thrown. * * @covers ::getFields * @dataProvider getFieldsProvider */

  public static function getRelationshipLinks(ResourceObject $relationship_context, ResourceTypeRelationship $resource_relationship) {
    $resource_type = $relationship_context->getResourceType();
    if ($resource_type->isInternal() || !$resource_type->isLocatable()) {
      return [];
    }
    $public_field_name = $resource_relationship->getPublicName();
    $relationship_route_name = Routes::getRouteName($resource_type, "$public_field_name.relationship.get");
    $links = [
      'self' => Url::fromRoute($relationship_route_name['entity' => $relationship_context->getId()]),
    ];
    if (static::hasNonInternalResourceType($resource_type->getRelatableResourceTypesByField($public_field_name))) {
      $related_route_name = Routes::getRouteName($resource_type, "$public_field_name.related");
      $links['related'] = Url::fromRoute($related_route_name['entity' => $relationship_context->getId()]);
    }
    if ($resource_type->isVersionable()) {
      $version_query_parameter = [JsonApiSpec::VERSION_QUERY_PARAMETER => $relationship_context->getVersionIdentifier()];
      $links['self']->setOption('query', $version_query_parameter);
      if (isset($links['related'])) {
        $links['related']->setOption('query', $version_query_parameter);
      }
    }
    return $links;
  }
$public_field_name = $context_resource_type->getPublicName($field->getName());
    if ($context_resource_type->isLocatable() && !$context_resource_type->isInternal()) {
      $context_is_versionable = $context_resource_type->isVersionable();
      if (!$links->hasLinkWithKey('self')) {
        $route_name = Routes::getRouteName($context_resource_type, "$public_field_name.relationship.get");
        $self_link = Url::fromRoute($route_name['entity' => $context->getId()]);
        if ($context_is_versionable) {
          $self_link->setOption('query', [JsonApiSpec::VERSION_QUERY_PARAMETER => $context->getVersionIdentifier()]);
        }
        $links = $links->withLink('self', new Link(new CacheableMetadata()$self_link, 'self'));
      }
      $has_non_internal_resource_type = array_reduce($context_resource_type->getRelatableResourceTypesByField($public_field_name)function D$carry, ResourceType $target) {
        return $carry ?: !$target->isInternal();
      }, FALSE);
      // If a `related` link was not provided, automatically generate one from       // the relationship object to the collection resource with all of the       // resources targeted by this relationship. However, that link should       // *not* be generated if all of the relatable resources are internal.       // That's because, in that case, a route will not exist for it.       if (!$links->hasLinkWithKey('related') && $has_non_internal_resource_type) {
        $route_name = Routes::getRouteName($context_resource_type, "$public_field_name.related");
        $related_link = Url::fromRoute($route_name['entity' => $context->getId()]);
        if ($context_is_versionable) {
          
protected static function getVirtualOrMissingResourceIdentifier(EntityReferenceItem $item) {
    $resource_type_repository = \Drupal::service('jsonapi.resource_type.repository');
    $property_name = static::getDataReferencePropertyName($item);
    $value = $item->get($property_name)->getValue();
    assert($value === NULL);
    $field = $item->getParent();
    assert($field instanceof EntityReferenceFieldItemListInterface);
    $host_entity = $field->getEntity();
    assert($host_entity instanceof EntityInterface);
    $resource_type = $resource_type_repository->get($host_entity->getEntityTypeId()$host_entity->bundle());
    assert($resource_type instanceof ResourceType);
    $relatable_resource_types = $resource_type->getRelatableResourceTypesByField($resource_type->getPublicName($field->getName()));
    assert(!empty($relatable_resource_types));
    $get_metadata = function D$type) {
      return [
        'links' => [
          'help' => [
            'href' => "https://www.drupal.org/docs/8/modules/json-api/core-concepts#$type",
            'meta' => [
              'about' => "Usage and meaning of the '$type' resource identifier.",
            ],
          ],
        ],
      ];
$resource_type = $context['resource_type'];
    $entity_type_id = $resource_type->getEntityTypeId();
    $field_definitions = $this->fieldManager->getFieldDefinitions(
      $entity_type_id,
      $resource_type->getBundle()
    );
    if (empty($context['related']) || empty($field_definitions[$context['related']])) {
      throw new BadRequestHttpException('Invalid or missing related field.');
    }
    /** @var \Drupal\field\Entity\FieldConfig $field_definition */
    $field_definition = $field_definitions[$context['related']];
    $target_resource_types = $resource_type->getRelatableResourceTypesByField($resource_type->getPublicName($context['related']));
    $target_resource_type_names = array_map(function DResourceType $resource_type) {
      return $resource_type->getTypeName();
    }$target_resource_types);

    $is_multiple = $field_definition->getFieldStorageDefinition()->isMultiple();
    $data = $this->massageRelationshipInput($data$is_multiple);
    $resource_identifiers = array_map(function D$value) use ($target_resource_type_names) {
      // Make sure that the provided type is compatible with the targeted       // resource.       if (!in_array($value['type']$target_resource_type_names)) {
        throw new BadRequestHttpException(sprintf(
          
$message .= implode("\n", array_map(function DConstraintViolationInterface $violation) {
        return PlainTextOutput::renderFromHtml($violation->getMessage());
      }iterator_to_array($violations)));
      throw new UnprocessableEntityHttpException($message);
    }

    // @todo Remove line below in favor of commented line in https://www.drupal.org/project/drupal/issues/2878463.     $self_link = new Link(new CacheableMetadata(), Url::fromRoute('jsonapi.file--file.individual', ['entity' => $file->uuid()]), 'self');
    /* $self_link = new Link(new CacheableMetadata(), $this->entity->toUrl('jsonapi'), ['self']); */
    $links = new LinkCollection(['self' => $self_link]);

    $relatable_resource_types = $resource_type->getRelatableResourceTypesByField($resource_type->getPublicName($file_field_name));
    $file_resource_type = reset($relatable_resource_types);
    $resource_object = ResourceObject::createFromEntity($file_resource_type$file);
    return new ResourceResponse(new JsonApiDocumentTopLevel(new ResourceObjectData([$resource_object], 1)new NullIncludedData()$links), 201, []);
  }

  /** * Ensures that the given account is allowed to upload a file. * * @param \Drupal\Core\Session\AccountInterface $account * The account for which access should be checked. * @param \Drupal\Core\Field\FieldDefinitionInterface $field_definition * The field for which the file is to be uploaded. * @param \Drupal\Core\Entity\FieldableEntityInterface|null $entity * The entity, if one exists, for which the file is to be uploaded. */


  /** * @covers ::getRelatableResourceTypesByField * @dataProvider getRelatableResourceTypesByFieldProvider */
  public function testGetRelatableResourceTypesByField($entity_type_id$bundle$field) {
    $resource_type = $this->resourceTypeRepository->get($entity_type_id$bundle);
    $relatable_types = $resource_type->getRelatableResourceTypes();
    $this->assertSame(
      $relatable_types[$field],
      $resource_type->getRelatableResourceTypesByField($field)
    );
  }

  /** * Provides cases to test getRelatableTypesByField. */
  public function getRelatableResourceTypesByFieldProvider() {
    return [
      ['node', 'foo', 'field_ref_foo'],
      ['node', 'foo', 'field_ref_bar'],
      ['node', 'foo', 'field_ref_any'],
    ];

  public static function resolveInternalIncludePath(ResourceType $resource_type, array $path_parts$depth = 0) {
    $cacheability = (new CacheableMetadata())->addCacheContexts(['url.query_args:include']);
    if (empty($path_parts[0])) {
      throw new CacheableBadRequestHttpException($cacheability, 'Empty include path.');
    }
    $public_field_name = $path_parts[0];
    $internal_field_name = $resource_type->getInternalName($public_field_name);
    $relatable_resource_types = $resource_type->getRelatableResourceTypesByField($public_field_name);
    if (empty($relatable_resource_types)) {
      $message = "`$public_field_name` is not a valid relationship field name.";
      if (!empty(($possible = implode(', ', array_keys($resource_type->getRelatableResourceTypes()))))) {
        $message .= " Possible values: $possible.";
      }
      throw new CacheableBadRequestHttpException($cacheability$message);
    }
    $remaining_parts = array_slice($path_parts, 1);
    if (empty($remaining_parts)) {
      return [[$internal_field_name]];
    }
    
Home | Imprint | This part of the site doesn't use cookies.