getPublicName example

$entity_type_id = $resource_type->getEntityTypeId();
    $entity_type_definition = $this->entityTypeManager->getDefinition($entity_type_id);
    $bundle_key = $entity_type_definition->getKey('bundle');
    $uuid_key = $entity_type_definition->getKey('uuid');

    // User resource objects contain a read-only attribute that is not a real     // field on the user entity type.     // @see \Drupal\jsonapi\JsonApiResource\ResourceObject::extractContentEntityFields()     // @todo: eliminate this special casing in https://www.drupal.org/project/drupal/issues/3079254.     if ($entity_type_id === 'user') {
      $data = array_diff_key($dataarray_flip([$resource_type->getPublicName('display_name')]));
    }

    // Translate the public fields into the entity fields.     foreach ($data as $public_field_name => $field_value) {
      $internal_name = $resource_type->getInternalName($public_field_name);

      // Skip any disabled field, except the always required bundle key and       // required-in-case-of-PATCHing uuid key.       // @see \Drupal\jsonapi\ResourceType\ResourceTypeRepository::getFieldMapping()       if ($resource_type->hasField($internal_name) && !$resource_type->isFieldEnabled($internal_name) && $bundle_key !== $internal_name && $uuid_key !== $internal_name) {
        continue;
      }
array_keys($fields),
      [$resource_type, 'isFieldEnabled']
    );

    // Special handling for user entities that allows a JSON:API user agent to     // access the display name of a user. For example, this is useful when     // displaying the name of a node's author.     // @todo: eliminate this special casing in https://www.drupal.org/project/drupal/issues/3079254.     $entity_type = $entity->getEntityType();
    if ($entity_type->id() == 'user' && $resource_type->isFieldEnabled('display_name')) {
      assert($entity instanceof UserInterface);
      $display_name = $resource_type->getPublicName('display_name');
      $output[$display_name] = $entity->getDisplayName();
    }

    // Return a sub-array of $output containing the keys in $enabled_fields.     $input = array_intersect_key($fieldsarray_flip($enabled_field_names));
    foreach ($input as $field_name => $field_value) {
      $public_field_name = $resource_type->getPublicName($field_name);
      $output[$public_field_name] = $field_value;
    }

    return $output;
  }

  public function getPublicName($field_name) {
    // By default the entity field name is the public field name.     return isset($this->fields[$field_name])
      ? $this->fields[$field_name]->getPublicName()
      : $field_name;
  }

  /** * Translates the public field name to the entity field name. * * This is only here so we can allow polymorphic implementations to take a * greater control on the field names. * * @return string * The internal field name as defined in the entity. */
