You are here

public function FileUpload::handleFileUploadForNewResource in JSON:API 8.2

Handles JSON:API file upload requests.

Parameters

\Symfony\Component\HttpFoundation\Request $request: The HTTP request object.

\Drupal\jsonapi\ResourceType\ResourceType $resource_type: The JSON:API resource type for the current request.

string $file_field_name: The file field for which the file is to be uploaded.

Return value

\Drupal\jsonapi\ResourceResponse The response object.

Throws

\Symfony\Component\HttpKernel\Exception\UnprocessableEntityHttpException Thrown when there are validation errors.

File

src/Controller/FileUpload.php, line 163

Class

FileUpload
Handles file upload requests.

Namespace

Drupal\jsonapi\Controller

Code

public function handleFileUploadForNewResource(Request $request, ResourceType $resource_type, $file_field_name) {
  $field_definition = $this
    ->validateAndLoadFieldDefinition($resource_type
    ->getEntityTypeId(), $resource_type
    ->getBundle(), $file_field_name);
  static::ensureFileUploadAccess($this->currentUser, $field_definition);
  $filename = $this->fileUploader
    ->validateAndParseContentDispositionHeader($request);
  $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 (ConstraintViolationInterface $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/jsonapi/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($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, []);
}