hasOne example

$file = $this->fileUploader->handleFileUploadForField($field_definition$filename$this->currentUser);

    if ($file instanceof EntityConstraintViolationListInterface) {
      $violations = $file;
      $message = "Unprocessable Entity: file validation failed.\n";
      $message .= implode("\n", array_map(function DConstraintViolationInterface $violation) {
        return PlainTextOutput::renderFromHtml($violation->getMessage());
      }(array) $violations->getIterator()));
      throw new UnprocessableEntityHttpException($message);
    }

    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);
    
$link_cacheability = new CacheableMetadata();
    $links = array_map(function DUrl $link) use ($link_cacheability) {
      $href = $link->setAbsolute()->toString(TRUE);
      $link_cacheability->addCacheableDependency($href);
      return ['href' => $href->getGeneratedUrl()];
    }static::getRelationshipLinks($context['resource_object']$resource_relationship));
    $data_normalization = $normalized_items->getNormalization();
    $normalization = [
      // Empty 'to-one' relationships must be NULL.       // Empty 'to-many' relationships must be an empty array.       // @link http://jsonapi.org/format/#document-resource-object-linkage       'data' => $resource_relationship->hasOne() ? array_shift($data_normalization) : $data_normalization,
    ];
    if (!empty($links)) {
      $normalization['links'] = $links;
    }
    return (new CacheableNormalization($normalized_items$normalization))->withCacheableDependency($link_cacheability);
  }

  /** * Gets the links for the relationship. * * @param \Drupal\jsonapi\JsonApiResource\ResourceObject $relationship_context * The JSON:API resource object context of the relationship. * @param \Drupal\jsonapi\ResourceType\ResourceTypeRelationship $resource_relationship * The resource type relationship field. * * @return array * The relationship's links. */
function DEntityInterface $entity) {
        return (bool) $this->resourceTypeRepository->get(
          $entity->getEntityTypeId(),
          $entity->bundle()
        );
      }
    );
    $collection_data = [];
    foreach ($referenced_entities as $referenced_entity) {
      $collection_data[] = $this->entityAccessChecker->getAccessCheckedResourceObject($referenced_entity);
    }
    $primary_data = new ResourceObjectData($collection_data$resource_relationship->hasOne() ? 1 : -1);
    $response = $this->buildWrappedResponse($primary_data$request$this->getIncludes($request$primary_data));

    // $response does not contain the entity list cache tag. We add the     // cacheable metadata for the finite list of entities in the relationship.     if ($response instanceof CacheableResponseInterface) {
      $response->addCacheableDependency($entity);
    }

    return $response;
  }

  

  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 */

class FieldNormalizer extends NormalizerBase implements DenormalizerInterface {

  /** * {@inheritdoc} */
  public function normalize($field$format = NULL, array $context = []): array|string|int|float|bool|\ArrayObject|NULL {
    /** @var \Drupal\Core\Field\FieldItemListInterface $field */
    $normalized_items = $this->normalizeFieldItems($field$format$context);
    assert($context['resource_object'] instanceof ResourceObject);
    return $context['resource_object']->getResourceType()->getFieldByInternalName($field->getName())->hasOne()
      ? array_shift($normalized_items) ?: CacheableNormalization::permanent(NULL)
      : CacheableNormalization::aggregate($normalized_items);
  }

  /** * {@inheritdoc} */
  public function denormalize($data$class$format = NULL, array $context = []): mixed {
    $field_definition = $context['field_definition'];
    assert($field_definition instanceof FieldDefinitionInterface);
    $resource_type = $context['resource_type'];
    
Home | Imprint | This part of the site doesn't use cookies.