\Drupal::state()->set('jsonapi_test_resource_type_builder.disabled_resource_types', $disabled_resource_types);
    Cache::invalidateTags(['jsonapi_resource_types']);
    $this->assertFalse($this->resourceTypeRepository->getByTypeName('node--article')->isInternal());
    $this->assertTrue($this->resourceTypeRepository->getByTypeName('node--page')->isInternal());
    $this->assertTrue($this->resourceTypeRepository->getByTypeName('user--user')->isInternal());
  }

  /** * Tests that resource type fields can be aliased per resource type. */
  public function testResourceTypeFieldAliasing() {
    $this->assertSame($this->resourceTypeRepository->getByTypeName('node--article')->getPublicName('uid'), 'uid');
    $this->assertSame($this->resourceTypeRepository->getByTypeName('node--page')->getPublicName('uid'), 'uid');
    $resource_type_field_aliases = [
      'node--article' => [
        'uid' => 'author',
      ],
      'node--page' => [
        'uid' => 'owner',
      ],
    ];
    \Drupal::state()->set('jsonapi_test_resource_type_builder.resource_type_field_aliases', $resource_type_field_aliases);
    Cache::invalidateTags(['jsonapi_resource_types']);
    
$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(
          
 new ResourceTypeRelationship($field_name$alias, TRUE, $has_one)
        : new ResourceTypeAttribute($field_name$alias, TRUE, $has_one);
    }

    // With all fields now aliased, detect any conflicts caused by the     // automatically generated aliases above.     foreach (array_intersect($reserved_field_namesarray_keys($fields)) as $reserved_field_name) {
      /** @var \Drupal\jsonapi\ResourceType\ResourceTypeField $aliased_reserved_field */
      $aliased_reserved_field = $fields[$reserved_field_name];
      /** @var \Drupal\jsonapi\ResourceType\ResourceTypeField $field */
      foreach (array_diff_key($fieldsarray_flip([$reserved_field_name])) as $field) {
        if ($aliased_reserved_field->getPublicName() === $field->getPublicName()) {
          throw new \LogicException("The generated alias '{$aliased_reserved_field->getPublicName()}' for field name '{$aliased_reserved_field->getInternalName()}' conflicts with an existing field. Please report this in the JSON:API issue queue!");
        }
      }
    }

    // Special handling for user entities that allows a JSON:API user agent to     // access the display name of a user. This is useful when displaying the     // name of a node's author.     // @see \Drupal\jsonapi\JsonApiResource\ResourceObject::extractContentEntityFields()     // @todo: eliminate this special casing in https://www.drupal.org/project/drupal/issues/3079254.     if ($entity_type->id() === 'user') {
      

  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);
      

  protected function resolveIncludeTree(array $include_tree, Data $data, Data $includes = NULL) {
    $includes = is_null($includes) ? new IncludedData([]) : $includes;
    foreach ($include_tree as $field_name => $children) {
      $references = [];
      foreach ($data as $resource_object) {
        // Some objects in the collection may be LabelOnlyResourceObjects or         // EntityAccessDeniedHttpException objects.         assert($resource_object instanceof ResourceIdentifierInterface);
        $public_field_name = $resource_object->getResourceType()->getPublicName($field_name);

        if ($resource_object instanceof LabelOnlyResourceObject) {
          $message = "The current user is not allowed to view this relationship.";
          $exception = new EntityAccessDeniedHttpException($resource_object->getEntity(), AccessResult::forbidden("The user only has authorization for the 'view label' operation."), '', $message$public_field_name);
          $includes = IncludedData::merge($includesnew IncludedData([$exception]));
          continue;
        }
        elseif (!$resource_object instanceof ResourceObject) {
          continue;
        }

        
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.",
            ],
          ],
        ],
      ];

  protected function setEntity(EntityInterface $entity) {
    $this->entity = $entity;
  }

  /** * {@inheritdoc} */
  protected static function extractFieldsFromEntity(ResourceType $resource_type, EntityInterface $entity) {
    $fields = parent::extractFieldsFromEntity($resource_type$entity);
    $public_label_field_name = $resource_type->getPublicName(static::getLabelFieldName($entity));
    return array_intersect_key($fields[$public_label_field_name => TRUE]);
  }

}

  protected function getRelationshipFieldNames(EntityInterface $entity = NULL) {
    $entity = $entity ?: $this->entity;
    // Only content entity types can have relationships.     $fields = $entity instanceof ContentEntityInterface
      ? iterator_to_array($entity)
      : [];
    return array_reduce($fieldsfunction D$field_names$field) {
      /** @var \Drupal\Core\Field\FieldItemListInterface $field */
      if (static::isReferenceFieldDefinition($field->getFieldDefinition())) {
        $field_names[] = $this->resourceType->getPublicName($field->getName());
      }
      return $field_names;
    }[]);
  }

  /** * Authorize the user under test with additional permissions to view includes. * * @return array * An array of special permissions to be granted for certain relationship * paths where the keys are relationships paths and values are an array of * permissions. */

  public static function createFromEntityReferenceField(ResourceObject $context, EntityReferenceFieldItemListInterface $field, LinkCollection $links = NULL, array $meta = []) {
    $context_resource_type = $context->getResourceType();
    $resource_field = $context_resource_type->getFieldByInternalName($field->getName());
    return new static(
      $resource_field->getPublicName(),
      new RelationshipData(ResourceIdentifier::toResourceIdentifiers($field)$resource_field->hasOne() ? 1 : -1),
      static::buildLinkCollectionFromEntityReferenceField($context$field$links ?: new LinkCollection([])),
      $meta,
      $context
    );
  }

  /** * Gets context resource object of the relationship. * * @return \Drupal\jsonapi\JsonApiResource\ResourceObject * The context ResourceObject. * * @see \Drupal\jsonapi\JsonApiResource\Relationship::$context */
'info' => [
        'href' => 'http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.1',
      ],
      'via' => ['href' => 'http://localhost/'],
    ]$normalized['errors'][0]['links']);
  }

  /** * Tests the message and exceptions when requesting a Label only resource. */
  public function testAliasFieldRouteException() {
    $this->assertSame('uid', $this->resourceTypeRepository->getByTypeName('node--article')->getPublicName('uid'));
    $this->assertSame('roles', $this->resourceTypeRepository->getByTypeName('user--user')->getPublicName('roles'));
    $resource_type_field_aliases = [
      'node--article' => [
        'uid' => 'author',
      ],
      'user--user' => [
        'roles' => 'user_roles',
      ],
    ];
    \Drupal::state()->set('jsonapi_test_resource_type_builder.resource_type_field_aliases', $resource_type_field_aliases);
    Cache::invalidateTags(['jsonapi_resource_types']);
    

  public function createIndividual(ResourceType $resource_type, Request $request) {
    $parsed_entity = $this->deserialize($resource_type$request, JsonApiDocumentTopLevel::class);

    if ($parsed_entity instanceof FieldableEntityInterface) {
      // Only check 'edit' permissions for fields that were actually submitted       // by the user. Field access makes no distinction between 'create' and       // 'update', so the 'edit' operation is used here.       $document = Json::decode($request->getContent());
      $field_mapping = array_map(function DResourceTypeField $field) {
        return $field->getPublicName();
      }$resource_type->getFields());
      // User resource objects contain a read-only attribute that is not a       // real field on the user entity type.       // @see \Drupal\jsonapi\JsonApiResource\ResourceObject::extractContentEntityFields()       // @todo: eliminate this special casing in https://www.drupal.org/project/drupal/issues/3079254.       if ($resource_type->getEntityTypeId() === 'user') {
        $field_mapping = array_diff($field_mapping[$resource_type->getPublicName('display_name')]);
      }
      foreach (['attributes', 'relationships'] as $data_member_name) {
        if (isset($document['data'][$data_member_name])) {
          foreach (array_intersect_key(array_flip($field_mapping)$document['data'][$data_member_name]) as $internal_field_name) {
            
if ($resource_type->getFieldByInternalName($file_field_name)->hasOne()) {
      $entity->{$file_field_name} = $file;
    }
    else {
      $entity->get($file_field_name)->appendItem($file);
    }
    static::validate($entity[$file_field_name]);
    $entity->save();

    $route_parameters = ['entity' => $entity->uuid()];
    $route_name = sprintf('jsonapi.%s.%s.related', $resource_type->getTypeName()$resource_type->getPublicName($file_field_name));
    $related_url = Url::fromRoute($route_name$route_parameters)->toString(TRUE);
    $request = Request::create($related_url->getGeneratedUrl(), 'GET', []$request->cookies->all()[]$request->server->all());
    return $this->httpKernel->handle($request, HttpKernelInterface::SUB_REQUEST);
  }

  /** * Handles JSON:API file upload requests. * * @param \Symfony\Component\HttpFoundation\Request $request * The HTTP request object. * @param \Drupal\jsonapi\ResourceType\ResourceType $resource_type * The JSON:API resource type for the current request. * @param string $file_field_name * The file field for which the file is to be uploaded. * * @return \Drupal\jsonapi\ResourceResponse * The response object. * * @throws \Symfony\Component\HttpKernel\Exception\UnprocessableEntityHttpException * Thrown when there are validation errors. */
Home | Imprint | This part of the site doesn't use cookies.